java.util.Locale.Category#edu.umd.cs.findbugs.annotations.SuppressFBWarnings源码实例Demo

下面列出了java.util.Locale.Category#edu.umd.cs.findbugs.annotations.SuppressFBWarnings 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: commercetools-sync-java   文件: ProductSync.java
@SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") // https://github.com/findbugsproject/findbugs/issues/79
@Nonnull
private CompletionStage<Void> applyCallbackAndCreate(@Nonnull final ProductDraft productDraft) {
    return syncOptions
        .applyBeforeCreateCallBack(productDraft)
        .map(draft -> productService
            .createProduct(draft)
            .thenAccept(productOptional -> {
                if (productOptional.isPresent()) {
                    readyToResolve.add(productDraft.getKey());
                    statistics.incrementCreated();
                } else {
                    statistics.incrementFailed();
                }
            })
        )
        .orElse(CompletableFuture.completedFuture(null));
}
 
源代码2 项目: GDH   文件: CipherAgentImpl.java
/**
 * Decrypt an encrypted byte array with a key and initial vector
 * 
 * @param encryptedBytes
 *            the byte array to decrypt
 * @param iv
 *            the initial vector. Must be a random 128 bit value and the
 *            same one used in encryption
 * @param key
 *            the key for decryption
 * 
 * @return the decrypted string
 */
@SuppressFBWarnings("UC_USELESS_OBJECT")
public String decrypt(byte[] encryptedBytes, byte[] iv, SecretKey key)
        throws InvalidKeyException, InvalidAlgorithmParameterException, IOException {
    byte[] buf = new byte[Constants.CIPHER_SIZE];
    ByteArrayOutputStream outputStream = null;
    IvParameterSpec ivspec = new IvParameterSpec(iv);
    decryptCipher.init(Cipher.DECRYPT_MODE, key, ivspec);
    outputStream = new ByteArrayOutputStream();
    ByteArrayInputStream inStream = new ByteArrayInputStream(encryptedBytes);
    CipherInputStream cipherInputStream = new CipherInputStream(inStream, decryptCipher);
    int bytesRead = 0;
    while ((bytesRead = cipherInputStream.read(buf)) >= 0) {
        outputStream.write(buf, 0, bytesRead);
    }
    cipherInputStream.close();

    return outputStream.toString(StandardCharsets.UTF_8.name());
}
 
源代码3 项目: arctic-sea   文件: SweHelper.java
@SuppressFBWarnings("BC_VACUOUS_INSTANCEOF")
private List<String> createBlock(SweAbstractDataComponent elementType, Time phenomenonTime, String phenID,
        Value<?> value) {
    if (elementType instanceof SweDataRecord) {
        SweDataRecord elementTypeRecord = (SweDataRecord) elementType;
        List<String> block = new ArrayList<>(elementTypeRecord.getFields().size());
        if (!(value instanceof NilTemplateValue)) {
            elementTypeRecord.getFields().forEach(field -> {
                if (field.getElement() instanceof SweTime || field.getElement() instanceof SweTimeRange) {
                    block.add(DateTimeHelper.format(phenomenonTime));
                } else if (field.getElement() instanceof SweAbstractDataComponent
                        && field.getElement().getDefinition().equals(phenID)) {
                    block.add(value.getValue().toString());
                } else if (field.getElement() instanceof SweObservableProperty) {
                    block.add(phenID);
                }
            });
        }
        return block;
    }
    String exceptionMsg = String.format("Type of ElementType is not supported: %s",
            elementType != null ? elementType.getClass().getName() : "null");
    LOGGER.debug(exceptionMsg);
    throw new IllegalArgumentException(exceptionMsg);
}
 
源代码4 项目: waltz   文件: AppendRequest.java
@SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "internal class")
public AppendRequest(
    ReqId reqId,
    long clientHighWaterMark,
    int[] writeLockRequest,
    int[] readLockRequest,
    int[] appendLockRequest,
    int header,
    byte[] data,
    int checksum
) {
    super(reqId);

    this.clientHighWaterMark = clientHighWaterMark;
    this.writeLockRequest = writeLockRequest;
    this.readLockRequest = readLockRequest;
    this.appendLockRequest = appendLockRequest;
    this.header = header;
    this.data = data;
    this.checksum = checksum;
}
 
源代码5 项目: waltz   文件: DemoAppBase.java
@SuppressFBWarnings(value = "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING", justification = "internal use")
protected void createClientHighWaterMarkTable(Connection connection, String clientHighWaterMarkTableName) throws SQLException {
    executeSQL(
        "DROP TABLE IF EXISTS " + clientHighWaterMarkTableName,
        connection,
        true // ignore exception
    );
    executeSQL(
        "CREATE TABLE " + clientHighWaterMarkTableName + " ("
            + "PARTITION_ID INTEGER NOT NULL,"
            + "HIGH_WATER_MARK BIGINT NOT NULL,"
            + "PRIMARY KEY (PARTITION_ID)"
            + ")",
        connection,
        false
    );
}
 
源代码6 项目: freecol   文件: ModifierFormat.java
@SuppressFBWarnings(value="NP_LOAD_OF_KNOWN_NULL_VALUE")
private static String getSourceName(FreeColObject source) {
    if (source == null) return getUnknownValue();

    String result = null;
    if (result == null && source instanceof Nameable) {
        result = ((Nameable)source).getName();
        if (result != null && result.isEmpty()) result = null;
    }
    if (result == null && source instanceof Named) {
        result = Messages.getName((Named)source);
        if (result.isEmpty()) result = null;
    }
    if (result == null) result = Messages.getName(source.getId());
    return result;
}
 
源代码7 项目: syndesis   文件: DbMetaDataHelper.java
@SuppressFBWarnings("OBL_UNSATISFIED_OBLIGATION")
/* default */ List<SqlParam> getOutputColumnInfo(
        final String sqlSelectStatement) throws SQLException {
    List<SqlParam> paramList = new ArrayList<>();
    try (PreparedStatement stmt = createPreparedStatement(sqlSelectStatement);
        ResultSet resultSet = stmt.executeQuery();) {
        ResultSetMetaData metaData = resultSet.getMetaData();
        if (metaData.getColumnCount()>0){
            for (int i=1; i<=metaData.getColumnCount(); i++) {
                SqlParam param = new SqlParam(metaData.getColumnName(i));
                param.setJdbcType(JDBCType.valueOf(metaData.getColumnType(i)));
                paramList.add(param);
            }
        }
        return paramList;
    }
}
 
@Test
@SuppressWarnings("ConstantConditions")
@SuppressFBWarnings(value = "DP_DO_INSIDE_DO_PRIVILEGED",
        justification = "Needed to keep `FlowNode.getPersistentAction` from failing. "
                + "We can't mock the method directly because it's final.")
void pipelineHandlerShouldSetBuildResultAndAddWarningAction()
        throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException {
    Run run = mock(Run.class);
    FlowNode flowNode = mock(FlowNode.class);
    Field actions = FlowNode.class.getDeclaredField("actions");
    actions.setAccessible(true);
    actions.set(flowNode, new CopyOnWriteArrayList<>());
    StageResultHandler pipelineHandler = new PipelineResultHandler(run, flowNode);
    pipelineHandler.setResult(Result.UNSTABLE, MESSAGE);
    verify(run).setResult(Result.UNSTABLE);
    verify(flowNode).addOrReplaceAction(refEq(new WarningAction(Result.UNSTABLE).withMessage(MESSAGE)));
    pipelineHandler.setResult(Result.FAILURE, MESSAGE);
    verify(flowNode).addOrReplaceAction(refEq(new WarningAction(Result.FAILURE).withMessage(MESSAGE)));
}
 
源代码9 项目: warnings-ng-plugin   文件: IntegrationTest.java
@SuppressFBWarnings(value = "LG", justification = "Setting the logger here helps to clean up the console log for tests")
static WebClient create(final JenkinsRule jenkins, final boolean isJavaScriptEnabled) {
    WebClient webClient = jenkins.createWebClient();
    webClient.setCssErrorHandler(new SilentCssErrorHandler());
    java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(Level.SEVERE);
    webClient.setIncorrectnessListener((s, o) -> {
    });

    webClient.setJavaScriptEnabled(isJavaScriptEnabled);
    webClient.setJavaScriptErrorListener(new IntegrationTestJavaScriptErrorListener());
    webClient.setAjaxController(new NicelyResynchronizingAjaxController());
    webClient.getCookieManager().setCookiesEnabled(isJavaScriptEnabled);
    webClient.getOptions().setCssEnabled(isJavaScriptEnabled);

    webClient.getOptions().setDownloadImages(false);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
    webClient.getOptions().setThrowExceptionOnScriptError(false);
    webClient.getOptions().setPrintContentOnFailingStatusCode(false);

    return webClient;
}
 
源代码10 项目: butterfly   文件: EolHelper.java
/**
 * Finds out what EOL character(s) are used by the specified text file.
 * If the specified file has no EOL characters null will be returned, and if more than
 * one type of EOL character(s) are used, the very first EOL occurrence will be returned.
 * If the file is empty, it returns null.
 *
 * @param textFile file to be analyzed based on its EOL character(s)
 * @return  the very first occurrence of EOL used in the specified text file, or null,
 *          if none is found
 * @throws IOException if any IO exception happens when opening and reading the text file
 */
@SuppressFBWarnings("DM_DEFAULT_ENCODING")
public static String findEol(File textFile) throws IOException {
    if (textFile == null) {
        throw new IllegalArgumentException("Text file object cannot be null");
    }
    if (!textFile.isFile()) {
        throw new IllegalArgumentException("Text file is not a file");
    }
    if (textFile.length() == 0) {
        return null;
    }
    EolBufferedReader eolBufferedReader = null;
    try {
        eolBufferedReader = new EolBufferedReader(new BufferedReader(new FileReader(textFile)));
        String line = eolBufferedReader.readLineKeepEol();
        return getEndEol(line);
    } finally {
        if (eolBufferedReader != null) eolBufferedReader.close();
    }
}
 
/**
 * Prints out the Plugin Management Tool version
 */
@SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE")
public void showVersion() {
    try (InputStream propertyInputStream = getPropertiesInputStream("/.properties")) {
        if (propertyInputStream == null) {
            throw new VersionNotFoundException("No version information available");
        }
        Properties properties = new Properties();
        properties.load(propertyInputStream);

        System.out.println(properties.getProperty("project.version"));
    } catch (IOException e) {
        throw new VersionNotFoundException("No version information available", e);
    }
}
 
源代码12 项目: hadoop-ozone   文件: PipelineStateMap.java
@Override
@SuppressFBWarnings("NP_EQUALS_SHOULD_HANDLE_NULL_ARGUMENT")
public boolean equals(Object other) {
  if (this == other) {
    return true;
  }
  if (!this.getClass().equals(other.getClass())) {
    return false;
  }
  PipelineQuery otherQuery = (PipelineQuery) other;
  return type == otherQuery.type && factor == otherQuery.factor;
}
 
源代码13 项目: hadoop-ozone   文件: ReplicationManager.java
/**
 * Process all the containers immediately.
 */
@VisibleForTesting
@SuppressFBWarnings(value="NN_NAKED_NOTIFY",
    justification="Used only for testing")
public synchronized void processContainersNow() {
  notifyAll();
}
 
源代码14 项目: testgrid   文件: OperationMessage.java
/**
 * Remove persisted in file.
 *
 * @return      true if success, else false
 */
@SuppressFBWarnings("DMI_HARDCODED_ABSOLUTE_FILENAME")
public synchronized boolean removePersistedFile() {
    Path filePath = Paths.get(PERSISTED_FILE_PATH, this.operationId.concat(".txt"));
    try {
        Files.delete(filePath);
    } catch (IOException e) {
        logger.warn("Error while removing file " + filePath.toString());
        return false;
    }
    return true;
}
 
源代码15 项目: ballerina-message-broker   文件: XidImpl.java
@SuppressFBWarnings(value = {"EI_EXPOSE_REP2", "EI_EXPOSE_REP2"},
        justification = "Data holder of global transaction identifier and branch qualifier")
public XidImpl(int formatId, byte[] branchQualifier, byte[] globalTransactionId) {
    this.branchQualifier = branchQualifier;
    this.formatId = formatId;
    this.globalTransactionId = globalTransactionId;
}
 
源代码16 项目: arctic-sea   文件: Identifier.java
@Override
@SuppressFBWarnings("EQ_OVERRIDING_EQUALS_NOT_SYMMETRIC")
public boolean equals(Object obj) {
    if (obj instanceof Identifier) {
        Identifier that = (Identifier) obj;
        return Objects.equal(this.getNamespace(), that.getNamespace())
                && Objects.equal(this.getLocalId(), that.getLocalId())
                && Objects.equal(this.getVersionId(), that.getVersionId());
    }
    return false;
}
 
源代码17 项目: BungeeChat2   文件: Account.java
@SuppressFBWarnings(
    value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD",
    justification = "Rarely every used, so no issue")
@Override
public void setDefaultChannelType(ChannelType channelType) {
  defaultChannelType = channelType;
}
 
源代码18 项目: waltz   文件: StoreAppendRequest.java
/**
 * Class constructor.
 * @param reqId The request Id.
 * @param header The header.
 * @param data The transaction data.
 * @param checksum The checksum.
 * @param callback The callback.
 */
@SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "internal class")
public StoreAppendRequest(ReqId reqId, int header, byte[] data, int checksum, LongConsumer callback) {
    this.reqId = reqId;
    this.header = header;
    this.data = data;
    this.checksum = checksum;
    this.callback = callback;
}
 
源代码19 项目: commercetools-sync-java   文件: CategorySync.java
/**
 * Given an existing {@link Category} and a new {@link CategoryDraft}, first resolves all references on the category
 * draft, then it calculates all the update actions required to synchronize the existing category to be the same as
 * the new one. Then the method applies the {@code ProductSyncOptions#beforeUpdateCallback} on the resultant list
 * of actions.
 *
 * <p>If there are update actions in the resulting list, a request is made to CTP to update the existing category,
 * otherwise it doesn't issue a request.
 *
 * @param oldCategory the category which could be updated.
 * @param newCategory the category draft where we get the new data.
 * @return a future which contains an empty result after execution of the update.
 */
@SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") // https://github.com/findbugsproject/findbugs/issues/79
private CompletionStage<Void> buildUpdateActionsAndUpdate(@Nonnull final Category oldCategory,
                                                          @Nonnull final CategoryDraft newCategory) {

    final List<UpdateAction<Category>> updateActions = buildActions(oldCategory, newCategory, syncOptions);
    final List<UpdateAction<Category>> beforeUpdateCallBackApplied =
        syncOptions.applyBeforeUpdateCallBack(updateActions, newCategory, oldCategory);

    if (!beforeUpdateCallBackApplied.isEmpty()) {
        return updateCategory(oldCategory, newCategory, beforeUpdateCallBackApplied);
    }

    return CompletableFuture.completedFuture(null);
}
 
源代码20 项目: NioSmtpClient   文件: SmtpSession.java
@SuppressFBWarnings("VA_FORMAT_STRING_USES_NEWLINE") // we shouldn't use platform-specific newlines for SMTP
private ByteBuf getBdatRequestWithData(ByteBuf data, boolean isLast) {
  String request = String.format("BDAT %d%s\r\n", data.readableBytes(), isLast ? " LAST" : "");
  ByteBuf requestBuf = channel.alloc().buffer(request.length());
  ByteBufUtil.writeAscii(requestBuf, request);

  return channel.alloc().compositeBuffer().addComponents(true, requestBuf, data);
}
 
源代码21 项目: testgrid   文件: TinkererSDK.java
/**
 * Get a list of agent for given set of test plans
 *
 * @param testPlanId    The test plan id
 * @return      List of agents for given test plan id
 */
@SuppressFBWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
public List<Agent> getAgentListByTestPlanId(String testPlanId) {
    Client client = ClientBuilder.newClient();
    Response response = client.target(this.tinkererHost + "test-plan/" + testPlanId)
            .path("agents")
            .request()
            .header(HttpHeaders.AUTHORIZATION, this.authenticationToken)
            .get();
    Type listType =  new TypeToken<List<Agent>>() { }.getType();
    return new Gson().fromJson(response.readEntity(String.class), listType);
}
 
源代码22 项目: testgrid   文件: OperationMessage.java
/**
 * Print string into a file
 *
 * @param message       The message to write into a file
 * @return              true if success, else false
 */
@SuppressFBWarnings("DMI_HARDCODED_ABSOLUTE_FILENAME")
private synchronized boolean persistMessage(String message) {
    try {
        FileUtil.saveFile(message, PERSISTED_FILE_PATH, this.operationId.concat(".txt"), true);
        this.messageQueue = new LinkedList<>();
        this.lastUpdatedTime = Calendar.getInstance().getTimeInMillis();;
        this.contentLength = 0;
        this.persisted = true;
    } catch (IOException e) {
        logger.error("Unable persist data into a file for operation id " + this.operationId, e);
        return false;
    }
    return true;
}
 
@SuppressFBWarnings(value = "BC_IMPOSSIBLE_CAST")
@SuppressWarnings(value = "unchecked")
public boolean containsAllEntries(Map<?, ?> m) {
    if (KolobokeLongObjectHashMap.identical(KolobokeLongObjectHashMap.this, m))
        throw new IllegalArgumentException();
    
    if (m instanceof LongObjMap) {
        LongObjMap m2 = ((LongObjMap) (m));
        if (m2.valueEquivalence().equals(KolobokeLongObjectHashMap.this.valueEquivalence())) {
            if ((KolobokeLongObjectHashMap.this.size()) < (m2.size()))
                return false;
            
            if ((InternalLongObjMapOps.class.isAssignableFrom(getClass())) && (m2 instanceof InternalLongObjMapOps)) {
                return ((InternalLongObjMapOps) (m2)).allEntriesContainingIn(((InternalLongObjMapOps<?>) (InternalLongObjMapOps.class.cast(KolobokeLongObjectHashMap.this))));
            } 
        } 
        return m2.forEachWhile(new LongObjPredicate() {
            @Override
            public boolean test(long a, Object b) {
                return containsEntry(a, b);
            }
        });
    } 
    for (Map.Entry<?, ?> e : m.entrySet()) {
        if (!(containsEntry(((Long) (e.getKey())), e.getValue())))
            return false;
        
    }
    return true;
}
 
@SuppressFBWarnings(value = "EC_UNRELATED_TYPES_USING_POINTER_EQUALITY")
@Override
public String toString() {
    if (KolobokeLongObjectHashMap.this.isEmpty())
        return "{}";
    
    StringBuilder sb = new StringBuilder();
    int elementCount = 0;
    int mc = modCount();
    long free = freeValue;
    long[] keys = set;
    V[] vals = values;
    for (int i = (keys.length) - 1; i >= 0; i--) {
        long key;
        if ((key = keys[i]) != free) {
            sb.append(' ');
            sb.append(key);
            sb.append('=');
            Object val = vals[i];
            sb.append((val != ((Object) (KolobokeLongObjectHashMap.this)) ? val : "(this Map)"));
            sb.append(',');
            if ((++elementCount) == 8) {
                int expectedLength = (sb.length()) * ((size()) / 8);
                sb.ensureCapacity((expectedLength + (expectedLength / 2)));
            } 
        } 
    }
    if (mc != (modCount()))
        throw new ConcurrentModificationException();
    
    sb.setCharAt(0, '{');
    sb.setCharAt(((sb.length()) - 1), '}');
    return sb.toString();
}
 
源代码25 项目: freecol   文件: AudioMixerOption.java
/**
 * {@inheritDoc}
 */
@SuppressFBWarnings(value="NP_LOAD_OF_KNOWN_NULL_VALUE")
@Override
protected void setValue(String valueString, String defaultValueString) {
    MixerWrapper mw = null;
    if (mw == null && valueString != null) {
        mw = getMixerWrapperByName(valueString);
    }
    if (mw == null && defaultValueString != null) {
        mw = getMixerWrapperByName(defaultValueString);
    }
    if (mw == null) mw = DEFAULT_MIXER_WRAPPER;
    setValue(mw);
}
 
源代码26 项目: commercetools-sync-java   文件: CategorySyncIT.java
@Test
@SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") // https://github.com/findbugsproject/findbugs/issues/79
void syncDrafts_withNewShuffledBatchOfCategories_ShouldCreateCategories() {
    //-----------------Test Setup------------------------------------
    // Delete all categories in target project
    deleteAllCategories(CTP_TARGET_CLIENT);

    // Create a total of 130 categories in the source project
    final List<Category> subFamily = createChildren(5, null, "root", CTP_SOURCE_CLIENT);

    for (final Category child : subFamily) {
        final List<Category> subsubFamily =
            createChildren(5, child, child.getName().get(Locale.ENGLISH), CTP_SOURCE_CLIENT);
        for (final Category subChild : subsubFamily) {
            createChildren(4, subChild, subChild.getName().get(Locale.ENGLISH), CTP_SOURCE_CLIENT);
        }
    }
    //---------------------------------------------------------------

    // Fetch categories from source project
    final List<Category> categories = CTP_SOURCE_CLIENT.execute(buildCategoryQuery())
                                                       .toCompletableFuture().join().getResults();

    // Put the keys in the reference ids to prepare for reference resolution
    final List<CategoryDraft> categoryDrafts = replaceCategoriesReferenceIdsWithKeys(categories);

    // Make sure there is no hierarchical order
    Collections.shuffle(categoryDrafts);

    // Simulate batches of categories where not all parent references are supplied at once.
    final List<List<CategoryDraft>> batches = batchElements(categoryDrafts, 13);

    final CategorySyncStatistics syncStatistics = syncBatches(categorySync, batches,
        CompletableFuture.completedFuture(null)).toCompletableFuture().join();

    assertThat(syncStatistics).hasValues(130, 130, 0, 0, 0);
    assertThat(callBackErrorResponses).isEmpty();
    assertThat(callBackExceptions).isEmpty();
    assertThat(callBackWarningResponses).isEmpty();
}
 
源代码27 项目: coding-snippets   文件: KolobokeLongIntHashMap.java
@SuppressFBWarnings(value = "BC_IMPOSSIBLE_CAST")
@SuppressWarnings(value = "unchecked")
public boolean containsAllEntries(Map<?, ?> m) {
    if (KolobokeLongIntHashMap.identical(KolobokeLongIntHashMap.this, m))
        throw new IllegalArgumentException();
    
    if (m instanceof LongIntMap) {
        LongIntMap m2 = ((LongIntMap) (m));
        if ((KolobokeLongIntHashMap.this.size()) < (m2.size()))
            return false;
        
        if ((InternalLongIntMapOps.class.isAssignableFrom(getClass())) && (m2 instanceof InternalLongIntMapOps)) {
            return ((InternalLongIntMapOps) (m2)).allEntriesContainingIn(((InternalLongIntMapOps) (InternalLongIntMapOps.class.cast(KolobokeLongIntHashMap.this))));
        } 
        return m2.forEachWhile(new LongIntPredicate() {
            @Override
            public boolean test(long a, int b) {
                return containsEntry(a, b);
            }
        });
    } 
    for (Map.Entry<?, ?> e : m.entrySet()) {
        if (!(containsEntry(((Long) (e.getKey())), ((Integer) (e.getValue())))))
            return false;
        
    }
    return true;
}
 
源代码28 项目: commercetools-sync-java   文件: InventorySync.java
/**
 * Given an existing {@link InventoryEntry} and a new {@link InventoryEntryDraft}, the method calculates all the
 * update actions required to synchronize the existing entry to be the same as the new one. If there are update
 * actions found, a request is made to CTP to update the existing entry, otherwise it doesn't issue a request.
 *
 * <p>The {@code statistics} instance is updated accordingly to whether the CTP request was carried
 * out successfully or not. If an exception was thrown on executing the request to CTP, the error handling method
 * is called.
 *
 * @param entry existing inventory entry that could be updated.
 * @param draft draft containing data that could differ from data in {@code entry}.
 *              <strong>Sku isn't compared</strong>
 * @return a future which contains an empty result after execution of the update.
 */
@SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") // https://github.com/findbugsproject/findbugs/issues/79
private CompletionStage<Optional<InventoryEntry>> buildActionsAndUpdate(
    @Nonnull final InventoryEntry entry,
    @Nonnull final InventoryEntryDraft draft) {

    final List<UpdateAction<InventoryEntry>> updateActions = buildActions(entry, draft, syncOptions);

    final List<UpdateAction<InventoryEntry>> beforeUpdateCallBackApplied =
        syncOptions.applyBeforeUpdateCallBack(updateActions, draft, entry);

    if (!beforeUpdateCallBackApplied.isEmpty()) {
        return inventoryService
            .updateInventoryEntry(entry, beforeUpdateCallBackApplied)
            .handle(ImmutablePair::new)
            .thenCompose(updateResponse -> {
                final InventoryEntry updatedInventoryEntry = updateResponse.getKey();
                final Throwable sphereException = updateResponse.getValue();
                if (sphereException != null) {
                    final ResourceIdentifier<Channel> supplyChannel = draft.getSupplyChannel();
                    final String errorMessage = format(CTP_INVENTORY_ENTRY_UPDATE_FAILED, draft.getSku(),
                        supplyChannel != null ? supplyChannel.getId() : null);
                    handleError(errorMessage, sphereException, 1);
                    return CompletableFuture.completedFuture(Optional.empty());
                } else {
                    statistics.incrementUpdated();
                    return CompletableFuture.completedFuture(Optional.of(updatedInventoryEntry));
                }
            });
    }
    return completedFuture(null);
}
 
源代码29 项目: coding-snippets   文件: KolobokeLongIntHashMap.java
@SuppressFBWarnings(value = "EC_UNRELATED_TYPES_USING_POINTER_EQUALITY")
@Override
public String toString() {
    if (KolobokeLongIntHashMap.this.isEmpty())
        return "{}";
    
    StringBuilder sb = new StringBuilder();
    int elementCount = 0;
    int mc = modCount();
    long free = freeValue;
    long[] keys = set;
    int[] vals = values;
    for (int i = (keys.length) - 1; i >= 0; i--) {
        long key;
        if ((key = keys[i]) != free) {
            sb.append(' ');
            sb.append(key);
            sb.append('=');
            sb.append(vals[i]);
            sb.append(',');
            if ((++elementCount) == 8) {
                int expectedLength = (sb.length()) * ((size()) / 8);
                sb.ensureCapacity((expectedLength + (expectedLength / 2)));
            } 
        } 
    }
    if (mc != (modCount()))
        throw new ConcurrentModificationException();
    
    sb.setCharAt(0, '{');
    sb.setCharAt(((sb.length()) - 1), '}');
    return sb.toString();
}
 
/**
 * Start processing the tasks.
 */
@SuppressFBWarnings(
        value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE",
        justification = "Return future ignored since the execution needs be done asynchronously.")
public synchronized void start() {
    log.info("Starting task manager. Task count {}", taskHolderDelayQueue.size());

    for (int i = 0; i < workerCount; i++) {
        TaskProcessor taskProcessor =
                new TaskProcessor(taskHolderDelayQueue, taskExceptionHandler, idleTaskDelayMillis);
        taskProcessorQueue.add(taskProcessor);
        taskExecutorPool.submit(taskProcessor);
    }
}