Java Code Examples for edu.umd.cs.findbugs.annotations.SuppressFBWarnings

The following examples show how to use edu.umd.cs.findbugs.annotations.SuppressFBWarnings. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: commercetools-sync-java   Source File: ProductSync.java    License: Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example 2
Source Project: GDH   Source File: CipherAgentImpl.java    License: MIT License 6 votes vote down vote up
/**
 * 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());
}
 
Example 3
Source Project: arctic-sea   Source File: SweHelper.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 4
Source Project: waltz   Source File: AppendRequest.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 5
Source Project: testgrid   Source File: TinkererSDK.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 6
Source Project: waltz   Source File: DemoAppBase.java    License: Apache License 2.0 6 votes vote down vote up
@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
    );
}
 
Example 7
Source Project: freecol   Source File: ModifierFormat.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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;
}
 
Example 8
Source Project: syndesis   Source File: DbMetaDataHelper.java    License: Apache License 2.0 6 votes vote down vote up
@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;
    }
}
 
Example 9
Source Project: warnings-ng-plugin   Source File: StageResultHandlerTest.java    License: MIT License 6 votes vote down vote up
@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)));
}
 
Example 10
Source Project: warnings-ng-plugin   Source File: IntegrationTest.java    License: MIT License 6 votes vote down vote up
@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;
}
 
Example 11
Source Project: butterfly   Source File: EolHelper.java    License: MIT License 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 12
Source Project: plugin-installation-manager-tool   Source File: CliOptions.java    License: MIT License 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 13
Source Project: hadoop-ozone   Source File: PipelineStateMap.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 14
Source Project: hadoop-ozone   Source File: ReplicationManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Process all the containers immediately.
 */
@VisibleForTesting
@SuppressFBWarnings(value="NN_NAKED_NOTIFY",
    justification="Used only for testing")
public synchronized void processContainersNow() {
  notifyAll();
}
 
Example 15
Source Project: testgrid   Source File: OperationMessage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 16
Source Project: ballerina-message-broker   Source File: XidImpl.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 17
Source Project: arctic-sea   Source File: Identifier.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 18
Source Project: BungeeChat2   Source File: Account.java    License: GNU General Public License v3.0 5 votes vote down vote up
@SuppressFBWarnings(
    value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD",
    justification = "Rarely every used, so no issue")
@Override
public void setDefaultChannelType(ChannelType channelType) {
  defaultChannelType = channelType;
}
 
Example 19
Source Project: waltz   Source File: StoreAppendRequest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 20
Source Project: commercetools-sync-java   Source File: CategorySync.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 21
Source Project: NioSmtpClient   Source File: SmtpSession.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 22
Source Project: testgrid   Source File: OperationMessage.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 23
Source Project: coding-snippets   Source File: KolobokeLongObjectHashMap.java    License: MIT License 5 votes vote down vote up
@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;
}
 
Example 24
Source Project: coding-snippets   Source File: KolobokeLongObjectHashMap.java    License: MIT License 5 votes vote down vote up
@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();
}
 
Example 25
Source Project: freecol   Source File: AudioMixerOption.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@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);
}
 
Example 26
Source Project: commercetools-sync-java   Source File: CategorySyncIT.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 27
Source Project: coding-snippets   Source File: KolobokeLongIntHashMap.java    License: MIT License 5 votes vote down vote up
@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;
}
 
Example 28
Source Project: commercetools-sync-java   Source File: InventorySync.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 29
Source Project: coding-snippets   Source File: KolobokeLongIntHashMap.java    License: MIT License 5 votes vote down vote up
@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();
}
 
Example 30
/**
 * 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);
    }
}