Java Code Examples for javax.annotation.Nullable

The following are top voted examples for showing how to use javax.annotation.Nullable. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: andbg   File: ClassPool.java   View source code 6 votes vote down vote up
@Nullable @Override
public Map.Entry<? extends PoolClassDef, Integer> getClassEntryByType(@Nullable CharSequence name) {
    if (name == null) {
        return null;
    }

    final PoolClassDef classDef = internedItems.get(name.toString());
    if (classDef == null) {
        return null;
    }

    return new Entry<PoolClassDef, Integer>() {
        @Override public PoolClassDef getKey() {
            return classDef;
        }

        @Override public Integer getValue() {
            return classDef.classDefIndex;
        }

        @Override public Integer setValue(Integer value) {
            return classDef.classDefIndex = value;
        }
    };
}
 
Example 2
Project: googles-monorepo-demo   File: AbstractMapBasedMultiset.java   View source code 6 votes vote down vote up
@CanIgnoreReturnValue
@Override
public int remove(@Nullable Object element, int occurrences) {
  if (occurrences == 0) {
    return count(element);
  }
  checkArgument(occurrences > 0, "occurrences cannot be negative: %s", occurrences);
  Count frequency = backingMap.get(element);
  if (frequency == null) {
    return 0;
  }

  int oldCount = frequency.get();

  int numberRemoved;
  if (oldCount > occurrences) {
    numberRemoved = occurrences;
  } else {
    numberRemoved = oldCount;
    backingMap.remove(element);
  }

  frequency.add(-numberRemoved);
  size -= numberRemoved;
  return oldCount;
}
 
Example 3
Project: CustomWorldGen   File: PreYggdrasilConverter.java   View source code 6 votes vote down vote up
private static void lookupNames(MinecraftServer server, Collection<String> names, ProfileLookupCallback callback)
{
    String[] astring = (String[])Iterators.toArray(Iterators.filter(names.iterator(), new Predicate<String>()
    {
        public boolean apply(@Nullable String p_apply_1_)
        {
            return !StringUtils.isNullOrEmpty(p_apply_1_);
        }
    }), String.class);

    if (server.isServerInOnlineMode())
    {
        server.getGameProfileRepository().findProfilesByNames(astring, Agent.MINECRAFT, callback);
    }
    else
    {
        for (String s : astring)
        {
            UUID uuid = EntityPlayer.getUUID(new GameProfile((UUID)null, s));
            GameProfile gameprofile = new GameProfile(uuid, s);
            callback.onProfileLookupSucceeded(gameprofile);
        }
    }
}
 
Example 4
Project: RNLearn_Project1   File: ReactFontManager.java   View source code 6 votes vote down vote up
private static
@Nullable Typeface createTypeface(
    String fontFamilyName,
    int style,
    AssetManager assetManager) {
  String extension = EXTENSIONS[style];
  for (String fileExtension : FILE_EXTENSIONS) {
    String fileName = new StringBuilder()
        .append(FONTS_ASSET_PATH)
        .append(fontFamilyName)
        .append(extension)
        .append(fileExtension)
        .toString();
    try {
      return Typeface.createFromAsset(assetManager, fileName);
    } catch (RuntimeException e) {
      // unfortunately Typeface.createFromAsset throws an exception instead of returning null
      // if the typeface doesn't exist
    }
  }

  return Typeface.create(fontFamilyName, style);
}
 
Example 5
Project: ForgeHax   File: ScoreboardListenerService.java   View source code 5 votes vote down vote up
@SubscribeEvent
public void onScoreboardEvent(PacketEvent.Incoming.Pre event) {
    if(event.getPacket() instanceof SPacketPlayerListItem
            && getWorld() != null
            && System.currentTimeMillis() > waitTime) {
        final SPacketPlayerListItem packet = (SPacketPlayerListItem) event.getPacket();
        packet.getEntries().stream()
                .filter(Objects::nonNull)
                .filter(data -> data.getProfile() != null)
                .filter(data -> !Strings.isNullOrEmpty(data.getProfile().getName()))
                .forEach(data -> {
                    final String name = data.getProfile().getName();
                    PlayerInfoHelper.invokeEfficiently(name, new FutureCallback<PlayerInfo>() {
                        @Override
                        public void onSuccess(@Nullable PlayerInfo result) {
                            if(result != null) fireEvents(packet.getAction(), result, data.getProfile());
                        }

                        @Override
                        public void onFailure(Throwable t) {

                        }
                    });
                });
    }
}
 
Example 6
Project: GitHub   File: CountingMemoryCache.java   View source code 5 votes vote down vote up
/** Creates a new entry with the usage count of 0. */
@VisibleForTesting
static <K, V> Entry<K, V> of(
    final K key,
    final CloseableReference<V> valueRef,
    final @Nullable EntryStateObserver<K> observer) {
  return new Entry<>(key, valueRef, observer);
}
 
Example 7
Project: aws-codecommit-trigger-plugin   File: AwsCredentialsHelper.java   View source code 5 votes vote down vote up
@CheckForNull
public static AwsCredentials getCredentials(@Nullable String credentialsId) {
    if (StringUtils.isBlank(credentialsId)) {
        return null;
    }

    return CredentialsMatchers.firstOrNull(
        CredentialsProvider.lookupCredentials(AwsCredentials.class, (Item) null, ACL.SYSTEM, null, null),
        CredentialsMatchers.withId(credentialsId)
    );
}
 
Example 8
Project: CustomWorldGen   File: BlockNewLeaf.java   View source code 5 votes vote down vote up
public void harvestBlock(World worldIn, EntityPlayer player, BlockPos pos, IBlockState state, @Nullable TileEntity te, @Nullable ItemStack stack)
{
    if (false && !worldIn.isRemote && stack != null && stack.getItem() == Items.SHEARS) //Forge: Noop this
    {
        player.addStat(StatList.getBlockStats(this));
        spawnAsEntity(worldIn, pos, new ItemStack(Item.getItemFromBlock(this), 1, ((BlockPlanks.EnumType)state.getValue(VARIANT)).getMetadata() - 4));
    }
    else
    {
        super.harvestBlock(worldIn, player, pos, state, te, stack);
    }
}
 
Example 9
Project: JRequests   File: JRequests.java   View source code 5 votes vote down vote up
public
@Nullable
String request(String url) throws IOException {
    try (ResponseBody responseBody = response(url).body()) {
        if (responseBody != null) return responseBody.string();
        return null;
    }
}
 
Example 10
Project: shibboleth-idp-oidc-extension   File: DefaultSubjectTypeStrategy.java   View source code 5 votes vote down vote up
/** {@inheritDoc} */
@Override
@Nullable
public SubjectType apply(@Nullable final ProfileRequestContext input) {

    SubjectType type = null;
    OIDCMetadataContext ctx = oidcMetadataContextLookupStrategy.apply(input);
    if (ctx != null && ctx.getClientInformation() != null && ctx.getClientInformation().getOIDCMetadata() != null) {
        type = ctx.getClientInformation().getOIDCMetadata().getSubjectType();
    }
    if (type == null) {
        boolean pairwise = false;
        final RelyingPartyContext rpc = relyingPartyContextLookupStrategy.apply(input);
        if (rpc != null) {
            final ProfileConfiguration pc = rpc.getProfileConfig();
            if (pc != null && pc instanceof OIDCCoreProtocolConfiguration) {
                pairwise = ((OIDCCoreProtocolConfiguration) pc).getPairwiseSubject().apply(input);
            }
        }
        type = pairwise ? SubjectType.PAIRWISE : SubjectType.PUBLIC;
    }
    return type;
}
 
Example 11
Project: centraldogma   File: Watcher.java   View source code 5 votes vote down vote up
/**
 * Returns the latest value of {@code watchFile()} result.
 *
 * @param defaultValue the default value which is returned when the value is not available yet
 */
@Nullable
default T latestValue(@Nullable T defaultValue) {
    final CompletableFuture<Latest<T>> initialValueFuture = initialValueFuture();
    if (initialValueFuture.isDone() && !initialValueFuture.isCompletedExceptionally()) {
        return latest().value();
    } else {
        return defaultValue;
    }
}
 
Example 12
Project: RNLearn_Project1   File: CustomStyleSpan.java   View source code 5 votes vote down vote up
public CustomStyleSpan(
    int fontStyle,
    int fontWeight,
    @Nullable String fontFamily,
    AssetManager assetManager) {
  mStyle = fontStyle;
  mWeight = fontWeight;
  mFontFamily = fontFamily;
  mAssetManager = assetManager;
}
 
Example 13
Project: guava-mock   File: NullPointerTester.java   View source code 5 votes vote down vote up
private static Invokable<?, ?> invokable(@Nullable Object instance, Method method) {
  if (instance == null) {
    return Invokable.from(method);
  } else {
    return TypeToken.of(instance.getClass()).method(method);
  }
}
 
Example 14
Project: sonar-analyzer-commons   File: TestFile.java   View source code 5 votes vote down vote up
@Nullable
String commentAt(int line) {
  List<Comment> comments = commentListPreLineMap.get(line);
  if (comments != null && !comments.isEmpty()) {
    return line(line).substring(comments.get(0).column - 1);
  }
  return null;
}
 
Example 15
Project: teasy   File: ElementsNotHaveAttribute.java   View source code 5 votes vote down vote up
@Nullable
@Override
public Boolean apply(@Nullable WebDriver webDriver) {
    errorElements = new ArrayList<>();
    boolean isCorrect = true;
    for (TeasyElement el : elements) {
        if (el.getAttribute(attributeName) != null) {
            isCorrect = false;
            errorElements.add(el);
        }
    }
    return isCorrect;
}
 
Example 16
Project: Nird2   File: RecentEmojiPageModel.java   View source code 5 votes vote down vote up
private LinkedHashSet<String> deserialize(@Nullable String serialized) {
	if (serialized == null) return new LinkedHashSet<>();
	String[] list = serialized.split(";");
	LinkedHashSet<String> result = new LinkedHashSet<>(list.length);
	Collections.addAll(result, list);
	return result;
}
 
Example 17
Project: FoodCraft-Reloaded   File: GuiHandler.java   View source code 5 votes vote down vote up
@Nullable
@Override
public Gui getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
    switch (ID) {
        case GuiID.DRINK_MACHINE:
            return new GuiContainerDrinkMachine(player.inventory, world.getTileEntity(new BlockPos(x, y, z)));
        case GuiID.PRESSURE_COOKER:
            return new GuiContainerPressureCooker(player.inventory, world.getTileEntity(new BlockPos(x, y, z)));
        case GuiID.SMELTING_PRESSURE_COOKER:
            return new GuiContainerSmeltingDrinkMachine(player.inventory, world.getTileEntity(new BlockPos(x, y, z)));
    }
    return null;
}
 
Example 18
Project: guava-mock   File: Predicates.java   View source code 5 votes vote down vote up
@Override
public boolean equals(@Nullable Object obj) {
  if (obj instanceof InstanceOfPredicate) {
    InstanceOfPredicate that = (InstanceOfPredicate) obj;
    return clazz == that.clazz;
  }
  return false;
}
 
Example 19
Project: toshi-headless-client   File: ECKey.java   View source code 5 votes vote down vote up
/**
 * Pair a private key integer with a public EC point
 *
 * BouncyCastle will be used as the Java Security Provider
 */
public ECKey(@Nullable BigInteger priv, ECPoint pub) {
    this(
            SpongyCastleProvider.getInstance(),
            privateKeyFromBigInteger(priv),
            pub
    );
}
 
Example 20
Project: ProjectAres   File: DeathMessageBuilder.java   View source code 5 votes vote down vote up
boolean ranged(RangedInfo rangedInfo, @Nullable Location distanceReference) {
    double distance = rangedInfo.distanceFrom(distanceReference);
    if(!Double.isNaN(distance) && option("distance")) {
        setDistance(distance);
        if(distance >= SNIPE_DISTANCE) {
            option("snipe");
        }
        return true;
    }
    return false;
}
 
Example 21
Project: RNLearn_Project1   File: DevSupportManagerFactory.java   View source code 5 votes vote down vote up
public static DevSupportManager create(
    Context applicationContext,
    ReactInstanceDevCommandsHandler reactInstanceCommandsHandler,
    @Nullable String packagerPathForJSBundleName,
    boolean enableOnCreate) {

  return create(
    applicationContext,
    reactInstanceCommandsHandler,
    packagerPathForJSBundleName,
    enableOnCreate,
    null);
}
 
Example 22
Project: GitHub   File: RealmQuery.java   View source code 5 votes vote down vote up
/**
 * Not-equal-to comparison.
 *
 * @param fieldName the field to compare.
 * @param value the value to compare with.
 * @return the query object.
 * @throws java.lang.IllegalArgumentException if one or more arguments do not match class or field type.
 */
public RealmQuery<E> notEqualTo(String fieldName, @Nullable byte[] value) {
    realm.checkIfValid();

    FieldDescriptor fd = schema.getColumnIndices(fieldName, RealmFieldType.BINARY);
    if (value == null) {
        this.query.isNotNull(fd.getColumnIndices(), fd.getNativeTablePointers());
    } else {
        this.query.notEqualTo(fd.getColumnIndices(), fd.getNativeTablePointers(), value);
    }
    return this;
}
 
Example 23
Project: guava-mock   File: DummyProxy.java   View source code 5 votes vote down vote up
@Override protected Object handleInvocation(
    Object proxy, Method method, Object[] args) {
  Invokable<?, ?> invokable = interfaceType.method(method);
  ImmutableList<Parameter> params = invokable.getParameters();
  for (int i = 0; i < args.length; i++) {
    Parameter param = params.get(i);
    if (!param.isAnnotationPresent(Nullable.class)) {
      checkNotNull(args[i]);
    }
  }
  return dummyReturnValue(interfaceType.resolveType(method.getGenericReturnType()));
}
 
Example 24
Project: Backmemed   File: EntityVex.java   View source code 5 votes vote down vote up
@Nullable

    /**
     * Called only once on an entity when first time spawned, via egg, mob spawner, natural spawning etc, but not called
     * when entity is reloaded from nbt. Mainly used for initializing attributes and inventory
     */
    public IEntityLivingData onInitialSpawn(DifficultyInstance difficulty, @Nullable IEntityLivingData livingdata)
    {
        this.setEquipmentBasedOnDifficulty(difficulty);
        this.setEnchantmentBasedOnDifficulty(difficulty);
        return super.onInitialSpawn(difficulty, livingdata);
    }
 
Example 25
Project: dremio-oss   File: MaterializationStoragePlugin.java   View source code 5 votes vote down vote up
private RelShuttle getTimestampBasedMaterializationShuttle(final Layout layout) {
  final RelShuttle shuttle = new FileMaterializationShuttle(Long.MIN_VALUE);
  return materializationStore.get().get(layout.getId())
      .transform(new Function<MaterializedLayout, RelShuttle>() {
        @Nullable
        @Override
        public RelShuttle apply(@Nullable final MaterializedLayout input) {
          if (AccelerationUtils.selfOrEmpty(input.getMaterializationList()).isEmpty()) {
            return shuttle;
          }
          final Long updateId = FluentIterable.from(input.getMaterializationList())
              .toSortedList(new Comparator<Materialization>() {
                @Override
                public int compare(Materialization o1, Materialization o2) {
                  // sorting in reverse order
                  return o2.getUpdateId().compareTo(o1.getUpdateId());
                }
              }).get(0).getUpdateId();

          if (updateId == null) {
            return shuttle;
          }

          return new FileMaterializationShuttle(updateId);
        }
      })
      .or(shuttle);
}
 
Example 26
Project: guava-mock   File: Iterators.java   View source code 5 votes vote down vote up
/**
 * Deletes and returns the next value from the iterator, or returns
 * {@code null} if there is no such value.
 */
@Nullable
static <T> T pollNext(Iterator<T> iterator) {
  if (iterator.hasNext()) {
    T result = iterator.next();
    iterator.remove();
    return result;
  } else {
    return null;
  }
}
 
Example 27
Project: Elasticsearch   File: EvaluatingNormalizer.java   View source code 5 votes vote down vote up
/**
 * @param functions function resolver
 * @param granularity the maximum row granularity the normalizer should try to normalize
 * @param referenceResolver reference resolver which is used to resolve paths
 * @param fieldResolver optional field resolver to resolve fields
 * @param inPlace defines if symbols like functions can be changed inplace instead of being copied when changed
 */
public EvaluatingNormalizer(
        Functions functions, RowGranularity granularity, ReferenceResolver<? extends Input<?>> referenceResolver,
        @Nullable FieldResolver fieldResolver, boolean inPlace) {
    this.functions = functions;
    this.granularity = granularity;
    this.referenceResolver = referenceResolver;
    this.fieldResolver = fieldResolver;
    if (inPlace) {
        this.visitor = new InPlaceVisitor();
    } else {
        this.visitor = new CopyingVisitor();
    }
}
 
Example 28
Project: ProjectAres   File: NavigatorInterface.java   View source code 5 votes vote down vote up
@Nullable ItemStack createIcon(Player viewer) {
    if(!connector.isVisible()) return null;

    final RenderedItemBuilder<?> icon = itemBuilders.create(viewer, this.icon.clone())
                                                    .flags(ItemFlag.values());
    final Object mapped = connector.mappedTo();
    if(Navigator.DEFAULT_MAPPING.equals(mapped)) {
        renderDefault(viewer, icon);
    } else if(mapped instanceof Server) {
        renderServer(viewer, icon, (Server) mapped);
    } else if(mapped instanceof Arena) {
        renderArena(viewer, icon, (Arena) mapped);
    }
    return icon.get();
}
 
Example 29
Project: react4j   File: HtmlGlobalFields.java   View source code 4 votes vote down vote up
@JsProperty
protected native void setOnCompositionUpdate( @Nullable final CompositionEventHandler onCompositionUpdate );
 
Example 30
Project: tac-kbp-eal   File: EREAligner.java   View source code 4 votes vote down vote up
@Override
public OffsetRange<CharOffset> apply(@Nullable final Response response) {
  return checkNotNull(response).canonicalArgument().charOffsetSpan().asCharOffsetRange();
}
 
Example 31
Project: hashsdn-controller   File: LocalProxyTransaction.java   View source code 4 votes vote down vote up
abstract void replayModifyTransactionRequest(ModifyTransactionRequest request,
@Nullable Consumer<Response<?, ?>> callback, long enqueuedTicks);
 
Example 32
Project: ProjectAres   File: TeamManager.java   View source code 4 votes vote down vote up
/**
 * @return The team this player is supposed to be on
 */
public @Nullable Team getTeam(Player player) {
    return getTeam(userStore.getUser(player));
}
 
Example 33
Project: react4j   File: HtmlGlobalFields.java   View source code 4 votes vote down vote up
@JsProperty
protected native void setOnMouseDown( @Nullable final MouseEventHandler onMouseDown );
 
Example 34
Project: date-helper   File: LocalDateTimeXMLConverter.java   View source code 4 votes vote down vote up
@Nullable
@Override
public LocalDateTime unmarshal(String v) {
	return isEmpty(v) ? null : LocalDateTime.parse(v);
}
 
Example 35
Project: Backmemed   File: CommandPardonIp.java   View source code 4 votes vote down vote up
public List<String> getTabCompletionOptions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos pos)
{
    return args.length == 1 ? getListOfStringsMatchingLastWord(args, server.getPlayerList().getBannedIPs().getKeys()) : Collections.<String>emptyList();
}
 
Example 36
Project: guava-mock   File: AbstractTable.java   View source code 4 votes vote down vote up
@Override
public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) {
  Map<C, V> row = Maps.safeGet(rowMap(), rowKey);
  return row != null && Maps.safeContainsKey(row, columnKey);
}
 
Example 37
Project: Equella   File: SimpleI18NString.java   View source code 4 votes vote down vote up
public SimpleI18NString(@Nullable String text, @Nullable String defaultText)
{
	this.text = text;
	this.defaultText = defaultText;
}
 
Example 38
Project: CustomWorldGen   File: EntitySnowman.java   View source code 4 votes vote down vote up
@Nullable
protected SoundEvent getAmbientSound()
{
    return SoundEvents.ENTITY_SNOWMAN_AMBIENT;
}
 
Example 39
Project: react4j   File: HtmlGlobalFields.java   View source code 4 votes vote down vote up
@JsProperty
protected native void setOnTouchCancel( @Nullable final TouchEventHandler onTouchCancel );
 
Example 40
Project: react4j   File: FormProps.java   View source code 4 votes vote down vote up
@JsOverlay
public final FormProps onDragLeave( @Nullable final DragEventHandler handler )
{
  setOnDragLeave( handler );
  return self();
}