Java Code Examples for java.util.Arrays#asList()

The following examples show how to use java.util.Arrays#asList() . 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: EmbeddedKafka.java    From modernmt with Apache License 2.0 5 votes vote down vote up
private void start(String netInterface, int port) throws IOException {
    if (!NetworkUtils.isAvailable(port))
        throw new IOException("Port " + port + " is already in use by another process");

    FileUtils.deleteDirectory(this.runtime);
    FileUtils.forceMkdir(this.runtime);
    deleteClusterId();  // we want to delete saved cluster-id because we reset Zookeeper at every startup

    FileUtils.deleteQuietly(this.logFile);
    FileUtils.touch(this.logFile);

    Process zookeeper = null;
    Process kafka;

    boolean success = false;

    try {
        int zookeperPort = NetworkUtils.getAvailablePort();

        zookeeper = this.startZookeeper(zookeperPort);
        kafka = this.startKafka(netInterface, port, zookeperPort);

        success = true;
    } finally {
        if (!success)
            this.kill(zookeeper, 1, TimeUnit.SECONDS);
    }

    this.subprocesses = Arrays.asList(kafka, zookeeper);
}
 
Example 2
Source File: GRUCell.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
@Override
public List<DataType> calculateOutputDataTypes(List<DataType> inputDataTypes){
    Preconditions.checkState(inputDataTypes != null && inputDataTypes.size() == 6, "Expected exactly 6 inputs to GRUCell, got %s", inputDataTypes);
    //4 outputs, all of same type as input
    DataType dt = inputDataTypes.get(0);
    Preconditions.checkState(dt.isFPType(), "Input type 0 must be a floating point type, got %s", dt);
    return Arrays.asList(dt, dt, dt, dt);
}
 
Example 3
Source File: TestMySqlDialect.java    From morf with Apache License 2.0 5 votes vote down vote up
/**
 * @see org.alfasoftware.morf.jdbc.AbstractSqlDialectTest#expectedAlterColumnMakePrimaryStatements()
 */
@Override
protected List<String> expectedAlterColumnMakePrimaryStatements() {
  return Arrays.asList(
    "ALTER TABLE `Test` DROP PRIMARY KEY",
    "ALTER TABLE `Test` CHANGE `dateField` `dateField` DATE",
    "ALTER TABLE `Test` ADD CONSTRAINT `Test_PK` PRIMARY KEY (`id`, `dateField`)"
  );
}
 
Example 4
Source File: Topic.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public void publishWeEvent(String topicName, String eventContent, String extensions, TransactionSucCallback callback) {
    final Function function = new Function(
            FUNC_PUBLISHWEEVENT, 
            Arrays.<Type>asList(new org.fisco.bcos.web3j.abi.datatypes.Utf8String(topicName), 
            new org.fisco.bcos.web3j.abi.datatypes.Utf8String(eventContent), 
            new org.fisco.bcos.web3j.abi.datatypes.Utf8String(extensions)), 
            Collections.<TypeReference<?>>emptyList());
    asyncExecuteTransaction(function, callback);
}
 
Example 5
Source File: QueryPathResolverTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void checkRelation() {
    ResourceInformation resourceInformation = resourceRegistry.getEntry(Task.class).getResourceInformation();
    List<String> jsonPath = Arrays.asList("project");

    QueryPathSpec spec = resolver.resolve(resourceInformation, jsonPath, QueryPathResolver.NamingType.JAVA, "test", queryContext);
    Assert.assertEquals(Project.class, spec.getValueType());
    Assert.assertEquals(jsonPath, spec.getAttributePath());
}
 
Example 6
Source File: DatastoreTemplateTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private void assertArgs(List<Object[]> callsArgs, Map<List, Integer> expected) {
	for (Object[] args : callsArgs) {
		List<Object> key = Arrays.asList(args);
		expected.put(key, expected.computeIfAbsent(key, k -> 0) - 1);
	}
	expected.forEach((key, value) -> assertThat(value).as("Extra calls with argument " + key).isEqualTo(0));
}
 
Example 7
Source File: CompactStatsCommand.java    From geowave with Apache License 2.0 4 votes vote down vote up
public void setParameters(final String storeName, final String adapterId) {
  parameters = Arrays.asList(storeName, adapterId);
}
 
Example 8
Source File: SupportAuthenticationToTokenEndpointWithSymmetricallySignedJWTs.java    From oxAuth with MIT License 4 votes vote down vote up
@Parameters({"redirectUris", "redirectUri", "userId", "userSecret", "sectorIdentifierUri"})
@Test
public void supportAuthenticationToTokenEndpointWithSymmetricallySignedJWTsHS512(
        final String redirectUris, final String redirectUri, final String userId, final String userSecret,
        final String sectorIdentifierUri) throws Exception {
    showTitle("OC5:FeatureTest-Support Authentication to Token Endpoint with Symmetrically Signed JWTs (HS512)");

    // 1. Register client
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_JWT);
    registerRequest.setSectorIdentifierUri(sectorIdentifierUri);

    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse registerResponse = registerClient.exec();

    showClient(registerClient);
    assertEquals(registerResponse.getStatus(), 200, "Unexpected response code: " + registerResponse.getEntity());
    assertNotNull(registerResponse.getClientId());
    assertNotNull(registerResponse.getClientSecret());
    assertNotNull(registerResponse.getRegistrationAccessToken());
    assertNotNull(registerResponse.getClientIdIssuedAt());
    assertNotNull(registerResponse.getClientSecretExpiresAt());

    String clientId = registerResponse.getClientId();
    String clientSecret = registerResponse.getClientSecret();

    // 2. Request authorization
    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE);
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email");
    String state = UUID.randomUUID().toString();

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, null);
    authorizationRequest.setState(state);

    AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess(
            authorizationEndpoint, authorizationRequest, userId, userSecret);

    assertNotNull(authorizationResponse.getLocation());
    assertNotNull(authorizationResponse.getCode());
    assertNotNull(authorizationResponse.getState());

    String authorizationCode = authorizationResponse.getCode();

    // 3. Get Access Token
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();

    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_JWT);
    tokenRequest.setCryptoProvider(cryptoProvider);
    tokenRequest.setAlgorithm(SignatureAlgorithm.HS512);
    tokenRequest.setAudience(tokenEndpoint);
    tokenRequest.setCode(authorizationCode);
    tokenRequest.setRedirectUri(redirectUri);
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);

    TokenClient tokenClient = new TokenClient(tokenEndpoint);
    tokenClient.setRequest(tokenRequest);
    TokenResponse tokenResponse = tokenClient.exec();

    showClient(tokenClient);
    assertEquals(tokenResponse.getStatus(), 200, "Unexpected response code: " + tokenResponse.getStatus());
    assertNotNull(tokenResponse.getEntity(), "The entity is null");
    assertNotNull(tokenResponse.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse.getRefreshToken(), "The refresh token is null");
}
 
Example 9
Source File: DataUtil.java    From easy-adapter with Apache License 2.0 4 votes vote down vote up
public static List<Person> getSomePeople() {
    Person person1 = createPerson("John Snow");
    Person person2 = createPerson("Sam Tarly");
    return Arrays.asList(person1, person2);
}
 
Example 10
Source File: Sign.java    From deeplearning4j with Apache License 2.0 4 votes vote down vote up
@Override
public List<SDVariable> doDiff(List<SDVariable> i_v) {
    SDVariable ret = sameDiff.zerosLike(arg());
    return Arrays.asList(ret);
}
 
Example 11
Source File: AssertingWithPredAndCond.java    From compliance with Apache License 2.0 4 votes vote down vote up
@Test
public void predicateAndConditionDemoTest() {
    final List<String> data = Arrays.asList("hello", "there", "everyone");

    assertThat(data).filteredOn(word -> word.contains("er")).hasSize(2);
}
 
Example 12
Source File: ArgumentPropagationMutatorTest.java    From pitest with Apache License 2.0 4 votes vote down vote up
public List<String> delegate(final List<Integer> is) {
  return Arrays.asList(new String[] { "foo", "bar" });
}
 
Example 13
Source File: AnimationManager.java    From Lunar with MIT License 4 votes vote down vote up
public AnimationManager(Animation[] animations) {
    animationFrames = Arrays.asList(animations);
}
 
Example 14
Source File: Arguments.java    From nodes with Apache License 2.0 4 votes vote down vote up
public Arguments(String dotPath, Argument... arguments) {
    this(dotPath, Arrays.asList(arguments));
}
 
Example 15
Source File: SubjectCreatorTest.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
private void getAndAssertGroupPrincipals(Principal... expectedGroups)
{
    Set<Principal> actualGroupPrincipals = _subjectCreator.getGroupPrincipals(USERNAME_PRINCIPAL);
    Set<Principal> expectedGroupPrincipals = new HashSet<Principal>(Arrays.asList(expectedGroups));
    assertEquals(expectedGroupPrincipals, actualGroupPrincipals);
}
 
Example 16
Source File: RatWorldEvaluationFunction.java    From WorldGrower with GNU General Public License v3.0 4 votes vote down vote up
@Override
public List<Goal> getPriorities(WorldObject performer, World world) {
	return Arrays.asList(Goals.KILL_OUTSIDERS_GOAL, Goals.ANIMAL_FOOD_GOAL, Goals.OFFSPRING_GOAL, Goals.REST_GOAL, Goals.IDLE_GOAL);
}
 
Example 17
Source File: MetadataLoader.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
public MetadataRule(String[] files)
{
	this.files = Arrays.asList(files);
}
 
Example 18
Source File: ElasticsearchHandler.java    From elasticsearch-hadoop with Apache License 2.0 4 votes vote down vote up
@Override
public void init(Properties properties) {
    // Collect Handler settings
    Settings handlerSettings = new PropertiesSettings(properties);
    boolean inheritRoot = true;
    if (handlerSettings.getProperty(CONF_CLIENT_INHERIT) != null) {
        inheritRoot = Booleans.parseBoolean(handlerSettings.getProperty(CONF_CLIENT_INHERIT));
    }

    // Exception: Should persist transport pooling key if it is preset in the root config, regardless of the inherit settings.
    if (SettingsUtils.hasJobTransportPoolingKey(rootSettings)) {
        String jobKey = SettingsUtils.getJobTransportPoolingKey(rootSettings);
        // We want to use a different job key based on the current one since error handlers might write
        // to other clusters or have seriously different settings from the current rest client.
        String newJobKey = jobKey + "_" + UUID.randomUUID().toString();
        // Place under the client configuration for the handler
        handlerSettings.setProperty(CONF_CLIENT_CONF + "." + InternalConfigurationOptions.INTERNAL_TRANSPORT_POOLING_KEY, newJobKey);
    }

    // Gather high level configs and push to client conf level
    resolveProperty(CONF_CLIENT_NODES, CONF_CLIENT_CONF + "." + ConfigurationOptions.ES_NODES, handlerSettings);
    resolveProperty(CONF_CLIENT_PORT, CONF_CLIENT_CONF + "." + ConfigurationOptions.ES_PORT, handlerSettings);
    resolveProperty(CONF_CLIENT_RESOURCE, CONF_CLIENT_CONF + "." + ConfigurationOptions.ES_RESOURCE_WRITE, handlerSettings);
    resolveProperty(CONF_CLIENT_RESOURCE, CONF_CLIENT_CONF + "." + ConfigurationOptions.ES_RESOURCE, handlerSettings);

    // Inherit the original configuration or not
    this.clientSettings = handlerSettings.getSettingsView(CONF_CLIENT_CONF);

    // Ensure we have a write resource to use
    Assert.hasText(clientSettings.getResourceWrite(), "Could not locate write resource for ES error handler.");

    if (inheritRoot) {
        LOG.info("Elasticsearch Error Handler inheriting root configuration");
        this.clientSettings = new CompositeSettings(Arrays.asList(clientSettings, rootSettings.excludeFilter("es.internal")));
    } else {
        LOG.info("Elasticsearch Error Handler proceeding without inheriting root configuration options as configured");
    }

    // Ensure no pattern in Index format, and extract the index to send errors to
    InitializationUtils.discoverClusterInfo(clientSettings, LOG);
    Resource resource = new Resource(clientSettings, false);
    IndexExtractor iformat = ObjectUtils.instantiate(clientSettings.getMappingIndexExtractorClassName(), handlerSettings);
    iformat.compile(resource.toString());
    if (iformat.hasPattern()) {
        throw new IllegalArgumentException(String.format("Cannot use index format within Elasticsearch Error Handler. Format was [%s]", resource.toString()));
    }
    this.endpoint = resource;

    // Configure ECS
    ElasticCommonSchema schema = new ElasticCommonSchema();
    TemplateBuilder templateBuilder = schema.buildTemplate()
            .setEventCategory(CONST_EVENT_CATEGORY);

    // Add any Labels and Tags to schema
    for (Map.Entry entry: handlerSettings.getSettingsView(CONF_LABEL).asProperties().entrySet()) {
        templateBuilder.addLabel(entry.getKey().toString(), entry.getValue().toString());
    }
    templateBuilder.addTags(StringUtils.tokenize(handlerSettings.getProperty(CONF_TAGS)));

    // Configure template using event handler
    templateBuilder = eventConverter.configureTemplate(templateBuilder);
    this.messageTemplate = templateBuilder.build();

    // Determine the behavior for successful write and error on write:
    this.returnDefault = HandlerResult.valueOf(handlerSettings.getProperty(CONF_RETURN_VALUE, CONF_RETURN_VALUE_DEFAULT));
    if (HandlerResult.PASS == returnDefault) {
        this.successReason = handlerSettings.getProperty(CONF_RETURN_VALUE + "." + CONF_PASS_REASON_SUFFIX);
    } else {
        this.successReason = null;
    }
    this.returnError = HandlerResult.valueOf(handlerSettings.getProperty(CONF_RETURN_ERROR, CONF_RETURN_ERROR_DEFAULT));
    if (HandlerResult.PASS == returnError) {
        this.errorReason = handlerSettings.getProperty(CONF_RETURN_ERROR + "." + CONF_PASS_REASON_SUFFIX);
    } else {
        this.errorReason = null;
    }
}
 
Example 19
Source File: CredentialTest.java    From mongodb-async-driver with Apache License 2.0 4 votes vote down vote up
/**
 * Test method for {@link Credential#equals(Object)}.
 */
@Test
public void testEqualsObject() {

    final List<Credential> objs1 = new ArrayList<Credential>();
    final List<Credential> objs2 = new ArrayList<Credential>();

    final File file1 = new File("a");
    final File file2 = new File("b");

    for (final String user : Arrays.asList("a", "b", "c", null)) {
        for (final String passwd : Arrays.asList("a", "b", "c", null)) {
            for (final String db : Arrays.asList("a", "b", "c", null)) {
                for (final File file : Arrays.asList(file1, file2, null)) {
                    for (final String type : Arrays.asList("a", "b", "c",
                            null)) {
                        if (passwd == null) {
                            objs1.add(Credential.builder().userName(user)
                                    .password(null).database(db).file(file)
                                    .authenticationType(type).build());
                            objs2.add(Credential.builder().userName(user)
                                    .password(null).database(db).file(file)
                                    .authenticationType(type).build());

                        }
                        else {
                            objs1.add(Credential.builder().userName(user)
                                    .password(passwd.toCharArray())
                                    .database(db).file(file)
                                    .authenticationType(type).build());
                            objs2.add(Credential.builder().userName(user)
                                    .password(passwd.toCharArray())
                                    .database(db).file(file)
                                    .authenticationType(type).build());

                            objs1.add(Credential.builder().userName(user)
                                    .password(passwd.toCharArray())
                                    .database(db).file(file)
                                    .addOption("f", "g")
                                    .authenticationType(type).build());
                            objs2.add(Credential.builder().userName(user)
                                    .addOption("f", "g")
                                    .password(passwd.toCharArray())
                                    .database(db).file(file)
                                    .authenticationType(type).build());
                        }
                    }
                }
            }
        }
    }

    // Sanity check.
    assertEquals(objs1.size(), objs2.size());

    for (int i = 0; i < objs1.size(); ++i) {
        final Credential obj1 = objs1.get(i);
        Credential obj2 = objs2.get(i);

        assertTrue(obj1.equals(obj1));
        assertEquals(obj1, obj2);

        assertEquals(obj1.hashCode(), obj2.hashCode());

        for (int j = i + 1; j < objs1.size(); ++j) {
            obj2 = objs2.get(j);

            assertFalse(obj1.equals(obj2));
            assertFalse(obj1.hashCode() == obj2.hashCode());
        }

        assertFalse(obj1.equals("foo"));
        assertFalse(obj1.equals(null));
    }
}
 
Example 20
Source File: IvyPostResolveTask.java    From ant-ivy with Apache License 2.0 4 votes vote down vote up
private String[] getConfsToResolve(ModuleDescriptor reference, String conf, String[] rconfs) {
    Message.debug("calculating configurations to resolve");

    if (reference == null) {
        Message.debug("module not yet resolved, all confs still need to be resolved");
        if (conf == null) {
            return new String[] {"*"};
        }
        return splitToArray(conf);
    }

    if (conf == null) {
        Message.debug("module already resolved, no configuration to resolve");
        return new String[0];
    }

    String[] confs;
    if ("*".equals(conf)) {
        confs = reference.getConfigurationsNames();
    } else {
        confs = splitToArray(conf);
    }

    Set<String> rconfsSet = new HashSet<>();

    // for each resolved configuration, check if the report still exists
    ResolutionCacheManager cache = getSettings().getResolutionCacheManager();
    for (String resolvedConf : rconfs) {
        String resolveId = getResolveId();
        if (resolveId == null) {
            resolveId = ResolveOptions.getDefaultResolveId(reference);
        }
        File report = cache.getConfigurationResolveReportInCache(resolveId, resolvedConf);
        // if the report does not exist any longer, we have to recreate it...
        if (report.exists()) {
            rconfsSet.add(resolvedConf);
        }
    }

    Set<String> confsSet = new HashSet<>(Arrays.asList(confs));
    Message.debug("resolved configurations:   " + rconfsSet);
    Message.debug("asked configurations:      " + confsSet);
    confsSet.removeAll(rconfsSet);
    Message.debug("to resolve configurations: " + confsSet);
    return confsSet.toArray(new String[confsSet.size()]);
}