Java Examples for javax.annotation.Nonnull
The following java examples will help you to understand the usage of javax.annotation.Nonnull. These source code samples are taken from different open source projects.
Example 1
| Project: android-calculatorpp-master File: ExpressionGeneratorWithInput.java View source code |
@Nonnull
public List<String> generate() {
final List<StringBuilder> expressions = new ArrayList<StringBuilder>();
for (String subExpression : subExpressions) {
expressions.add(new StringBuilder(subExpression));
}
int i = 0;
while (i < getDepth()) {
final Operation operation = generateOperation();
final Function function = generateFunction();
final boolean brackets = generateBrackets();
for (int j = 0; j < subExpressions.size(); j++) {
final StringBuilder expression = expressions.get(j);
expression.append(operation.getToken());
if (function == null) {
expression.append(subExpressions.get(j));
} else {
expression.append(function.getToken()).append("(").append(subExpressions.get(j)).append(")");
}
if (brackets) {
expressions.set(j, new StringBuilder("(").append(expression).append(")"));
}
}
i++;
}
final List<String> result = new ArrayList<String>();
for (StringBuilder expression : expressions) {
result.add(expression.toString());
}
return result;
}Example 2
| Project: artifactory-plugin-master File: ArtifactoryDSL.java View source code |
@Nonnull @Override public Object getValue(@Nonnull CpsScript cpsScript) throws Exception { Binding binding = cpsScript.getBinding(); Object artifactory; if (binding.hasVariable(getName())) { artifactory = binding.getVariable(getName()); } else { artifactory = new ArtifactoryPipelineGlobal(cpsScript); binding.setVariable(getName(), artifactory); } return artifactory; }
Example 3
| Project: matrix-project-plugin-master File: MatrixConfigurationSorterDescriptor.java View source code |
/**
* Returns all the registered {@link MatrixConfigurationSorterDescriptor}s.
*/
@Nonnull
public static DescriptorExtensionList<MatrixConfigurationSorter, MatrixConfigurationSorterDescriptor> all() {
final Jenkins jenkins = Jenkins.getInstance();
if (jenkins != null) {
return jenkins.<MatrixConfigurationSorter, MatrixConfigurationSorterDescriptor>getDescriptorList(MatrixConfigurationSorter.class);
} else {
return DescriptorExtensionList.createDescriptorList((Jenkins) null, MatrixConfigurationSorter.class);
}
}Example 4
| Project: robolectric-master File: SdkEnvironment.java View source code |
@Nonnull
private ResourcePath createRuntimeSdkResourcePath(DependencyResolver dependencyResolver) {
try {
Fs systemResFs = Fs.fromJar(dependencyResolver.getLocalArtifactUrl(sdkConfig.getAndroidSdkDependency()));
Class<?> androidRClass = getRobolectricClassLoader().loadClass("android.R");
Class<?> androidInternalRClass = getRobolectricClassLoader().loadClass("com.android.internal.R");
return new ResourcePath(androidRClass, systemResFs.join("res"), systemResFs.join("assets"), androidInternalRClass);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}Example 5
| Project: stash-master File: DefaultBuildStateMapper.java View source code |
@Nonnull
public BuildStatus getBuildStatus(AbstractBuild<?, ?> build) {
if (build.getResult() == null) {
return BuildStatus.INPROGRESS;
}
if (build.getResult().equals(Result.SUCCESS) || build.getResult().equals(Result.UNSTABLE)) {
return BuildStatus.SUCCESSFUL;
}
if (build.getResult().equals(Result.FAILURE) || build.getResult().equals(Result.ABORTED)) {
return BuildStatus.FAILED;
}
// Result.NOT_BUILT
return BuildStatus.INPROGRESS;
}Example 6
| Project: stashnotifier-plugin-master File: DefaultBuildStateMapper.java View source code |
@Nonnull
public BuildStatus getBuildStatus(AbstractBuild<?, ?> build) {
if (build.getResult() == null) {
return BuildStatus.INPROGRESS;
}
if (build.getResult().equals(Result.SUCCESS) || build.getResult().equals(Result.UNSTABLE)) {
return BuildStatus.SUCCESSFUL;
}
if (build.getResult().equals(Result.FAILURE) || build.getResult().equals(Result.ABORTED)) {
return BuildStatus.FAILED;
}
// Result.NOT_BUILT
return BuildStatus.INPROGRESS;
}Example 7
| Project: USB-Device-Info---Android-master File: Validation.java View source code |
public boolean isValidUsbDeviceCandidate(@Nonnull final File file) {
final boolean retVal;
if (!file.exists()) {
retVal = false;
} else if (!file.isDirectory()) {
retVal = false;
} else if (".".equals(file.getName()) || "..".equals(file.getName())) {
retVal = false;
} else {
retVal = true;
}
return retVal;
}Example 8
| Project: sonar-java-master File: ChangeMethodContractCheck.java View source code |
private void checkParameter(VariableTree parameter, Symbol overrideeParamSymbol) {
Tree reportTree = parameter;
if (nonNullVsNull(parameter.symbol(), overrideeParamSymbol)) {
for (AnnotationTree annotationTree : parameter.modifiers().annotations()) {
if (annotationTree.symbolType().is(JAVAX_ANNOTATION_NONNULL)) {
reportTree = annotationTree;
}
}
reportIssue(reportTree, "Remove this \"Nonnull\" annotation to honor the overridden method's contract.");
}
}Example 9
| Project: deadcode4j-master File: StaticLoggerBinder.java View source code |
/**
* Returns a <code>MavenPluginLoggerFactory</code> if the current thread was properly
* {@link #setLog(org.apache.maven.plugin.logging.Log) initialized}; an instance of
* <code>NOPLoggerFactory</code> otherwise.
*
* @since 1.5
*/
@Nonnull
@Override
public ILoggerFactory getLoggerFactory() {
ILoggerFactory loggerFactory = loggerFactoryForThread.get();
if (loggerFactory == null) {
Util.report("No Maven Log set; using NOPLoggerFactory! " + "Make sure to call StaticLoggerBinder.getSingleton().setLog(Log log)!");
loggerFactory = new NOPLoggerFactory();
}
return loggerFactory;
}Example 10
| Project: docker-slaves-plugin-master File: ContainerSpecEnvironmentContributor.java View source code |
@Override public void buildEnvironmentFor(@Nonnull Run r, @Nonnull EnvVars envs, @Nonnull TaskListener listener) throws IOException, InterruptedException { final Job job = r.getParent(); final ContainerSetDefinition property = (ContainerSetDefinition) job.getProperty(ContainerSetDefinition.class); if (property == null) return; property.getBuildHostImage().setupEnvironment(envs); for (SideContainerDefinition sidecar : property.getSideContainers()) { sidecar.getSpec().setupEnvironment(envs); } }
Example 11
| Project: email-ext-plugin-master File: RecipientProvider.java View source code |
public static void checkAllSupport(@Nonnull List<? extends RecipientProvider> providers, Class<? extends Job> clazz) {
Set<String> notSupported = new TreeSet<>();
for (RecipientProvider provider : providers) {
if (!provider.getDescriptor().isApplicable(clazz)) {
notSupported.add(provider.getClass().getName());
}
}
if (!notSupported.isEmpty()) {
throw new IllegalArgumentException(MessageFormat.format("The following recipient providers do not support {0} {1}", clazz.getName(), StringUtil.join(notSupported, ", ")));
}
}Example 12
| Project: fest-swing-1.x-master File: JToolBarIsFloatingQuery.java View source code |
@RunsInCurrentThread
static boolean isJToolBarFloating(@Nonnull JToolBar toolBar) {
ToolBarUI ui = toolBar.getUI();
if (ui instanceof BasicToolBarUI) {
return ((BasicToolBarUI) ui).isFloating();
}
// Have to guess; probably ought to check for sibling components
Window w = getWindowAncestor(toolBar);
return !(w instanceof Frame) && toolBar.getParent().getComponentCount() == 1;
}Example 13
| Project: griffon-master File: Config.java View source code |
@Override
protected void initialize(@Nonnull Map<String, Object> entries) {
map(entries).e("application", map().e("title", "${project_name}").e("startupGroups", asList("${project_property_name}")).e("autoShutdown", true)).e("mvcGroups", map().e("${project_property_name}", map().e("model", "${project_package}.${project_class_name}Model").e("view", "${project_package}.${project_class_name}View").e("controller", "${project_package}.${project_class_name}Controller")));
}Example 14
| Project: gwt-appcache-master File: LocalePropertyProvider.java View source code |
@Override
@Nullable
public String getPropertyValue(@Nonnull final HttpServletRequest request) {
final String queryString = request.getQueryString();
if (null != queryString) {
final String[] parts = queryString.split("&");
for (final String part : parts) {
final int index = part.indexOf('=');
if (-1 != index) {
final String key = part.substring(0, index);
if ("locale".equals(key)) {
return part.substring(index + 1);
}
}
}
}
final String language = request.getHeader("Accept-Language");
if (null != language) {
final String[] parts = language.split("[,\\;]");
return parts[0];
}
return "default";
}Example 15
| Project: ItemRenamer-master File: Components.java View source code |
/**
* Construct a registerable component of inner components.
* @param components - registerable components.
* @return The composite component.
*/
public static Component asComposite(final Component... components) {
return new AbstractComponent() {
@Override
protected void onRegistered(@Nonnull Plugin plugin, EventBus bus) {
for (Component registerable : components) {
registerable.register(plugin, bus);
}
}
@Override
protected void onUnregistered(@Nonnull Plugin plugin) {
for (Component registerable : components) {
registerable.unregister(plugin);
}
}
};
}Example 16
| Project: ItsJustaCharm-master File: RecipeMakerConstructionTable.java View source code |
@Nonnull
public static List<RecipeWrapperConstructionTable> getRecipes() {
ArrayList<RecipeWrapperConstructionTable> recipes = new ArrayList<RecipeWrapperConstructionTable>();
for (RecipeBaseConstructionTable recipe : ItsJustaCharmAPI.ConstructionTable.constructionTableRecipes) {
ItemStack output = recipe.getOutput();
Object[] gridInputs = recipe.getGridInputs();
Object[] secInputs = recipe.getSecInputs();
boolean shapeless = recipe instanceof RecipeShapelessConstructionTable;
RecipeWrapperConstructionTable jeiRecipe = new RecipeWrapperConstructionTable(output, gridInputs, secInputs, shapeless);
recipes.add(jeiRecipe);
}
return recipes;
}Example 17
| Project: javersion-master File: DefaultMappingResolver.java View source code |
@Nonnull
@Override
public <T extends StaticExecutable & ElementDescriptor> Result<StaticExecutable> creator(T methodOrConstructor) {
if (methodOrConstructor instanceof ConstructorDescriptor) {
ConstructorDescriptor constructor = (ConstructorDescriptor) methodOrConstructor;
if (constructor.getParameters().isEmpty()) {
return Result.of(constructor);
}
}
return Result.notFound();
}Example 18
| Project: jenkins-plugins-master File: PropertiesInstanceWhitelist.java View source code |
@Override public boolean permitsMethod(@Nonnull Method method, @Nonnull Object receiver, @Nonnull Object[] args) { if (permitsInstance(receiver) && isClass(method.getDeclaringClass())) { String name = method.getName(); return name.equals("setProperty") || name.equals("put") || name.equals("getProperty") || name.equals("get") || name.equals("propertyNames") || name.equals("stringPropertyNames") || name.equals("list"); } return false; }
Example 19
| Project: netbeans-mmd-plugin-master File: PsiExtraFileReferenceProvider.java View source code |
@Nonnull @Override public PsiReference[] getReferencesByElement(@Nonnull PsiElement element, @Nonnull ProcessingContext context) { PsiReference[] result = PsiReference.EMPTY_ARRAY; final PsiExtraFile extraFile = (PsiExtraFile) element; final VirtualFile targetFile = extraFile.findTargetFile(); if (targetFile != null) { final TextRange range = new TextRange(0, extraFile.getTextLength()); result = new PsiReference[] { new PsiExtraFileReference(extraFile, range) }; } return result; }
Example 20
| Project: nifty-gui-master File: ImageSlickRenderImageLoader.java View source code |
/** * Load the image. */ @Nonnull @Override public SlickRenderImage loadImage(final String filename, final boolean filterLinear) throws SlickLoadImageException { try { final int filter = filterLinear ? Image.FILTER_LINEAR : Image.FILTER_NEAREST; final Image image = new Image(filename, false, filter); return new ImageSlickRenderImage(image); } catch (@Nonnull final SlickException e) { throw new SlickLoadImageException("Loading the image \"" + filename + "\" failed.", e); } }
Example 21
| Project: Project-Zed-master File: JeiPlugin.java View source code |
@Override
public void register(@Nonnull IModRegistry registry) {
IJeiHelpers jeiHelpers = registry.getJeiHelpers();
IGuiHelper guiHelper = jeiHelpers.getGuiHelper();
FabricationTableRecipeTransferHandler.register(registry);
StoneCraftingTableRecipeTransferHandler.register(registry);
PatternEncoderRecipeTransferHandler.register(registry);
}Example 22
| Project: RxLifecycle-master File: TakeUntilGenerator.java View source code |
@Nonnull static <T> Observable<Boolean> takeUntilCorrespondingEvent(@Nonnull final Observable<T> lifecycle, @Nonnull final Func1<T, T> correspondingEvents) { return Observable.combineLatest(lifecycle.take(1).map(correspondingEvents), lifecycle.skip(1), new Func2<T, T, Boolean>() { @Override public Boolean call(T bindUntilEvent, T lifecycleEvent) { return lifecycleEvent.equals(bindUntilEvent); } }).onErrorReturn(Functions.RESUME_FUNCTION).takeFirst(Functions.SHOULD_COMPLETE); }
Example 23
| Project: Sone-master File: WebTestUtils.java View source code |
@Nonnull public static Matcher<RedirectException> redirectsTo(@Nonnull final String page) { return new TypeSafeDiagnosingMatcher<RedirectException>() { @Override protected boolean matchesSafely(RedirectException exception, Description mismatchDescription) { if (!exception.getTarget().equals(page)) { mismatchDescription.appendText("target is ").appendValue(exception.getTarget()); return false; } return true; } @Override public void describeTo(Description description) { description.appendText("target is ").appendValue(page); } }; }
Example 24
| Project: Store-master File: DontCacheErrorsTest.java View source code |
@Before
public void setUp() {
store = StoreBuilder.<Integer>barcode().fetcher(new Fetcher<Integer, BarCode>() {
@Nonnull
@Override
public Observable<Integer> fetch(@Nonnull BarCode barCode) {
return Observable.fromCallable(new Callable<Integer>() {
@Override
public Integer call() {
if (shouldThrow) {
throw new RuntimeException();
} else {
return 0;
}
}
});
}
}).open();
}Example 25
| Project: swagger-parser-master File: V11ApiDeclarationMigrator.java View source code |
@Nonnull @Override public JsonNode migrate(@Nonnull final JsonNode input) throws SwaggerMigrationException { final MutableJsonTree tree = new MutableJsonTree(input); tree.applyMigrator(membersToString("swaggerVersion", "apiVersion")); tree.applyMigrator(patchFromResource("/patches/v1.1/versionChange" + ".json")); tree.setPointer(JsonPointer.of("apis")); tree.applyMigratorToElements(migrator); return tree.getBaseNode(); }
Example 26
| Project: Tank-master File: FilterGroupDao.java View source code |
/**
* @param productName
* @return
*/
@Nonnull
public List<ScriptFilterGroup> getFilterGroupsForProduct(@Nonnull String productName) {
String prefix = "x";
NamedParameter parameter = new NamedParameter(ScriptFilterGroup.PROPERTY_PRODUCT_NAME, "productName", productName);
StringBuilder sb = new StringBuilder();
sb.append(buildQlSelect(prefix)).append(startWhere()).append(buildWhereClause(Operation.EQUALS, prefix, parameter));
return listWithJQL(sb.toString(), parameter);
}Example 27
| Project: TinkersConstruct-master File: CustomStateMap.java View source code |
@Nonnull @Override protected ModelResourceLocation getModelResourceLocation(@Nonnull IBlockState state) { LinkedHashMap<IProperty<?>, Comparable<?>> linkedhashmap = Maps.newLinkedHashMap(state.getProperties()); ResourceLocation res = new ResourceLocation(Block.REGISTRY.getNameForObject(state.getBlock()).getResourceDomain(), customName); return new ModelResourceLocation(res, this.getPropertyString(linkedhashmap)); }
Example 28
| Project: Abyss-master File: TransmutationRecipeMaker.java View source code |
@Nonnull
public static List<TransmutationRecipe> getTransmutatorRecipes(IJeiHelpers helpers) {
IStackHelper stackHelper = helpers.getStackHelper();
TransmutatorRecipes transmutatorRecipes = TransmutatorRecipes.instance();
Map<ItemStack, ItemStack> transmutationMap = getTransmutationMap(transmutatorRecipes);
List<TransmutationRecipe> recipes = new ArrayList<>();
for (Map.Entry<ItemStack, ItemStack> itemStackItemStackEntry : transmutationMap.entrySet()) {
ItemStack input = itemStackItemStackEntry.getKey();
ItemStack output = itemStackItemStackEntry.getValue();
float experience = transmutatorRecipes.getExperience(output);
List<ItemStack> inputs = stackHelper.getSubtypes(input);
TransmutationRecipe recipe = new TransmutationRecipe(inputs, output, experience);
recipes.add(recipe);
}
return recipes;
}Example 29
| Project: AbyssalCraft-master File: TransmutationRecipeMaker.java View source code |
@Nonnull
public static List<TransmutationRecipe> getTransmutatorRecipes(IJeiHelpers helpers) {
IStackHelper stackHelper = helpers.getStackHelper();
TransmutatorRecipes transmutatorRecipes = TransmutatorRecipes.instance();
Map<ItemStack, ItemStack> transmutationMap = getTransmutationMap(transmutatorRecipes);
List<TransmutationRecipe> recipes = new ArrayList<>();
for (Map.Entry<ItemStack, ItemStack> itemStackItemStackEntry : transmutationMap.entrySet()) {
ItemStack input = itemStackItemStackEntry.getKey();
ItemStack output = itemStackItemStackEntry.getValue();
float experience = transmutatorRecipes.getExperience(output);
List<ItemStack> inputs = stackHelper.getSubtypes(input);
TransmutationRecipe recipe = new TransmutationRecipe(inputs, output, experience);
recipes.add(recipe);
}
return recipes;
}Example 30
| Project: ADirStat-master File: FileUtils.java View source code |
@SneakyThrows
public static Optional<String> getMimeType(@Nonnull File file) {
if (file.isDirectory())
return Optional.of(DIRECTORY_MIMETYPE);
try {
Optional<String> possibleMimeType = Optional.fromNullable(guessContentTypeFromName(file.getAbsolutePath()));
if (!possibleMimeType.isPresent()) {
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
possibleMimeType = Optional.fromNullable(guessContentTypeFromStream(inputStream));
} catch (IOException e) {
return Optional.absent();
} finally {
if (inputStream != null)
inputStream.close();
}
}
return possibleMimeType;
} catch (StringIndexOutOfBoundsException ignored) {
return Optional.absent();
}
}Example 31
| Project: allure-bamboo-plugin-master File: AllureExecutable.java View source code |
@Nonnull
AllureGenerateResult generate(Path sourceDir, Path targetDir) {
try {
final LinkedList<String> args = new LinkedList<>(asList("generate", "-o", targetDir.toString(), sourceDir.toString()));
String output;
if (cmdLine.isUnix() && cmdLine.hasCommand(BASH_CMD)) {
args.addFirst(cmdPath.toString());
output = cmdLine.runCommand("/bin/bash", args.toArray(new String[args.size()]));
} else {
output = cmdLine.runCommand(cmdPath.toString(), args.toArray(new String[args.size()]));
}
LOGGER.info(output);
return cmdLine.parseGenerateOutput(output);
} catch (Exception e) {
throw new RuntimeException("Failed to generate allure report", e);
}
}Example 32
| Project: analysis-core-plugin-master File: Compatibility.java View source code |
private static Method getMethod(@Nonnull Class clazz, @Nonnull String methodName, @Nonnull Class... types) throws NoSuchMethodException { Method res = null; try { res = clazz.getDeclaredMethod(methodName, types); } catch (NoSuchMethodException e) { Class superclass = clazz.getSuperclass(); if (superclass != null) { res = getMethod(superclass, methodName, types); } } catch (SecurityException e) { throw new AssertionError(e); } if (res == null) { throw new NoSuchMethodException("Method " + methodName + " not found in " + clazz.getName()); } return res; }
Example 33
| Project: android-checkout-master File: PurchaseRequest.java View source code |
@Override void start(@Nonnull IInAppBillingService service, @Nonnull String packageName) throws RemoteException, RequestException { final Bundle bundle = service.getBuyIntent(mApiVersion, packageName, mSku, mProduct, mPayload == null ? "" : mPayload); if (handleError(bundle)) { return; } final PendingIntent pendingIntent = bundle.getParcelable("BUY_INTENT"); Check.isNotNull(pendingIntent); onSuccess(pendingIntent); }
Example 34
| Project: android-messengerpp-master File: JsonUserConverter.java View source code |
@Nonnull @Override public List<User> convert(@Nonnull String json) { final JsonUsers jsonUsersResult = newFromJson(json); final List<JsonUser> jsonUsers = jsonUsersResult.getUsers(); return newArrayList(transform(jsonUsers, new Function<JsonUser, User>() { @Override public User apply(JsonUser jsonUser) { try { return jsonUser.toUser(account); } catch (IllegalJsonException e) { throw new IllegalJsonRuntimeException(e); } } })); }
Example 35
| Project: baigan-config-master File: EtcdConfigurationRepository.java View source code |
@Nonnull public Optional<Configuration> get(@Nonnull final String key) { try { checkArgument(!Strings.isNullOrEmpty(key), "Attempt to get configuration for an empty key !"); final Optional<String> optionalConfig = etcdClient.get(CONFIG_PATH_PREFIX + key); if (optionalConfig.isPresent()) { return Optional.of(objectMapper.readValue(optionalConfig.get(), Configuration.class)); } } catch (IOException e) { LOG.warn("Error while loading configuration for key: " + key, e); } return Optional.empty(); }
Example 36
| Project: bgpcep-master File: PCCServerPeerProposal.java View source code |
@Override public void setPeerSpecificProposal(@Nonnull final InetSocketAddress address, @Nonnull final TlvsBuilder openBuilder) { Preconditions.checkNotNull(address); final LspDbVersionBuilder lspDbVersionBuilder = new LspDbVersionBuilder(); if (this.isAfterReconnection) { lspDbVersionBuilder.setLspDbVersionValue(this.dbVersion); } else { this.isAfterReconnection = true; } openBuilder.addAugmentation(Tlvs3.class, new Tlvs3Builder().setLspDbVersion(lspDbVersionBuilder.build()).build()); }
Example 37
| Project: com.cedarsoft.serialization-master File: BitSetSerializer.java View source code |
@Nonnull @Override public BitSet deserialize(@Nonnull JsonParser deserializeFrom, @Nonnull Version formatVersion) throws IOException, VersionException, SerializationException, JsonProcessingException { BitSet bitSet = new BitSet(); JacksonParserWrapper parserWrapper = new JacksonParserWrapper(deserializeFrom); while (parserWrapper.nextToken() != JsonToken.END_ARRAY) { Number value = parserWrapper.getNumberValue(); bitSet.set(value.intValue()); } return bitSet; }
Example 38
| Project: controller-master File: NormalizedNodeInputOutput.java View source code |
public static NormalizedNodeDataInput newDataInput(@Nonnull final DataInput input) throws IOException {
final byte marker = input.readByte();
if (marker != TokenTypes.SIGNATURE_MARKER) {
throw new InvalidNormalizedNodeStreamException(String.format("Invalid signature marker: %d", marker));
}
final short version = input.readShort();
switch(version) {
case TokenTypes.LITHIUM_VERSION:
return new NormalizedNodeInputStreamReader(input, true);
default:
throw new InvalidNormalizedNodeStreamException(String.format("Unhandled stream version %s", version));
}
}Example 39
| Project: CorfuDB-master File: ReadWaitHoleFillPolicy.java View source code |
/** {@inheritDoc} */
@Nonnull
@Override
public ILogData peekUntilHoleFillRequired(long address, Function<Long, ILogData> peekFunction) throws HoleFillRequiredException {
int tryNum = 0;
do {
// If this is not the first try, sleep before trying again
if (tryNum != 0) {
try {
Thread.sleep(waitMs);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// Try the read
ILogData data = peekFunction.apply(address);
// If it was not null, we can return it.
if (data != null) {
return data;
}
// Otherwise increment the counter and try again.
tryNum++;
} while (numRetries > tryNum);
throw new HoleFillRequiredException("No data after " + tryNum + " retries");
}Example 40
| Project: coverity-sonar-plugin-master File: CIMClientFactory.java View source code |
public CIMClient create(@Nonnull Settings settings) {
Validate.notNull(settings);
String host = settings.getString(CoverityPlugin.COVERITY_CONNECT_HOSTNAME);
int port = settings.getInt(CoverityPlugin.COVERITY_CONNECT_PORT);
String user = settings.getString(CoverityPlugin.COVERITY_CONNECT_USERNAME);
String password = settings.getString(CoverityPlugin.COVERITY_CONNECT_PASSWORD);
boolean ssl = settings.getBoolean(CoverityPlugin.COVERITY_CONNECT_SSL);
return new CIMClient(host, port, user, password, ssl);
}Example 41
| Project: DLect-master File: UpdateCheckingHelper.java View source code |
public void doUpdate(@Nonnull UpdateStyle us) throws UpdateException {
boolean update = updateChecker.isUpdateAvaliable(mc.getDatabaseHandler().getSetting(CommonSettingNames.PROVIDER_CODE), mc.getDatabaseHandler().getSetting(CommonSettingNames.UUID), mc.getDatabaseHandler().getSetting(CommonSettingNames.BBID));
if (update) {
updateExecutor.executeUpdate(us);
}
}Example 42
| Project: FindBug-for-Domino-Designer-master File: PathElementLabelProvider.java View source code |
@Nonnull
public String getToolTip(Object element) {
if (!(element instanceof IPathElement)) {
return "";
}
IPathElement pathElement = (IPathElement) element;
IStatus status = pathElement.getStatus();
if (status == null || status.isOK()) {
return pathElement.toString();
}
return status.getMessage();
}Example 43
| Project: Flaxbeards-Steam-Power-master File: ItemMultiplicativeResonatorUpgrade.java View source code |
@Override public void onPlayerHarvestDropsWithTool(BlockEvent.HarvestDropsEvent event, @Nonnull ItemStack toolStack, @Nonnull ItemStack thisUpgradeStack) { BlockPos pos = event.getPos(); EntityPlayer player = event.getHarvester(); World world = event.getWorld(); IBlockState state = event.getState(); Block block = state.getBlock(); event.getDrops().clear(); event.getDrops().addAll(block.getDrops(world, pos, state, EnchantmentUtility.getFortuneModifier(player) + 2)); }
Example 44
| Project: fullstop-master File: Repositories.java View source code |
Repository parse(@Nonnull String url) throws UnknownScmUrlException {
final String lowerCaseUrl = url.toLowerCase();
final Matcher matcher = pattern.matcher(lowerCaseUrl);
if (matcher.matches()) {
return new Repository(matcher.group("host"), matcher.group("owner"), matcher.group("name"));
} else {
throw new UnknownScmUrlException(url);
}
}Example 45
| Project: Galacticraft-master File: Tier2RocketRecipeHandler.java View source code |
@Override
public boolean isRecipeValid(@Nonnull Tier2RocketRecipeWrapper recipe) {
if (recipe.getInputs().size() != 21) {
GCLog.severe(this.getClass().getSimpleName() + " JEI recipe has wrong number of inputs!");
}
if (recipe.getOutputs().size() != 1) {
GCLog.severe(this.getClass().getSimpleName() + " JEI recipe has wrong number of outputs!");
}
return true;
}Example 46
| Project: github-plugin-master File: BuildDataHelper.java View source code |
/**
* Gets SHA1 from the build.
*
* @param build
*
* @return SHA1 of the las
* @throws IOException Cannot get the info about commit ID
*/
@Nonnull
public static ObjectId getCommitSHA1(@Nonnull Run<?, ?> build) throws IOException {
BuildData buildData = build.getAction(BuildData.class);
if (buildData == null) {
throw new IOException(Messages.BuildDataHelper_NoBuildDataError());
}
// buildData?.lastBuild?.marked and fall back to .revision with null check everywhere to be defensive
Build b = buildData.lastBuild;
if (b != null) {
Revision r = b.marked;
if (r == null) {
r = b.revision;
}
if (r != null) {
return r.getSha1();
}
}
// Nowhere to report => fail the build
throw new IOException(Messages.BuildDataHelper_NoLastRevisionError());
}Example 47
| Project: Harvest-Festival-master File: HFCommandTool.java View source code |
@Override public void execute(@Nonnull MinecraftServer server, @Nonnull ICommandSender sender, @Nonnull String[] parameters) throws CommandException { if (parameters.length == 1 || parameters.length == 2) { double level = Double.parseDouble(parameters[parameters.length - 1]); EntityPlayerMP player = parameters.length == 1 ? CommandBase.getCommandSenderAsPlayer(sender) : CommandBase.getPlayer(server, sender, parameters[0]); if (!applyLevel(player.getHeldItemOffhand(), level)) applyLevel(player.getHeldItemMainhand(), level); } else throw new WrongUsageException(getCommandUsage(sender)); }
Example 48
| Project: hello-world-master File: TcFreemarkerRender.java View source code |
@SneakyThrows public String render(@Nonnull String templatePath, @Nonnull Map<String, Object> params) { checkNotNull(freeMarkerConfigurer); checkNotNull(templatePath); checkNotNull(params); Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templatePath); try (StringWriter stringWriter = new StringWriter()) { template.process(params, stringWriter); log.info("render template [{}]", templatePath); return stringWriter.toString(); } }
Example 49
| Project: hideyoshi-master File: DownloadUrlFinder.java View source code |
@Nonnull
String findDownloadUrl(Version version, OperatingSystem system) throws IOException {
checkNotNull(version);
try (InputStream urlInfo = version.loadUrlInformation()) {
if (urlInfo == null) {
throw new IllegalArgumentException("specified version (" + version + ") is not supported yet.");
}
Properties urlInfoProperty = new Properties();
urlInfoProperty.load(urlInfo);
String key = String.format("javaee.%s.%d", system.getName(), system.getBits());
String downloadUrl = urlInfoProperty.getProperty(key);
if (Strings.isNullOrEmpty(downloadUrl)) {
throw new UnsupportedOperationException("download URL for specified version (" + version + ") is unknown");
}
return downloadUrl;
}
}Example 50
| Project: hydra-master File: SuppressChanges.java View source code |
public boolean suppress(@Nonnull String oldMessage, @Nonnull String newMessage) { switch(this) { case TRUE: return true; case FALSE: return false; case NEWLINE: { int oldLines = StringUtils.countMatches(oldMessage, "\n"); int newLines = StringUtils.countMatches(newMessage, "\n"); return (oldLines == newLines); } default: throw new IllegalStateException("unknown value " + this); } }
Example 51
| Project: jersey-metrics-filter-master File: ResourceMetricNamerImpl.java View source code |
@Nonnull
@Override
public String getMetricBaseName(AbstractResourceMethod am) {
String metricId = getPathWithoutSurroundingSlashes(am.getResource().getPath());
if (!metricId.isEmpty()) {
metricId = "/" + metricId;
}
String httpMethod;
if (am instanceof AbstractSubResourceMethod) {
// if this is a subresource, add on the subresource's path component
AbstractSubResourceMethod asrm = (AbstractSubResourceMethod) am;
metricId += "/" + getPathWithoutSurroundingSlashes(asrm.getPath());
httpMethod = asrm.getHttpMethod();
} else {
httpMethod = am.getHttpMethod();
}
if (metricId.isEmpty()) {
// this happens for WadlResource -- that case actually exists at "application.wadl" though
metricId = "_no path_";
}
metricId += " " + httpMethod;
return metricId;
}Example 52
| Project: jersey-new-relic-master File: ResourceTransactionNamerImpl.java View source code |
@Override
@Nonnull
public String getTransactionName(AbstractResourceMethod am) {
String transactionName = getPathWithoutSurroundingSlashes(am.getResource().getPath());
if (!transactionName.isEmpty()) {
transactionName = "/" + transactionName;
}
String httpMethod;
if (am instanceof AbstractSubResourceMethod) {
// if this is a subresource, add on the subresource's path component
AbstractSubResourceMethod asrm = (AbstractSubResourceMethod) am;
transactionName += "/" + getPathWithoutSurroundingSlashes(asrm.getPath());
httpMethod = asrm.getHttpMethod();
} else {
httpMethod = am.getHttpMethod();
}
if (transactionName.isEmpty()) {
// this happens for WadlResource -- that case actually exists at "application.wadl" though
transactionName = "(no path)";
}
transactionName += " " + httpMethod;
return transactionName;
}Example 53
| Project: JodaEngine-master File: BpmnEndEventActivity.java View source code |
@Override
protected void executeIntern(@Nonnull AbstractToken token) {
// as this token has finished, it is removed from the instance, because it is not needed anymore.
token.getInstance().removeToken(token);
if (!token.getInstance().hasAssignedTokens()) {
// there are no tokens assigned to this instance any longer, so it has finished (as the parameter tokens was
// the last one).
token.getNavigator().signalEndedProcessInstance(token.getInstance());
}
// logger.info("Completed Process", token.getID());
// TODO Add persistence for process context variables, if we have a method for persistence.
}Example 54
| Project: Koloboke-master File: CommonSetOps.java View source code |
public static boolean equals(@Nonnull Set<?> set, Object obj) {
if (set == obj)
return true;
if (!(obj instanceof Set))
return false;
Set<?> another = (Set<?>) obj;
if (another.size() != set.size())
return false;
try {
return set.containsAll(another);
} catch (ClassCastException e) {
return false;
} catch (NullPointerException e) {
return false;
}
}Example 55
| Project: MineMenu-master File: ItemStackSerializer.java View source code |
@Override
@Nonnull
public ItemStack deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (!json.isJsonObject()) {
return ItemStack.EMPTY;
}
String name = "";
int damage = 0;
for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
String key = entry.getKey();
JsonElement element = entry.getValue();
if (key.equals("name")) {
name = element.getAsString();
} else if (key.equals("damage")) {
damage = element.getAsInt();
}
}
return name.isEmpty() ? ItemStack.EMPTY : new ItemStack(Item.REGISTRY.getObject(new ResourceLocation(name)), 1, damage);
}Example 56
| Project: MoarSigns-master File: MoarSignsRecipeHandlerBase.java View source code |
@Override
public boolean isRecipeValid(@Nonnull T recipe) {
if (recipe.getRecipeOutput() == null) {
return false;
}
int inputCount = 0;
for (Object input : recipe.getInput()) {
if (input instanceof List) {
if (((List) input).size() == 0) {
return false;
}
}
if (input instanceof MaterialInfo) {
if (((MaterialInfo) input).materialName == null || ((MaterialInfo) input).materialName.isEmpty()) {
return false;
}
}
if (input != null) {
inputCount++;
}
}
return inputCount > 0;
}Example 57
| Project: Mvc4j-master File: RazorCommentCodeGenerator.java View source code |
@Override public void generateStartBlockCode(@Nonnull final Block target, @Nonnull final CodeGeneratorContext context) { // Flush the buffered statement since we're interrupting it with a comment. if (!Strings.isNullOrEmpty(context.getCurrentBufferedStatement())) { context.markEndOfGeneratedCode(); context.bufferStatementFragment(context.buildCodeString(CodeWriter::writeLineContinuation)); } context.flushBufferedStatement(); }
Example 58
| Project: myria-master File: RoundRobinPartitionFunction.java View source code |
@Override
public TupleBatch[] partition(@Nonnull final TupleBatch tb) {
BitSet[] partitions = new BitSet[numPartitions()];
for (int i = 0; i < partitions.length; ++i) {
partitions[i] = new BitSet();
}
for (int i = 0; i < tb.numTuples(); i++) {
partitions[curPartition].set(i);
curPartition = (curPartition + 1) % numPartitions();
}
TupleBatch[] tbs = new TupleBatch[numPartitions()];
for (int i = 0; i < tbs.length; ++i) {
tbs[i] = tb.filter(partitions[i]);
}
return tbs;
}Example 59
| Project: Natura-master File: CustomStateMap.java View source code |
@Nonnull @Override protected ModelResourceLocation getModelResourceLocation(@Nonnull IBlockState state) { LinkedHashMap<IProperty<?>, Comparable<?>> linkedhashmap = Maps.newLinkedHashMap(state.getProperties()); ResourceLocation res = new ResourceLocation(Block.REGISTRY.getNameForObject(state.getBlock()).getResourceDomain(), this.customName); return new ModelResourceLocation(res, this.getPropertyString(linkedhashmap)); }
Example 60
| Project: nextprot-api-master File: ProteomicsPageDisplayPredicate.java View source code |
@Nonnull
@Override
protected List<AnnotationCategory> getFeatureCategoryWhiteList() {
return Arrays.asList(AnnotationCategory.MATURATION_PEPTIDE, AnnotationCategory.MATURE_PROTEIN, AnnotationCategory.INITIATOR_METHIONINE, AnnotationCategory.SIGNAL_PEPTIDE, AnnotationCategory.TRANSIT_PEPTIDE, AnnotationCategory.DISULFIDE_BOND, AnnotationCategory.MODIFIED_RESIDUE, AnnotationCategory.CROSS_LINK, AnnotationCategory.GLYCOSYLATION_SITE, AnnotationCategory.LIPIDATION_SITE, AnnotationCategory.SELENOCYSTEINE);
}Example 61
| Project: nodejs-plugin-master File: FixEnvVarEnvironmentContributor.java View source code |
@Override
public void buildEnvironmentFor(@SuppressWarnings("rawtypes") @Nonnull Run run, @Nonnull EnvVars envs, @Nonnull TaskListener listener) throws IOException, InterruptedException {
Computer c = Computer.currentComputer();
if (c != null) {
Field platformField = ReflectionUtils.findField(EnvVars.class, "platform", Platform.class);
ReflectionUtils.makeAccessible(platformField);
Platform currentPlatform = (Platform) ReflectionUtils.getField(platformField, envs);
if (currentPlatform == null) {
// try to fix value with than one that comes from current computer
EnvVars remoteEnv = c.getEnvironment();
Platform computerPlatform = (Platform) ReflectionUtils.getField(platformField, remoteEnv);
if (computerPlatform != null) {
ReflectionUtils.setField(platformField, envs, computerPlatform);
}
}
}
}Example 62
| Project: Oilcraft-master File: OilCraftPlugin.java View source code |
@Override
public void register(@Nonnull IModRegistry registry) {
jeiHelper = registry.getJeiHelpers();
IGuiHelper guiHelper = jeiHelper.getGuiHelper();
registry.addRecipeCategories(new OilCompressorRecipeCategory(guiHelper));
registry.addRecipeHandlers(new OilCompressorRecipeHandler());
registry.addRecipeCategoryCraftingItem(new ItemStack(OCBlockRegistry.OIL_COMPRESSOR), ModInfo.ID + ":oil_compressor");
registry.addRecipeCategoryCraftingItem(new ItemStack(OCBlockRegistry.OIL_FURNACE), VanillaRecipeCategoryUid.SMELTING);
registry.addRecipes(OilCompressorRecipeMaker.getRecipes());
registry.addRecipeClickArea(GuiOilCompressor.class, 31, 34, 18, 21, ModInfo.ID + ":oil_compressor");
}Example 63
| Project: oryx-engine-master File: BpmnEndEventActivity.java View source code |
@Override
protected void executeIntern(@Nonnull AbstractToken token) {
// as this token has finished, it is removed from the instance, because it is not needed anymore.
token.getInstance().removeToken(token);
if (!token.getInstance().hasAssignedTokens()) {
// there are no tokens assigned to this instance any longer, so it has finished (as the parameter tokens was
// the last one).
token.getNavigator().signalEndedProcessInstance(token.getInstance());
}
// logger.info("Completed Process", token.getID());
// TODO Add persistence for process context variables, if we have a method for persistence.
}Example 64
| Project: ParallelGit-master File: GfsPathMatcher.java View source code |
@Nonnull
public static GfsPathMatcher newMatcher(String syntax, String pattern) {
String expr;
if (syntax.equals(GLOB_SYNTAX)) {
expr = GitGlobs.toRegexPattern(pattern);
} else {
if (syntax.equals(REGEX_SYNTAX))
expr = pattern;
else
throw new UnsupportedOperationException("Syntax '" + syntax + "' not recognized");
}
return newMatcher(Pattern.compile(expr));
}Example 65
| Project: performance-plugin-master File: PerfTestDSLVariable.java View source code |
@Nonnull @Override public Object getValue(@Nonnull CpsScript script) throws Exception { Binding binding = script.getBinding(); CpsThread c = CpsThread.current(); if (c == null) throw new IllegalStateException("Expected to be called from CpsThread"); ClassLoader cl = getClass().getClassLoader(); String scriptPath = "hudson/plugins/performance/dsl/" + getName() + ".groovy"; Reader r = new InputStreamReader(cl.getResourceAsStream(scriptPath), "UTF-8"); GroovyCodeSource gsc = new GroovyCodeSource(r, getName() + ".groovy", cl.getResource(scriptPath).getFile()); gsc.setCachable(true); Object pipelineDSL = c.getExecution().getShell().getClassLoader().parseClass(gsc).newInstance(); binding.setVariable(getName(), pipelineDSL); r.close(); return pipelineDSL; }
Example 66
| Project: plexus-io-master File: FlattenFileMapper.java View source code |
@Nonnull public String getMappedFileName(@Nonnull String pName) { // Check for null, etc. String name = super.getMappedFileName(pName); int offset = pName.lastIndexOf('/'); if (offset >= 0) { name = name.substring(offset + 1); } offset = pName.lastIndexOf('\\'); if (offset >= 0) { name = name.substring(offset + 1); } return name; }
Example 67
| Project: ProjectAres-master File: RemoveIndexTransformation.java View source code |
@Override @Nonnull public RotationState apply(@Nonnull RotationState state) { Preconditions.checkNotNull(state, "rotation state"); if (state.getMaps().size() > 1 && this.index < state.getMaps().size()) { List<PGMMap> maps = Lists.newArrayList(state.getMaps()); maps.remove(this.index); int nextId = state.getNextId(); if (nextId >= maps.size()) { nextId = 0; } else if (this.index < nextId) { nextId--; } return new RotationState(maps, nextId); } return state; }
Example 68
| Project: reasm-m68k-master File: GeneralPurposeRegister.java View source code |
@CheckForNull
static GeneralPurposeRegister identify(@Nonnull String identifier) {
if (identifier.length() == 2) {
final char ch = identifier.charAt(0);
final boolean isDataRegister = equalsAsciiCaseInsensitive(ch, 'D');
if (isDataRegister || equalsAsciiCaseInsensitive(ch, 'A')) {
final int registerNumber = parseRegisterNumber(identifier.charAt(1));
if (registerNumber != -1) {
return VALUES[(isDataRegister ? 0 : 8) | registerNumber];
}
} else if (equalsAsciiCaseInsensitive(ch, 'S')) {
if (equalsAsciiCaseInsensitive(identifier.charAt(1), 'P')) {
return A7;
}
}
}
return null;
}Example 69
| Project: redwood-master File: CustomStateMap.java View source code |
@Nonnull @Override protected ModelResourceLocation getModelResourceLocation(@Nonnull IBlockState state) { LinkedHashMap<IProperty<?>, Comparable<?>> linkedhashmap = Maps.newLinkedHashMap(state.getProperties()); ResourceLocation res = new ResourceLocation(Block.REGISTRY.getNameForObject(state.getBlock()).getResourceDomain(), this.customName); return new ModelResourceLocation(res, this.getPropertyString(linkedhashmap)); }
Example 70
| Project: shibboleth-idp-ext-cas-master File: ProxyGrantingTicketSerializer.java View source code |
@Override
@NotEmpty
protected String[] extractFields(@Nonnull final ProxyGrantingTicket ticket) {
final ArrayList<String> fields = new ArrayList<String>(4);
fields.add(ticket.getSessionId());
fields.add(ticket.getService());
fields.add(String.valueOf(ticket.getExpirationInstant().getMillis()));
if (ticket.getParentId() != null) {
fields.add(ticket.getParentId());
}
return fields.toArray(new String[fields.size()]);
}Example 71
| Project: simple-bitbucket-commit-checker-master File: ConfigValidator.java View source code |
@Override public void validate(@Nonnull Settings settings, @Nonnull SettingsValidationErrors errors, @Nonnull Repository repository) { try { SbccRenderer sbccRenderer = new SbccRenderer(this.authenticationContext); final SbccSettings sbccSettings = sscSettings(new RenderingSettings(settings, sbccRenderer)); logger.fine("Validating:\n" + sbccSettings.toString()); } catch (final ValidationException e) { errors.addFieldError(e.getField(), e.getError()); } }
Example 72
| Project: simple-java-mail-master File: OutlookMessageParser.java View source code |
@Nonnull public static OutlookMessage parseOutlookMsg(@Nonnull final File msgFile) { checkNonEmptyArgument(msgFile, "msgFile"); try { return new org.simplejavamail.outlookmessageparser.OutlookMessageParser().parseMsg(msgFile); } catch (final IOException e) { throw new OutlookMessageException(OutlookMessageException.ERROR_PARSING_OUTLOOK_MSG, e); } }
Example 73
| Project: stash-plugin-master File: StashAditionalParameterEnvironmentContributor.java View source code |
@Override public void buildEnvironmentFor(@Nonnull Run r, @Nonnull EnvVars envs, @Nonnull TaskListener listener) throws IOException, InterruptedException { StashCause cause = (StashCause) r.getCause(StashCause.class); if (cause == null) { return; } ParametersAction pa = r.getAction(ParametersAction.class); for (String param : params) { addParameter(param, pa, envs); } super.buildEnvironmentFor(r, envs, listener); }
Example 74
| Project: SupaCommons-master File: VectorSerializer.java View source code |
@Nullable @Override public Vector deserialize(@Nullable Object serialized, @Nonnull Class wantedType, @Nonnull SerializerSet serializerSet) { if (serialized == null) { return null; } checkNotNullOrEmpty(serialized.toString(), "serialized string"); String[] split = PATTERN.split(serialized.toString(), 4); checkArgument(split.length == 3, "string is in an invalid format."); return new Vector(Double.parseDouble(split[0]), Double.parseDouble(split[1]), Double.parseDouble(split[2])); }
Example 75
| Project: AgriCraft-master File: AgriCraftJEIPlugin.java View source code |
@Override
public void register(@Nonnull IModRegistry registry) {
registry.addRecipeCategories(new MutationRecipeCategory(registry.getJeiHelpers().getGuiHelper()), new ProduceRecipeCategory(registry.getJeiHelpers().getGuiHelper()));
registry.addRecipeHandlers(new MutationRecipeHandler(), new ProduceRecipeHandler());
registry.addRecipeCategoryCraftingItem(new ItemStack(AgriItems.getInstance().CROPS), CATEGORY_MUTATION, CATEGORY_PRODUCE);
}Example 76
| Project: apollo-android-master File: GitHuntApplication.java View source code |
@Nonnull @Override public CacheKey fromFieldRecordSet(@Nonnull Field field, @Nonnull Map<String, Object> map) { String typeName = (String) map.get("__typename"); if ("User".equals(typeName)) { String userKey = typeName + "." + map.get("login"); return CacheKey.from(userKey); } if (map.containsKey("id")) { String typeNameAndIDKey = map.get("__typename") + "." + map.get("id"); return CacheKey.from(typeNameAndIDKey); } return CacheKey.NO_KEY; }
Example 77
| Project: Applied-Energistics-2-master File: ConfigLoader.java View source code |
@Override
public BufferedReader getFile(@Nonnull final String relativeFilePath) throws Exception {
Preconditions.checkNotNull(relativeFilePath);
Preconditions.checkArgument(!relativeFilePath.isEmpty(), "Supplying an empty String will result creating a reader of a folder.");
final File generatedFile = new File(this.generatedRecipesDir, relativeFilePath);
final File userFile = new File(this.userRecipesDir, relativeFilePath);
final File toBeLoaded = (userFile.exists() && userFile.isFile()) ? userFile : generatedFile;
return new BufferedReader(new InputStreamReader(new FileInputStream(toBeLoaded), "UTF-8"));
}Example 78
| Project: approval-master File: GraphConverter.java View source code |
@Nonnull
@Override
protected String getStringForm(Graph value) {
StringBuilder statementsInDotFormat = new StringBuilder();
for (Statement statement : value) {
statementsInDotFormat.append(String.format("\t\"<%s>\" -> \"<%s>\" [label=\"%s\"];%n", statement.getSubject().stringValue(), statement.getObject().stringValue(), statement.getPredicate().stringValue()));
}
return String.format("digraph graphName {%n%s}%n", statementsInDotFormat);
}Example 79
| Project: as2-lib-master File: AS2ServletPartnershipFactory.java View source code |
@Override
protected void onBeforeAddPartnership(@Nonnull final Partnership aPartnership) throws OpenAS2Exception {
super.onBeforeAddPartnership(aPartnership);
// Ensure a nice name
if (Partnership.DEFAULT_NAME.equals(aPartnership.getName()))
aPartnership.setName(aPartnership.getSenderAS2ID() + "-" + aPartnership.getReceiverAS2ID());
// is specified anyway and for the MIC it is specified explicitly
if (aPartnership.getSigningAlgorithm() == null)
aPartnership.setSigningAlgorithm(ECryptoAlgorithmSign.DIGEST_SHA_1);
}Example 80
| Project: assertj-swing-master File: ComponentSetPopupMenuTask.java View source code |
@RunsInEDT @Nonnull public static JPopupMenu createAndSetPopupMenu(@Nonnull final JComponent c, final String... items) { JPopupMenu result = execute(() -> { JPopupMenu popupMenu = new JPopupMenu(); for (String item : items) { popupMenu.add(new JMenuItem(item)); } c.setComponentPopupMenu(popupMenu); return popupMenu; }); return checkNotNull(result); }
Example 81
| Project: atom-game-framework-sdk-master File: VariableTypeDescription.java View source code |
@Nonnull
public String getScriptString() {
if (escapedTypeArguments.isEmpty()) {
return typeName;
}
String formattedTypeArguments = escapedTypeArguments;
formattedTypeArguments = escapeCharacter(formattedTypeArguments, ']');
formattedTypeArguments = escapeCharacter(formattedTypeArguments, '}');
return typeName + ":" + formattedTypeArguments;
}Example 82
| Project: beam-master File: Annotations.java View source code |
@Override
public boolean apply(@Nonnull final Annotation category) {
return FluentIterable.from(Arrays.asList(((Category) category).value())).anyMatch(new Predicate<Class<?>>() {
@Override
public boolean apply(final Class<?> aClass) {
return allowDerived ? value.isAssignableFrom(aClass) : value.equals(aClass);
}
});
}Example 83
| Project: bees-shop-clickstart-master File: ShoppingCartRepository.java View source code |
@Nonnull public ShoppingCart getCurrentShoppingCart(@Nonnull HttpServletRequest request) { HttpSession session = request.getSession(); ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute(ShoppingCart.class.getName()); if (shoppingCart == null) { shoppingCart = new ShoppingCart(); session.setAttribute(ShoppingCart.class.getName(), shoppingCart); } return shoppingCart; }
Example 84
| Project: BlockOwn-master File: CachedDatabase.java View source code |
/**
* Flush cache data to database. Removes each flushed key-value-pair from the given {@link Map}.
*
* @param cacheData the cache data
* @return true, if successful
*/
boolean flushDatabase(@Nonnull final Map<Ownable, Optional<User>> cacheData) {
Iterator<Entry<Ownable, Optional<User>>> iterator = cacheData.entrySet().iterator();
Entry<Ownable, Optional<User>> owning;
while (iterator.hasNext()) {
owning = iterator.next();
DatabaseAction action;
Ownable key = owning.getKey();
Optional<User> value = owning.getValue();
if (!value.isPresent()) {
action = DatabaseAction.newUnownInstance(key);
} else {
action = DatabaseAction.newOwnInstance(key, value.get());
}
if (!setDatabaseOwner(action)) {
return false;
}
iterator.remove();
}
return true;
}Example 85
| Project: Botania-master File: ItemWaterRod.java View source code |
@Nonnull
@Override
public EnumActionResult onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing side, float par8, float par9, float par10) {
ItemStack stack = player.getHeldItem(hand);
if (ManaItemHandler.requestManaExactForTool(stack, player, COST, false) && !world.provider.doesWaterVaporize()) {
// Adapted from bucket code
RayTraceResult mop = rayTrace(world, player, false);
if (mop != null && mop.typeOfHit == RayTraceResult.Type.BLOCK) {
BlockPos hitPos = mop.getBlockPos();
if (!world.isBlockModifiable(player, hitPos))
return EnumActionResult.FAIL;
BlockPos placePos = hitPos.offset(mop.sideHit);
if (player.canPlayerEdit(placePos, mop.sideHit, stack)) {
if (ManaItemHandler.requestManaExactForTool(stack, player, COST, true) && ((ItemBucket) Items.WATER_BUCKET).tryPlaceContainedLiquid(player, world, placePos)) {
for (int i = 0; i < 6; i++) Botania.proxy.sparkleFX(pos.getX() + side.getFrontOffsetX() + Math.random(), pos.getY() + side.getFrontOffsetY() + Math.random(), pos.getZ() + side.getFrontOffsetZ() + Math.random(), 0.2F, 0.2F, 1F, 1F, 5);
return EnumActionResult.SUCCESS;
}
}
}
return EnumActionResult.FAIL;
}
return EnumActionResult.PASS;
}Example 86
| Project: camunda-bpm-mockito-master File: ReadXmlDocumentFromResource.java View source code |
@Nonnull
@Override
public String apply(final Document document) {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
final StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
return writer.getBuffer().toString();
} catch (javax.xml.transform.TransformerException e) {
throw new RuntimeException(e);
}
}Example 87
| Project: components-ness-event-master File: TestJmsEventReceiver.java View source code |
@Before
public void setUp() throws Exception {
Injector injector = Guice.createInjector(new ConfigModule(Config.getEmptyConfig()), new NessJacksonModule());
NessEventDispatcher eventDispatcherStub = new NessEventDispatcher() {
@Override
public void dispatch(@Nonnull NessEvent event) {
LOG.debug("Event: %s", event);
}
};
eventReceiver = new JmsEventReceiver(null, eventDispatcherStub, injector.getInstance(ObjectMapper.class));
}Example 88
| Project: Coursera-Introduction-to-Recommender-Systems-Programming-Assignment-5-master File: SimpleGlobalItemScorer.java View source code |
/** * Score items with respect to a set of reference items. * * @param items * The reference items. * @param scores * The score vector. Its domain is the items to be scored, and the scores should be stored into this vector. */ @Override public void globalScore(@Nonnull Collection<Long> items, @Nonnull MutableSparseVector scores) { scores.fill(0); for (VectorEntry e : scores.fast(VectorEntry.State.EITHER)) { long item = e.getKey(); List<ScoredId> neighbors = model.getNeighbors(item); double sumScore = 0; for (ScoredId thisNghbr : neighbors) { if (items.contains(thisNghbr.getId())) sumScore += thisNghbr.getScore(); } scores.set(item, sumScore); } }
Example 89
| Project: coursera_recommender_systems-master File: SimpleGlobalItemScorer.java View source code |
/** * Score items with respect to a set of reference items. * @param items The reference items. * @param scores The score vector. Its domain is the items to be scored, and the scores should * be stored into this vector. */ @Override public void globalScore(@Nonnull Collection<Long> items, @Nonnull MutableSparseVector scores) { scores.fill(0); // score items in the domain of scores for (VectorEntry e : scores.fast(VectorEntry.State.EITHER)) { // each item's score is the sum of its similarity to each item in items, if they are // neighbors in the model. long itemId = e.getKey(); // getting neighbors List<ScoredId> neighbors = model.getNeighbors(itemId); Map<Long, Double> neighMap = new HashMap<Long, Double>(); for (ScoredId scoredId : neighbors) { neighMap.put(scoredId.getId(), scoredId.getScore()); } // scoring similarity double score = 0.0; for (Long basketItem : items) { Double similarity = 0.0; if (neighMap.containsKey(basketItem)) similarity = neighMap.get(basketItem); score += similarity; } // asserting score scores.set(e, score); } }
Example 90
| Project: damapping-master File: MapperAnnotationValidationStep.java View source code |
@Override
public void validate(@Nonnull DASourceClass sourceClass) throws ValidationError {
List<DAAnnotation> mapperAnnotations = from(sourceClass.getAnnotations()).filter(DAAnnotationPredicates.isMapper()).toList();
if (mapperAnnotations.size() > 1) {
throw new ValidationError("Mapper with more than one @Mapper annotation is not supported", sourceClass, null, mapperAnnotations.get(1));
}
if (mapperAnnotations.isEmpty()) {
throw new ValidationError("Mapper without @Mapper annotation is not supported", sourceClass, null, null);
}
}Example 91
| Project: dasein-cloud-core-master File: TagUtils.java View source code |
@Nonnull
public static Tag[] getTagsForDelete(Map<String, String> all, Tag[] tags) {
Collection<Tag> result = new ArrayList<Tag>();
if (all != null) {
for (Map.Entry<String, String> entry : all.entrySet()) {
if (!isKeyInTags(entry.getKey(), tags)) {
result.add(new Tag(entry.getKey(), entry.getValue()));
}
}
}
return result.toArray(new Tag[result.size()]);
}Example 92
| Project: dasein-cloud-joyent-master File: BasicSchemeHttpAuth.java View source code |
public void addPreemptiveAuth(@Nonnull HttpRequest request) throws CloudException, InternalException {
if (providerContext == null) {
throw new CloudException("No context was defined for this request");
}
try {
String username = new String(providerContext.getAccessPublic(), "utf-8");
String password = new String(providerContext.getAccessPrivate(), "utf-8");
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
request.addHeader(new BasicScheme().authenticate(creds, request));
} catch (UnsupportedEncodingException e) {
throw new InternalException(e);
} catch (AuthenticationException e) {
throw new InternalException(e);
}
}Example 93
| Project: dcache-master File: RequestStatusTool.java View source code |
public static final boolean isFailedRequestStatus(@Nonnull TReturnStatus returnStatus) {
TStatusCode statusCode = checkNotNull(returnStatus.getStatusCode());
return statusCode != TStatusCode.SRM_PARTIAL_SUCCESS && statusCode != TStatusCode.SRM_REQUEST_INPROGRESS && statusCode != TStatusCode.SRM_REQUEST_QUEUED && statusCode != TStatusCode.SRM_REQUEST_SUSPENDED && statusCode != TStatusCode.SRM_SUCCESS && statusCode != TStatusCode.SRM_DONE;
}Example 94
| Project: devcoin-android-master File: SendCoinsOfflineTask.java View source code |
public final void sendCoinsOffline(@Nonnull final SendRequest sendRequest) {
backgroundHandler.post(new Runnable() {
@Override
public void run() {
// can take long
final Transaction transaction = wallet.sendCoinsOffline(sendRequest);
callbackHandler.post(new Runnable() {
@Override
public void run() {
if (transaction != null)
onSuccess(transaction);
else
onFailure();
}
});
}
});
}Example 95
| Project: docker-plugin-master File: DockerBuilderControlCloudOption.java View source code |
@Nonnull
protected DockerCloud getCloud(Run<?, ?> build, Launcher launcher) {
// Did we specify?
if (!Strings.isNullOrEmpty(cloudName)) {
DockerCloud specifiedCloud = (DockerCloud) Jenkins.getInstance().getCloud(cloudName);
if (specifiedCloud == null)
throw new IllegalStateException("Could not find a cloud named " + cloudName);
return specifiedCloud;
}
// Otherwise default to where we ran
Optional<DockerCloud> cloud = JenkinsUtils.getCloudThatWeBuiltOn(build, launcher);
if (!cloud.isPresent()) {
throw new IllegalStateException("Cannot list cloud for docker action");
}
return cloud.get();
}Example 96
| Project: dropwizard-caching-bundle-master File: CachedResponseWeigher.java View source code |
@Override public int weigh(@Nonnull String key, @Nonnull CachedResponse value) { int weight = 0; // This just an estimate for weighing purposes, not a precise calculation of memory use. // Size of the key weight += key.length() * CHAR_BYTES; // Size of the headers for (Map.Entry<String, List<String>> header : value.getResponseHeaders().entrySet()) { weight += header.getKey().length() * CHAR_BYTES; for (String headerValue : header.getValue()) { weight += headerValue.length() * CHAR_BYTES; } } // Size of the body weight += value.getResponseContent().length; return weight; }
Example 97
| Project: dropwizard-guicey-master File: HK2InstanceListener.java View source code |
@Override
public Filter getFilter() {
final List<String> managedTypes = Lists.transform(contextDebugService.getManagedTypes(), new Function<Class<?>, String>() {
@Override
public String apply(@Nonnull final Class<?> input) {
return input.getName();
}
});
return new Filter() {
@Override
public boolean matches(final Descriptor d) {
return d.getDescriptorType() == DescriptorType.CLASS && managedTypes.contains(d.getImplementation());
}
};
}Example 98
| Project: eucalyptus-master File: TokensServiceGuard.java View source code |
public void beforeService(@Nonnull final Object object) throws TokensException {
// Check type
if (!(object instanceof TokenMessage)) {
throw new TokensException(TokensException.Code.InvalidAction, "Invalid action");
}
// Check action enabled
final TokenMessage message = TokenMessage.class.cast(object);
final String action = RestrictedTypes.getIamActionByMessageType(message).toLowerCase();
if ((!getEnabledActions().isEmpty() && !getEnabledActions().contains(action)) || getDisabledActions().contains(action)) {
throw new TokensException(TokensException.Code.ServiceUnavailable, "Service unavailable");
}
}Example 99
| Project: fb-contrib-eclipse-quick-fixes-master File: TraversalUtil.java View source code |
@SuppressWarnings("unchecked")
public static <T extends ASTNode> T findClosestAncestor(@Nonnull ASTNode node, @Nonnull Class<T> parentClass) {
ASTNode parent = node.getParent();
while (parent != null) {
if (parentClass.isAssignableFrom(parent.getClass())) {
// allows parentClass to be something generic like Statement.class
return (T) parent;
}
parent = parent.getParent();
}
return null;
}Example 100
| Project: felix-master File: PreprocessorDTOBuilder.java View source code |
/**
* Build a preprocessor DTO from a filter info
* @param info The preprocessor info
* @return A preprocessor DTO
*/
@Nonnull
public static PreprocessorDTO build(@Nonnull final PreprocessorInfo info, final int reason) {
final PreprocessorDTO dto = (reason != -1 ? new FailedPreprocessorDTO() : new PreprocessorDTO());
dto.initParams = info.getInitParameters();
dto.serviceId = info.getServiceId();
if (reason != -1) {
((FailedPreprocessorDTO) dto).failureReason = reason;
}
return dto;
}Example 101
| Project: fest-assert-1.x-master File: Fail_failIfNotEqual_withStubs_Test.java View source code |
@Before
public void setUp() {
invoker = new ConstructorInvoker() {
@Override
Object newInstance(@Nonnull String className, @Nonnull Class<?>[] parameterTypes, @Nonnull Object[] parameterValues) {
// simulate that ComparisonFailure cannot be created (e.g. if JUnit is not in the classpath)
return null;
}
};
ComparisonFailureFactory.constructorInvoker(invoker);
}