java.util.Arrays Java Examples

The following examples show how to use java.util.Arrays. 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 File: SchemaRegistryServiceImpl.java    From pulsar with Apache License 2.0 8 votes vote down vote up
@Override
public CompletableFuture<SchemaVersion> getSchemaVersionBySchemaData(
        List<SchemaAndMetadata> schemaAndMetadataList,
        SchemaData schemaData) {
    final CompletableFuture<SchemaVersion> completableFuture = new CompletableFuture<>();
    SchemaVersion schemaVersion;
    for (SchemaAndMetadata schemaAndMetadata : schemaAndMetadataList) {
        if (Arrays.equals(hashFunction.hashBytes(schemaAndMetadata.schema.getData()).asBytes(),
                hashFunction.hashBytes(schemaData.getData()).asBytes())) {
            schemaVersion = schemaAndMetadata.version;
            completableFuture.complete(schemaVersion);
            return completableFuture;
        }
    }
    completableFuture.complete(null);
    return completableFuture;
}
 
Example #2
Source File: NodeListAddRemoveTest.java    From flow with Apache License 2.0 8 votes vote down vote up
@Test
public void removeOperationAfterDelete_addRemove_subsequentOperationsAreNotAffected() {
    List<String> items = resetToRemoveAfterAddCase();

    nodeList.add("foo");
    int index = items.size();
    nodeList.remove(index);

    nodeList.remove(index - 1);
    // As a result: "remove" and "add" before it are discarded and the last
    // "remove" operation is not affected
    List<NodeChange> changes = collectChanges(nodeList);
    Assert.assertEquals(1, changes.size());
    Assert.assertTrue(changes.get(0) instanceof ListRemoveChange<?>);

    verifyRemoved(changes, Arrays.asList(items.get(index - 1)), index - 1);
}
 
Example #3
Source File: JmxDumper.java    From helix with Apache License 2.0 6 votes vote down vote up
private static boolean checkOptionArgsNumber(Option[] options) {
  for (Option option : options) {
    int argNb = option.getArgs();
    String[] args = option.getValues();
    if (argNb == 0) {
      if (args != null && args.length > 0) {
        System.err.println(option.getArgName() + " shall have " + argNb + " arguments (was "
            + Arrays.toString(args) + ")");
        return false;
      }
    } else {
      if (args == null || args.length != argNb) {
        System.err.println(option.getArgName() + " shall have " + argNb + " arguments (was "
            + Arrays.toString(args) + ")");
        return false;
      }
    }
  }
  return true;
}
 
Example #4
Source File: BusinessObjectDataNotificationRegistrationServiceTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetBusinessObjectDataNotificationRegistrationsByNotificationFilterTrimParameters()
{
    // Create a business object data notification registration key.
    NotificationRegistrationKey notificationRegistrationKey = new NotificationRegistrationKey(NAMESPACE, NOTIFICATION_NAME);

    // Create and persist a business object data notification registration entity.
    notificationRegistrationDaoTestHelper.createBusinessObjectDataNotificationRegistrationEntity(notificationRegistrationKey,
        NotificationEventTypeEntity.EventTypesBdata.BUS_OBJCT_DATA_STTS_CHG.name(), BDEF_NAMESPACE, BDEF_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE,
        FORMAT_VERSION, STORAGE_NAME, BDATA_STATUS, BDATA_STATUS_2, notificationRegistrationDaoTestHelper.getTestJobActions(),
        NotificationRegistrationStatusEntity.ENABLED);

    // Retrieve a list of business object data notification registration keys using input parameters with leading and trailing empty spaces.
    assertEquals(new BusinessObjectDataNotificationRegistrationKeys(Arrays.asList(notificationRegistrationKey)),
        businessObjectDataNotificationRegistrationService.getBusinessObjectDataNotificationRegistrationsByNotificationFilter(
            new BusinessObjectDataNotificationFilter(addWhitespace(BDEF_NAMESPACE), addWhitespace(BDEF_NAME), addWhitespace(FORMAT_USAGE_CODE),
                addWhitespace(FORMAT_FILE_TYPE_CODE), NO_FORMAT_VERSION, NO_STORAGE_NAME, NO_BDATA_STATUS, NO_BDATA_STATUS)));
}
 
Example #5
Source File: PolyhedronTest.java    From javascad with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void boundariesShouldBeDefinedByTheLowestAndHighestPoints() {
	Coords3d c1 = new Coords3d(0.0, 10.0, 20.0);
	Coords3d c2 = new Coords3d(15.5, 7.0, 30.0);
	Coords3d c3 = new Coords3d(20.0, 3.14, 40.0);
	Coords3d c4 = new Coords3d(25.0, 5, 60.0);
	
	Triangle3d t1 = new Triangle3d(c1, c2, c3);
	Triangle3d t2 = new Triangle3d(c2, c3, c4);
	
	Polyhedron polyhedron = new Polyhedron(Arrays.asList(t1, t2));
	
	Boundaries3d boundaries = polyhedron.getBoundaries();
	
	assertDoubleEquals(0.0, boundaries.getX().getMin());
	assertDoubleEquals(25.0, boundaries.getX().getMax());
	
	assertDoubleEquals(3.14, boundaries.getY().getMin());
	assertDoubleEquals(10.0, boundaries.getY().getMax());
	
	assertDoubleEquals(20.0, boundaries.getZ().getMin());
	assertDoubleEquals(60.0, boundaries.getZ().getMax());
}
 
Example #6
Source File: AbstractIOTestBase.java    From cyclops with Apache License 2.0 6 votes vote down vote up
@Test
public void recoverWithRecursiveList(){

    AtomicInteger count = new AtomicInteger(0);
    List<Integer> result = of(1, 2, 3).<Integer>map(i -> {
        throw new RuntimeException();
    })
        .recoverWith(e->of(100,200,300).peek(i-> {
            if (count.incrementAndGet() < 200)
                throw new RuntimeException();
        }))
        .stream()
        .toList();


    assertThat(count.get(),greaterThan(200));

    assertThat(result,equalTo(Arrays.asList(100,200,300)));
}
 
Example #7
Source File: TestMigrationManager.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasic()
{
    Migration m1 = () -> Arrays.asList(v1opA, v1opB);
    Migration m2 = () -> Collections.singletonList(v2op);
    Migration m3 = () -> Collections.singletonList(v3op);
    MigrationSet migrationSet = MigrationSet.build("1", Arrays.asList(m1, m2, m3));

    complete(manager.migrate(migrationSet));

    ModeledFramework<ModelV3> v3Client = ModeledFramework.wrap(client, v3Spec);
    complete(v3Client.read(), (m, e) -> {
        Assert.assertEquals(m.getAge(), 30);
        Assert.assertEquals(m.getFirstName(), "One");
        Assert.assertEquals(m.getLastName(), "Two");
    });

    int count = manager.debugCount.get();
    complete(manager.migrate(migrationSet));
    Assert.assertEquals(manager.debugCount.get(), count);   // second call should do nothing
}
 
Example #8
Source File: HttpURLConnection.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns an unmodifiable Map of general request
 * properties for this connection. The Map keys
 * are Strings that represent the request-header
 * field names. Each Map value is a unmodifiable List
 * of Strings that represents the corresponding
 * field values.
 *
 * @return  a Map of the general request properties for this connection.
 * @throws IllegalStateException if already connected
 * @since 1.4
 */
@Override
public synchronized Map<String, List<String>> getRequestProperties() {
    if (connected)
        throw new IllegalStateException("Already connected");

    // exclude headers containing security-sensitive info
    if (setUserCookies) {
        return requests.getHeaders(EXCLUDE_HEADERS);
    }
    /*
     * The cookies in the requests message headers may have
     * been modified. Use the saved user cookies instead.
     */
    Map<String, List<String>> userCookiesMap = null;
    if (userCookies != null || userCookies2 != null) {
        userCookiesMap = new HashMap<>();
        if (userCookies != null) {
            userCookiesMap.put("Cookie", Arrays.asList(userCookies));
        }
        if (userCookies2 != null) {
            userCookiesMap.put("Cookie2", Arrays.asList(userCookies2));
        }
    }
    return requests.filterAndAddHeaders(EXCLUDE_HEADERS2, userCookiesMap);
}
 
Example #9
Source File: ConfigDefaultTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
public void testGetJsonMapConfig() throws Exception {
    config.clear();
    Map<String, Object> configMap = config.getJsonMapConfig("test");
    // case1: regular config
    Assert.assertEquals("default config", configMap.get("value"));
    // case2: config with environment variable
    if (!OS.startsWith("windows")) {
        Assert.assertEquals(System.getenv("HOME"), configMap.get("value1"));
    }
    // case3: escape from injecting environment variable
    Assert.assertEquals("${ESCAPE}", configMap.get("value2"));
    // case4: override to map with centralized file
    Assert.assertEquals("test", configMap.get("value3"));
    // case5: override to map with centralized file
    Assert.assertEquals(Arrays.asList("element1", "element2"), configMap.get("value4"));
    // case6: override to map with centralized file
    Assert.assertEquals(testMap, configMap.get("value5"));
    // case7: default value start with $ but not escape
    Assert.assertEquals("$abc", configMap.get("value6"));
}
 
Example #10
Source File: MongoResourceRepositoryTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void testFindByDomain() throws TechnicalException {
    // create resource_set, resource_scopes being the most important field.
    Resource resource1 = new Resource().setResourceScopes(Arrays.asList("a","b","c")).setDomain(DOMAIN_ID).setClientId(CLIENT_ID).setUserId(USER_ID);
    Resource resource2 = new Resource().setResourceScopes(Arrays.asList("d","e","f")).setDomain(DOMAIN_ID).setClientId(CLIENT_ID).setUserId(USER_ID);

    repository.create(resource1).blockingGet();
    repository.create(resource2).blockingGet();

    // fetch applications
    TestObserver<Page<Resource>> testObserver = repository.findByDomain(DOMAIN_ID, 0, Integer.MAX_VALUE).test();
    testObserver.awaitTerminalEvent();

    testObserver.assertComplete();
    testObserver.assertNoErrors();
    testObserver.assertValue(resources -> resources.getData().size() == 2);
}
 
Example #11
Source File: SourceGroupSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static List<ClassPath> gerClassPath(Project project) {
    List<ClassPath> paths = new ArrayList<ClassPath>();
    List<SourceGroup> groups = new ArrayList<SourceGroup>();
    groups.addAll(Arrays.asList(ProjectUtils.getSources(project).getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA)));
    ClassPathProvider cpp = project.getLookup().lookup(ClassPathProvider.class);
    for (SourceGroup group : groups) {
        ClassPath cp = cpp.findClassPath(group.getRootFolder(), ClassPath.COMPILE);
        if (cp != null) {
            paths.add(cp);
        }
        cp = cpp.findClassPath(group.getRootFolder(), ClassPath.SOURCE);
        if (cp != null) {
            paths.add(cp);
        }
    }
    return paths;
}
 
Example #12
Source File: VoteProposerTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void emptyProposerReturnsNoVotes() {
  final VoteProposer proposer = new VoteProposer();

  assertThat(proposer.getVote(localAddress, new VoteTally(Collections.emptyList())))
      .isEqualTo(Optional.empty());
  assertThat(
          proposer.getVote(
              localAddress,
              new VoteTally(
                  Arrays.asList(
                      Address.fromHexString("0"),
                      Address.fromHexString("1"),
                      Address.fromHexString("2")))))
      .isEqualTo(Optional.empty());
}
 
Example #13
Source File: PersonDataTests.java    From entref-spring-boot with MIT License 6 votes vote down vote up
@Test
public void insert_Success() {
    String id = "nm0000001";
    Person newPerson = new Person();
    newPerson.nconst = id;
    newPerson.birthYear = 2020;
    newPerson.primaryName = "Tim Tam";
    newPerson.primaryProfession = Arrays.asList("Test", "Dancer");

    assertThat(this.repo.insert(newPerson), is(newPerson));
    assertThat(this.repo.count(), is(2L));

    Person actual = this.repo.findById(id).get();

    assertThat(actual.nconst, is(id));
    assertThat(actual.primaryName, is("Tim Tam"));
    assertThat(actual.birthYear, is(2020));
    assertThat(actual.deathYear, is(nullValue()));
    assertThat(actual.primaryProfession, is(Arrays.asList("Test", "Dancer")));
    assertThat(actual.knownForTitles, is(nullValue()));
}
 
Example #14
Source File: SqlQueriesTopologyMappingTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** */
private void checkQueryWithRebalance(CacheMode cacheMode) throws Exception {
    IgniteEx ign0 = startGrid(0);

    IgniteCache<Object, Object> cache = ign0.createCache(new CacheConfiguration<>(DEFAULT_CACHE_NAME)
        .setCacheMode(cacheMode)
        .setIndexedTypes(Integer.class, Integer.class));

    cache.put(1, 2);

    blockRebalanceSupplyMessages(ign0, DEFAULT_CACHE_NAME, getTestIgniteInstanceName(1));

    startGrid(1);
    startClientGrid(10);

    for (Ignite ign : G.allGrids()) {
        List<List<?>> res = ign.cache(DEFAULT_CACHE_NAME)
            .query(new SqlFieldsQuery("select * from Integer")).getAll();

        assertEquals(1, res.size());
        assertEqualsCollections(Arrays.asList(1, 2), res.get(0));
    }
}
 
Example #15
Source File: AWSCodePipelinePublisherTest.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 6 votes vote down vote up
@Test
public void putsJobSuccessWhenBuildSucceeds() {
    // given
    when(mockBuild.getResult()).thenReturn(Result.SUCCESS);
    when(mockJobData.getOutputArtifacts()).thenReturn(generateOutputArtifactsWithNames(Arrays.asList("artifact_1", "artifact_2")));

    // when
    assertTrue(publisher.perform(mockBuild, null, null));

    // then
    final InOrder inOrder = inOrder(mockFactory, mockAWS, mockCodePipelineClient);
    inOrder.verify(mockFactory).getAwsClient(ACCESS_KEY, SECRET_KEY, PROXY_HOST, PROXY_PORT, REGION, PLUGIN_VERSION);
    inOrder.verify(mockAWS).getCodePipelineClient();
    inOrder.verify(mockCodePipelineClient).putJobSuccessResult(putJobSuccessResultRequest.capture());

    final PutJobSuccessResultRequest request = putJobSuccessResultRequest.getValue();
    assertEquals(jobId, request.getJobId());
    assertEquals(BUILD_ID, request.getExecutionDetails().getExternalExecutionId());
    assertEquals("Finished", request.getExecutionDetails().getSummary());

    assertContainsIgnoreCase(PUBLISHING_ARTIFACTS_MESSAGE, outContent.toString());
    assertContainsIgnoreCase(PUT_JOB_SUCCESS_MESSAGE, outContent.toString());
}
 
Example #16
Source File: FormatTest.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@Override
public boolean equals(java.lang.Object o) {
  if (this == o) {
    return true;
  }
  if (o == null || getClass() != o.getClass()) {
    return false;
  }
  FormatTest formatTest = (FormatTest) o;
  return Objects.equals(this.integer, formatTest.integer) &&
      Objects.equals(this.int32, formatTest.int32) &&
      Objects.equals(this.int64, formatTest.int64) &&
      Objects.equals(this.number, formatTest.number) &&
      Objects.equals(this._float, formatTest._float) &&
      Objects.equals(this._double, formatTest._double) &&
      Objects.equals(this.string, formatTest.string) &&
      Arrays.equals(this._byte, formatTest._byte) &&
      Objects.equals(this.binary, formatTest.binary) &&
      Objects.equals(this.date, formatTest.date) &&
      Objects.equals(this.dateTime, formatTest.dateTime) &&
      Objects.equals(this.uuid, formatTest.uuid) &&
      Objects.equals(this.password, formatTest.password) &&
      Objects.equals(this.bigDecimal, formatTest.bigDecimal);
}
 
Example #17
Source File: FacetMapperTest.java    From vind with Apache License 2.0 6 votes vote down vote up
@Test
public void testComplexField() throws SyntaxError {

    HashMap<String, String> dateIntervals = new HashMap<>();
    dateIntervals.put("after","[NOW+23DAYS/DAY TO *]");
    dateIntervals.put("before","[* TO NOW+23DAYS/DAY]");

    HashMap<String, String> numberIntervals = new HashMap<>();
    numberIntervals.put("bigger","[23 TO *]");
    numberIntervals.put("smaller","[* TO 22]");

    SingleValuedComplexField.UtilDateComplexField<Taxonomy,Date,Date> complexDateField = new ComplexFieldDescriptorBuilder<Taxonomy,Date,Date>()
            .setFacet(true, tax -> Arrays.asList(tax.getDate()))
            .buildUtilDateComplexField("complexDateTax", Taxonomy.class, Date.class, Date.class);

    SingleValuedComplexField.NumericComplexField<Taxonomy,Number,Number> complexNumberField = new ComplexFieldDescriptorBuilder<Taxonomy,Number,Number>()
            .setFacet(true, tax -> Arrays.asList(tax.getTerm()))
            .buildNumericComplexField("complexNumberTax", Taxonomy.class, Number.class, Number.class);

    Assert.assertTrue(FacetMapper.stringQuery2FacetMapper(complexDateField, "dateFacet",dateIntervals).getName().equals("dateFacet"));
    Assert.assertTrue(FacetMapper.stringQuery2FacetMapper(complexNumberField, "numericFacet", numberIntervals).getName().equals("numericFacet"));

    Assert.assertTrue(true);
}
 
Example #18
Source File: ECKeyTest.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testCreatedSigAndPubkeyAreCanonical() throws Exception {
    // Tests that we will not generate non-canonical pubkeys or signatures
    // We dump failed data to error log because this test is not expected to be deterministic
    ECKey key = new ECKey();
    if (!ECKey.isPubKeyCanonical(key.getPubKey())) {
        log.error(Utils.HEX.encode(key.getPubKey()));
        fail();
    }

    byte[] hash = new byte[32];
    new Random().nextBytes(hash);
    byte[] sigBytes = key.sign(Sha256Hash.wrap(hash)).encodeToDER();
    byte[] encodedSig = Arrays.copyOf(sigBytes, sigBytes.length + 1);
    encodedSig[sigBytes.length] = Transaction.SigHash.ALL.byteValue();
    if (!TransactionSignature.isEncodingCanonical(encodedSig)) {
        log.error(Utils.HEX.encode(sigBytes));
        fail();
    }
}
 
Example #19
Source File: FlexMessageGenerator.java    From line-sdk-android with Apache License 2.0 5 votes vote down vote up
/**
 * This function help to generate 4 line of texts with 3 separators like below:
 * <p>
 * text1
 * ------
 * text2
 * ------
 * text3
 * ------
 * text4
 *
 * @return the generated FlexBoxComponent with 4 vertically arranged texts.
 */
@NonNull
private FlexBoxComponent createBodyContentRightBoxComponent() {
    FlexSeparatorComponent separatorComponent = new FlexSeparatorComponent();
    FlexTextComponent text1 = FlexTextComponent.newBuilder("7 Things to Know for Today")
            .setGravity(FlexMessageComponent.Gravity.TOP)
            .setSize(FlexMessageComponent.Size.XS)
            .setFlex(1)
            .build();
    FlexTextComponent text2 = FlexTextComponent.newBuilder("Hay fever goes wild")
            .setGravity(FlexMessageComponent.Gravity.CENTER)
            .setSize(FlexMessageComponent.Size.XS)
            .setFlex(2)
            .build();
    FlexTextComponent text3 = FlexTextComponent.newBuilder("LINE Pay Begins Barcode Payment Service")
            .setGravity(FlexMessageComponent.Gravity.CENTER)
            .setSize(FlexMessageComponent.Size.XS)
            .setFlex(2)
            .build();
    FlexTextComponent text4 = FlexTextComponent.newBuilder("LINE Adds LINE Wallet")
            .setGravity(FlexMessageComponent.Gravity.BOTTOM)
            .setSize(FlexMessageComponent.Size.XS)
            .setFlex(1)
            .build();

    return FlexBoxComponent.newBuilder(FlexMessageComponent.Layout.VERTICAL,
            Arrays.asList(text1,
                    separatorComponent,
                    text2,
                    separatorComponent,
                    text3,
                    separatorComponent,
                    text4))
            .setFlex(2)
            .build();
}
 
Example #20
Source File: TestRDFChangesGraph.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
private static void check(Graph graph, Triple...quads) {
    if ( quads.length == 0 ) {
        assertTrue(graph.isEmpty());
        return;
    }
    List<Triple> listExpected = Arrays.asList(quads);
    List<Triple> listActual = Iter.toList(graph.find());
    assertEquals(listActual.size(), listExpected.size());
    assertTrue(ListUtils.equalsUnordered(listExpected, listActual));
}
 
Example #21
Source File: BlockTest.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testUpdateLength() {
    NetworkParameters params = UnitTestParams.get();
    Block block = params.getGenesisBlock().createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, new ECKey().getPubKey(), Block.BLOCK_HEIGHT_GENESIS);
    assertEquals(block.bitcoinSerialize().length, block.length);
    final int origBlockLen = block.length;
    Transaction tx = new Transaction(params);
    // this is broken until the transaction has > 1 input + output (which is required anyway...)
    //assertTrue(tx.length == tx.bitcoinSerialize().length && tx.length == 8);
    byte[] outputScript = new byte[10];
    Arrays.fill(outputScript, (byte) ScriptOpCodes.OP_FALSE);
    tx.addOutput(new TransactionOutput(params, null, Coin.SATOSHI, outputScript));
    tx.addInput(new TransactionInput(params, null, new byte[] {(byte) ScriptOpCodes.OP_FALSE},
            new TransactionOutPoint(params, 0, Sha256Hash.of(new byte[] { 1 }))));
    int origTxLength = 8 + 2 + 8 + 1 + 10 + 40 + 1 + 1;
    assertEquals(tx.unsafeBitcoinSerialize().length, tx.length);
    assertEquals(origTxLength, tx.length);
    block.addTransaction(tx);
    assertEquals(block.unsafeBitcoinSerialize().length, block.length);
    assertEquals(origBlockLen + tx.length, block.length);
    block.getTransactions().get(1).getInputs().get(0).setScriptBytes(new byte[] {(byte) ScriptOpCodes.OP_FALSE, (byte) ScriptOpCodes.OP_FALSE});
    assertEquals(block.length, origBlockLen + tx.length);
    assertEquals(tx.length, origTxLength + 1);
    block.getTransactions().get(1).getInputs().get(0).clearScriptBytes();
    assertEquals(block.length, block.unsafeBitcoinSerialize().length);
    assertEquals(block.length, origBlockLen + tx.length);
    assertEquals(tx.length, origTxLength - 1);
    block.getTransactions().get(1).addInput(new TransactionInput(params, null, new byte[] {(byte) ScriptOpCodes.OP_FALSE},
            new TransactionOutPoint(params, 0, Sha256Hash.of(new byte[] { 1 }))));
    assertEquals(block.length, origBlockLen + tx.length);
    assertEquals(tx.length, origTxLength + 41); // - 1 + 40 + 1 + 1
}
 
Example #22
Source File: RecoverableMultiPartUploadImplTest.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(Object o) {
	if (this == o) {
		return true;
	}
	if (o == null || getClass() != o.getClass()) {
		return false;
	}

	final TestPutObjectResult that = (TestPutObjectResult) o;
	// we ignore the etag as it contains randomness
	return Arrays.equals(getContent(), that.getContent());
}
 
Example #23
Source File: QuerySqlTranslatorTest.java    From sync-android with Apache License 2.0 5 votes vote down vote up
@Test
public void validWhereNOTClauseForSingleTermEQ() throws QueryException {
    Map<String, Object> eq = new HashMap<String, Object>();
    eq.put("$eq", "mike");
    Map<String, Object> not = new HashMap<String, Object>();
    not.put("$not", eq);
    Map<String, Object> name = new HashMap<String, Object>();
    name.put("name", not);
    SqlParts where = QuerySqlTranslator.whereSqlForAndClause(Arrays.<Object>asList(name),
                                                             indexName);
    String expected = String.format("_id NOT IN (SELECT _id FROM \"%s\" WHERE \"name\" = ?)",
                                    indexTable);
    assertThat(where.sqlWithPlaceHolders, is(expected));
    assertThat(where.placeHolderValues, is(arrayContaining("mike")));
}
 
Example #24
Source File: AddReadsTestWarningError.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "missingArguments")
public void testEmptyArgument(String[] options, String msg) throws Exception {
    String[] args = Stream.concat(Arrays.stream(options), Stream.of("-version"))
                          .toArray(String[]::new);
    int exitValue = executeTestJava(args)
        .outputTo(System.out)
        .errorTo(System.out)
        .shouldContain(msg)
        .getExitValue();

    assertTrue(exitValue != 0);
}
 
Example #25
Source File: Sonic.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns {@code buffer} or a copy of it, such that there is enough space in the returned buffer
 * to store {@code newFrameCount} additional frames.
 *
 * @param buffer The buffer.
 * @param frameCount The number of frames already in the buffer.
 * @param additionalFrameCount The number of additional frames that need to be stored in the
 *     buffer.
 * @return A buffer with enough space for the additional frames.
 */
private short[] ensureSpaceForAdditionalFrames(
    short[] buffer, int frameCount, int additionalFrameCount) {
  int currentCapacityFrames = buffer.length / channelCount;
  if (frameCount + additionalFrameCount <= currentCapacityFrames) {
    return buffer;
  } else {
    int newCapacityFrames = 3 * currentCapacityFrames / 2 + additionalFrameCount;
    return Arrays.copyOf(buffer, newCapacityFrames * channelCount);
  }
}
 
Example #26
Source File: StringCoding.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
private static char[] safeTrim(char[] ca, int len,
                               Charset cs, boolean isTrusted) {
    if (len == ca.length && (isTrusted || System.getSecurityManager() == null))
        return ca;
    else
        return Arrays.copyOf(ca, len);
}
 
Example #27
Source File: PartitionSpec.java    From iceberg with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(Object other) {
  if (this == other) {
    return true;
  } else if (!(other instanceof PartitionSpec)) {
    return false;
  }

  PartitionSpec that = (PartitionSpec) other;
  if (this.specId != that.specId) {
    return false;
  }
  return Arrays.equals(fields, that.fields);
}
 
Example #28
Source File: AlawEncoderSync.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    preparePCMBuffer();
    log("pcmStream size: " + pcmBuffer.length);

    for (int i=0; i<THREAD_COUNT; i++) {
        threads[i] = new ConversionThread(i);
        threads[i].start();
    }

    for (int i=0; i<THREAD_COUNT; i++) {
        try {
            threads[i].join();
        } catch (InterruptedException ex) {
            log("Main thread was interrupted, exiting.");
            return;
        }
    }

    int failed = 0;
    log("comparing result arrays...");
    for (int i=1; i<THREAD_COUNT; i++) {
        if (!Arrays.equals(threads[0].resultArray, threads[i].resultArray)) {
            failed++;
            log("NOT equals: 0 and " + i);
        }
    }
    if (failed > 0) {
        throw new RuntimeException("test FAILED");
    }
    log("test PASSED.");
}
 
Example #29
Source File: DecodeFormatManager.java    From QrScan with Apache License 2.0 5 votes vote down vote up
static Vector<BarcodeFormat> parseDecodeFormats(Uri inputUri) {
  List<String> formats = inputUri.getQueryParameters(Intents.Scan.SCAN_FORMATS);
  if (formats != null && formats.size() == 1 && formats.get(0) != null){
    formats = Arrays.asList(COMMA_PATTERN.split(formats.get(0)));
  }
  return parseDecodeFormats(formats, inputUri.getQueryParameter(Intents.Scan.MODE));
}
 
Example #30
Source File: StringUtils.java    From big-c with Apache License 2.0 5 votes vote down vote up
static void startupShutdownMessage(Class<?> clazz, String[] args,
                                   final LogAdapter LOG) { 
  final String hostname = NetUtils.getHostname();
  final String classname = clazz.getSimpleName();
  LOG.info(
      toStartupShutdownString("STARTUP_MSG: ", new String[] {
          "Starting " + classname,
          "  host = " + hostname,
          "  args = " + Arrays.asList(args),
          "  version = " + VersionInfo.getVersion(),
          "  classpath = " + System.getProperty("java.class.path"),
          "  build = " + VersionInfo.getUrl() + " -r "
                       + VersionInfo.getRevision()  
                       + "; compiled by '" + VersionInfo.getUser()
                       + "' on " + VersionInfo.getDate(),
          "  java = " + System.getProperty("java.version") }
      )
    );

  if (SystemUtils.IS_OS_UNIX) {
    try {
      SignalLogger.INSTANCE.register(LOG);
    } catch (Throwable t) {
      LOG.warn("failed to register any UNIX signal loggers: ", t);
    }
  }
  ShutdownHookManager.get().addShutdownHook(
    new Runnable() {
      @Override
      public void run() {
        LOG.info(toStartupShutdownString("SHUTDOWN_MSG: ", new String[]{
          "Shutting down " + classname + " at " + hostname}));
      }
    }, SHUTDOWN_HOOK_PRIORITY);

}