Java Code Examples for com.google.common.collect.Iterables#tryFind()

The following examples show how to use com.google.common.collect.Iterables#tryFind() . 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: KubernetesLocation.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected LocationSpec<KubernetesSshMachineLocation> prepareSshableLocationSpec(Entity entity, ConfigBag setup, Service service, Pod pod) {
    InetAddress node = Networking.getInetAddressWithFixedName(pod.getSpec().getNodeName());
    String podAddress = pod.getStatus().getPodIP();
    LocationSpec<KubernetesSshMachineLocation> locationSpec = LocationSpec.create(KubernetesSshMachineLocation.class)
            .configure(ADDRESS_KEY, node)
            .configure(SshMachineLocation.PRIVATE_ADDRESSES, ImmutableSet.of(podAddress))
            .configure(CALLER_CONTEXT, setup.get(CALLER_CONTEXT));
    if (!isDockerContainer(entity)) {
        Optional<ServicePort> sshPort = Iterables.tryFind(service.getSpec().getPorts(), input -> "TCP".equalsIgnoreCase(input.getProtocol()) && input.getPort() == 22);
        Optional<Integer> sshPortNumber;
        if (sshPort.isPresent()) {
            sshPortNumber = Optional.of(sshPort.get().getNodePort());
        } else {
            LOG.warn("No port-mapping found to ssh port 22, for container {}", service);
            sshPortNumber = Optional.absent();
        }
        locationSpec.configure(CloudLocationConfig.USER, setup.get(KubernetesLocationConfig.LOGIN_USER))
                .configure(SshMachineLocation.PASSWORD, setup.get(KubernetesLocationConfig.LOGIN_USER_PASSWORD))
                .configureIfNotNull(SshMachineLocation.SSH_PORT, sshPortNumber.orNull())
                .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, true)
                .configure(BrooklynConfigKeys.ONBOX_BASE_DIR, "/tmp");
    }
    return locationSpec;
}
 
Example 2
Source File: RiakClusterImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Override
protected void doStart() {
    super.doStart();
    connectSensors();

    try {
        Duration delay = getConfig(DELAY_BEFORE_ADVERTISING_CLUSTER);
        Tasks.setBlockingDetails("Sleeping for "+delay+" before advertising cluster available");
        Time.sleep(delay);
    } finally {
        Tasks.resetBlockingDetails();
    }

    //FIXME: add a quorum to tolerate failed nodes before setting on fire.
    @SuppressWarnings("unchecked")
    Optional<Entity> anyNode = Iterables.tryFind(getMembers(), Predicates.and(
            Predicates.instanceOf(RiakNode.class),
            EntityPredicates.attributeEqualTo(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER, true),
            EntityPredicates.attributeEqualTo(RiakNode.SERVICE_UP, true)));
    if (anyNode.isPresent()) {
        sensors().set(IS_CLUSTER_INIT, true);
    } else {
        log.warn("No Riak Nodes are found on the cluster: {}. Initialization Failed", getId());
        ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
    }
}
 
Example 3
Source File: AccelerationManagerImpl.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public void dropLayout(List<String> path, final String layoutIdOrName, ReflectionContext reflectionContext) {
  NamespaceKey key = new NamespaceKey(path);
  ReflectionAdministrationService administrationReflectionService = reflectionAdministrationServiceFactory.get().get(reflectionContext);
  for (ReflectionGoal rg : administrationReflectionService.getReflectionsByDatasetPath(key)) {
    if (rg.getId().getId().equals(layoutIdOrName) || layoutIdOrName.equals(rg.getName())) {
      administrationReflectionService.remove(rg);
      // only match first and exist.
      return;
    }
  }

  Optional<ExternalReflection> er = Iterables.tryFind(administrationReflectionService.getExternalReflectionByDatasetPath(path), new Predicate<ExternalReflection>() {
    @Override
    public boolean apply(@Nullable ExternalReflection externalReflection) {
      return layoutIdOrName.equalsIgnoreCase(externalReflection.getName()) ||
        layoutIdOrName.equals(externalReflection.getId());
    }
  });

  if (er.isPresent()) {
    administrationReflectionService.dropExternalReflection(er.get().getId());
    return;
  }
  throw UserException.validationError().message("No matching reflection found.").build(logger);
}
 
Example 4
Source File: KafkaSupport.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
/**
 * Send a message to the {@link KafkaCluster} on the given topic.
 */
public void sendMessage(String topic, String message) {
    Optional<Entity> anyBrokerNodeInCluster = Iterables.tryFind(cluster.getCluster().getChildren(), Predicates.and(
            Predicates.instanceOf(KafkaBroker.class),
            EntityPredicates.attributeEqualTo(KafkaBroker.SERVICE_UP, true)));
    if (anyBrokerNodeInCluster.isPresent()) {
        KafkaBroker broker = (KafkaBroker)anyBrokerNodeInCluster.get();

        Properties props = new Properties();

        props.put("metadata.broker.list", format("%s:%d", broker.getAttribute(KafkaBroker.HOSTNAME), broker.getKafkaPort()));
        props.put("bootstrap.servers", format("%s:%d", broker.getAttribute(KafkaBroker.HOSTNAME), broker.getKafkaPort()));
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        Producer<String, String> producer = new KafkaProducer<>(props);
        ((KafkaZooKeeper)cluster.getZooKeeper()).createTopic(topic);

        ProducerRecord<String, String> data = new ProducerRecord<>(topic, message);
        producer.send(data);
        producer.close();
    } else {
        throw new InvalidParameterException("No kafka broker node found");
    }
}
 
Example 5
Source File: ImportJobDto.java    From website with GNU Affero General Public License v3.0 6 votes vote down vote up
public String getItemsStatus() {
    String status = "PROCESSED";
    
    Optional<ImportItem> optional = Iterables.tryFind(getImportItems(), new Predicate<ImportItem>() {

        @Override
        public boolean apply(ImportItem input) {
            return input.getStatus() != Status.PROCESSED;
        }

    });

    if (optional.isPresent()) {
        status = "PROCESSING";
    }

    return status;
}
 
Example 6
Source File: PcRptMessageCodec.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected Reports getValidReports(final List<Object> objects, final List<Message> errors) {
    final Optional<Object> find = Iterables.tryFind(objects, Predicates.instanceOf(BandwidthUsage.class));
    final Object object;
    if (find.isPresent()) {
        object = find.get();
        objects.remove(object);
    } else {
        object = null;
    }
    final Reports validReports = super.getValidReports(objects, errors);
    if (object != null && validReports != null) {
        final Path path = validReports.getPath();
        if (path != null) {
            return new ReportsBuilder(validReports).setPath(new PathBuilder(path).setBandwidth(
                    setBandwidthUsage(path.getBandwidth(), (BandwidthUsage) object)).build()).build();
        }
    }
    return validReports;
}
 
Example 7
Source File: RoleController.java    From java-platform with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/userRemove", method = RequestMethod.POST)
@ResponseBody
public Result removeUser(@RequestParam(value = "id", required = false) Role role,
		@RequestParam(value = "users") User[] users) {
	if (users != null) {
		List<UserRole> userRoles = userRoleService.findByRole(role);
		for (User user : users) {
			Optional<UserRole> optional = Iterables.tryFind(userRoles,
					(userRole) -> Objects.equal(userRole.getUser(), user));
			if (optional.isPresent()) {
				userRoleService.delete(optional.get());
			}
		}
	}
	return Result.success();
}
 
Example 8
Source File: PostalAddressRepository.java    From estatio with Apache License 2.0 6 votes vote down vote up
@Programmatic
public PostalAddress findByAddress(
        final CommunicationChannelOwner owner, 
        final String address1, 
        final String postalCode, 
        final String city, 
        final Country country) {

    // TODO: rewrite to use JDK8 streams
    final List<CommunicationChannelOwnerLink> links =
            communicationChannelOwnerLinkRepository.findByOwnerAndCommunicationChannelType(owner, CommunicationChannelType.POSTAL_ADDRESS);
    final Iterable<PostalAddress> postalAddresses =
            Iterables.transform(
                    links,
                    CommunicationChannelOwnerLink.Functions.communicationChannel(PostalAddress.class));
    final Optional<PostalAddress> postalAddressIfFound =
            Iterables.tryFind(postalAddresses, PostalAddress.Predicates.equalTo(address1, postalCode, city, country));
    return postalAddressIfFound.orNull();
}
 
Example 9
Source File: JsonTokenHelper.java    From identity-toolkit-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public void check(JsonObject payload) throws SignatureException {
  if (!payload.has(JsonToken.AUDIENCE)) {
    throw new SignatureException("No audience in payload.");
  }
  final String audienceInIdToken = payload.get(JsonToken.AUDIENCE).getAsString();
  Optional<String> matchedAud = Iterables.tryFind(
      expectedAudiences,
      new Predicate<String>() {
        public boolean apply(String aud) {
          return audienceInIdToken.equals(aud);
        }
      });

  if (!matchedAud.isPresent()) {
    throw new SignatureException(String.format(
        "Gitkit token audience(%s) doesn't match projectId or clientId in server configuration",
        audienceInIdToken));
  }
}
 
Example 10
Source File: NotificationStore.java    From notification with Apache License 2.0 5 votes vote down vote up
/**
 * Return the parent notification that matches the given ID or is the parent of a child
 * notification.
 *
 * @param notifications Notifications to search through
 * @param id Notification ID to find
 * @return the notification
 */
public static Optional<Notification> tryFind(
    final Iterable<Notification> notifications, final String id) {

  Objects.requireNonNull(notifications, "notifications == null");

  if (Strings.isNullOrEmpty(id)) {
    return Optional.empty();
  }

  final com.google.common.base.Optional<Notification> result =
      Iterables.tryFind(
          notifications,
          notification -> {
            // first check that the ID matches
            final Optional<String> notificationId = notification.getId();
            if (!notificationId.isPresent()) {
              return false;
            } else if (id.equals(notificationId.get())) {
              return true;
            }

            // Check to see if the notification is included in any rolled up notifications. This
            // code should not be hit as tryFind() is called prior to the rollups happening, but
            // we include this here for completeness.
            final Collection<Notification> children = notification.getNotifications();
            if (children.isEmpty()) {
              return false;
            }
            return (tryFind(children, id)).isPresent();
          });

  return result.toJavaUtil();
}
 
Example 11
Source File: GerritRestClient.java    From gerrit-rest-java-client with Apache License 2.0 5 votes vote down vote up
private Optional<Cookie> findCookie(final String cookieName) {
    List<Cookie> cookies = cookieStore.getCookies();
    return Iterables.tryFind(cookies, new Predicate<Cookie>() {
        @Override
        public boolean apply(Cookie cookie) {
            return cookie.getName().equals(cookieName);
        }
    });
}
 
Example 12
Source File: SpecParameterUnwrappingTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testDependantCatalogConfigOverridesParameters() {
    addCatalogItems(
            "brooklyn.catalog:",
            "  version: " + TEST_VERSION,
            "  items:",
            "  - id: paramItem",
            "    item:",
            "      type: " + ConfigEntityForTest.class.getName(),
            "      brooklyn.parameters:",
            "      - name: simple",
            "        default: biscuits",
            "      brooklyn.config:",
            "        simple: value",
            "  - id: " + SYMBOLIC_NAME,
            "    item:",
            "      type: paramItem",
            "      brooklyn.parameters:",
            "      - name: simple",
            "        default: rabbits");

    AbstractBrooklynObjectSpec<?,?> spec = peekSpec();
    List<SpecParameter<?>> params = spec.getParameters();
    assertTrue(Iterables.tryFind(params, nameEqualTo("simple")).isPresent());
    Optional<ConfigKey<?>> config = Iterables.tryFind(spec.getConfig().keySet(), ConfigPredicates.nameEqualTo("simple"));
    assertTrue(config.isPresent());
    Object value = spec.getConfig().get(config.get());
    assertEquals(value, "value");
}
 
Example 13
Source File: RebindEntityTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testRebindAnonymousKeyDowncastedGivesCorrectType() throws Exception {
    // happens if we write yaml and put an int where a double is expected
    final String doubleKeyName = "double.key";
    final ConfigKey<Object> keyAsObject = ConfigKeys.newConfigKey(Object.class, doubleKeyName);
    final ConfigKey<Double> keyAsDouble = ConfigKeys.newDoubleConfigKey(doubleKeyName);
    // set an int
    origApp.config().set(keyAsObject, (int) 1);
    // get the double when queried
    Asserts.assertInstanceOf(origApp.config().get(keyAsDouble), Double.class);
    // but doesn't actually know it's a double
    Asserts.assertInstanceOf(origApp.config().get(keyAsObject), Integer.class);
    // also assert the key isn't included in declared list
    Optional<ConfigKey<?>> declaredKey = Iterables.tryFind(getTypeDeclaredKeys(origApp), (k) -> k.getName().equals(doubleKeyName));
    if (declaredKey.isPresent()) Assert.fail("Shouldn't have declared anonymous key, but had: "+declaredKey.get());
    
    newApp = rebind();
    // now (2017-11) this works because we check both types on lookup
    Asserts.assertInstanceOf(newApp.config().get(keyAsDouble), Double.class);
    // if not querying double, we get the original type
    Asserts.assertInstanceOf(newApp.config().get(keyAsObject), Integer.class);
    
    // and this also succeeds because because now the anonymous key definition is not persisted
    // (test changed, but confirmed it fails without the new BasicEntityMemento.isAnonymous check)
    Optional<ConfigKey<?>> persistedKey = Iterables.tryFind(getTypeDeclaredKeys(newApp), (k) -> k.getName().equals(doubleKeyName));
    if (persistedKey.isPresent()) Assert.fail("Shouldn't have persisted anonymous key, but had: "+persistedKey.get());
}
 
Example 14
Source File: ApplicationResourceTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(dependsOnMethods = { "testDeployApplication", "testLocatedLocation" })
public void testDeploymentFailsOnDuplicateAppId() throws Exception {
    // First app
    String appId = "myuidtestdeploymentuidfailsonduplicate";
    String yaml = "{ name: my-name-1, services: [ { type: "+BasicApplication.class.getCanonicalName()+" } ] }";
    Response response = deployApp(yaml, appId);
    assertResponseStatus(response, 201);

    BasicApplication app = (BasicApplication) getManagementContext().getEntityManager().getEntity(appId);
    assertNotNull(app);

    // Second app should get a conflict response (409)
    String yaml2 = "{ name: my-name-2, services: [ { type: "+BasicApplication.class.getCanonicalName()+" } ] }";
    Response response2 = deployApp(yaml2, appId);
    assertResponseStatus(response2, 409, StringPredicates.containsAllLiterals(
            IdAlreadyExistsException.class.getSimpleName(), "already known under that id '"+appId+"'"));

    Optional<Application> app2 = Iterables.tryFind(getManagementContext().getApplications(), EntityPredicates.displayNameEqualTo("my-name-2"));
    assertFalse(app2.isPresent(), "app2="+app2);
    
    // Third app with different app id should work
    String appId3 = "myuiddifferent";
    String yaml3 = "{ name: my-name-3, services: [ { type: "+BasicApplication.class.getCanonicalName()+" } ] }";
    Response response3 = deployApp(yaml3, appId3);
    assertResponseStatus(response3, 201);
    
    BasicApplication app3 = (BasicApplication) getManagementContext().getEntityManager().getEntity(appId3);
    assertNotNull(app3);
    
    // Delete app1; then deploying app2 should succeed
    Entities.unmanage(app);
    
    Response response2b = deployApp(yaml2, appId);
    assertResponseStatus(response2b, 201);

    BasicApplication app2b = (BasicApplication) getManagementContext().getEntityManager().getEntity(appId);
    assertNotNull(app2b);
    assertEquals(app2b.getDisplayName(), "my-name-2");
}
 
Example 15
Source File: EasyFormatDatasetAccessor.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private BatchSchema getBatchSchema(BatchSchema oldSchema, final FileSelection selection, final FileSystem dfs) throws Exception {
  final SabotContext context = formatPlugin.getContext();
  try (
      BufferAllocator sampleAllocator = context.getAllocator().newChildAllocator("sample-alloc", 0, Long.MAX_VALUE);
      OperatorContextImpl operatorContext = new OperatorContextImpl(context.getConfig(), sampleAllocator, context.getOptionManager(), 1000);
      SampleMutator mutator = new SampleMutator(sampleAllocator)
  ) {
    final ImplicitFilesystemColumnFinder explorer = new ImplicitFilesystemColumnFinder(context.getOptionManager(), dfs, GroupScan.ALL_COLUMNS);

    Optional<FileAttributes> fileName = Iterables.tryFind(selection.getFileAttributesList(), input -> input.size() > 0);

    final FileAttributes file = fileName.or(selection.getFileAttributesList().get(0));

    EasyDatasetSplitXAttr dataset = EasyDatasetSplitXAttr.newBuilder()
        .setStart(0l)
        .setLength(Long.MAX_VALUE)
        .setPath(file.getPath().toString())
        .build();
    try (RecordReader reader = new AdditionalColumnsRecordReader(((EasyFormatPlugin) formatPlugin)
        .getRecordReader(operatorContext, dfs, dataset, GroupScan.ALL_COLUMNS), explorer.getImplicitFieldsForSample(selection))) {
      reader.setup(mutator);
      Map<String, ValueVector> fieldVectorMap = new HashMap<>();
      int i = 0;
      for (VectorWrapper<?> vw : mutator.getContainer()) {
        fieldVectorMap.put(vw.getField().getName(), vw.getValueVector());
        if (++i > maxLeafColumns) {
          throw new ColumnCountTooLargeException(maxLeafColumns);
        }
      }
      reader.allocate(fieldVectorMap);
      reader.next();
      mutator.getContainer().buildSchema(BatchSchema.SelectionVectorMode.NONE);
      BatchSchema newSchema = mutator.getContainer().getSchema();
      return oldSchema != null ? oldSchema.merge(newSchema) : newSchema;
    }
  }
}
 
Example 16
Source File: TestListenHTTP.java    From nifi with Apache License 2.0 4 votes vote down vote up
protected MockFlowFile findFlowFile(List<MockFlowFile> flowFilesForRelationship, String attributeName, String attributeValue) {
    Optional<MockFlowFile> optional = Iterables.tryFind(flowFilesForRelationship, ff -> ff.getAttribute(attributeName).equals(attributeValue));
    Assert.assertTrue(optional.isPresent());
    return optional.get();
}
 
Example 17
Source File: TeamModule.java    From UHC with MIT License 4 votes vote down vote up
public Optional<Team> findFirstEmptyTeam() {
    return Iterables.tryFind(teams.values(), Predicates.not(FunctionalUtil.TEAMS_WITH_PLAYERS));
}
 
Example 18
Source File: SpecParameterUnwrappingTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Test
public void testParameterDefaultsUsedInConfig() throws Exception {
    addCatalogItems(
            "brooklyn.catalog:",
            "  version: " + TEST_VERSION,
            "  items:",
            "    - id: " + ConfigEntityForTest.class.getSimpleName() + "WithParams",
            "      itemType: entity",
            "      item:",
            "        type: " + ConfigEntityForTest.class.getName(),
            "        brooklyn.parameters:",
            "          - name: num",
            "            type: integer",
            "            default: 1234",
            "        brooklyn.children:",
            "          - type: " + BasicStartable.class.getName(),
            "            name: s",
            "            brooklyn.config:",
            "              test: $brooklyn:parent().config(\"num\")",
            "    - id: " + SYMBOLIC_NAME,
            "      itemType: entity",
            "      item:",
            "        type: " + BasicApplication.class.getName(),
            "        brooklyn.children:",
            "          - type: " + ConfigEntityForTest.class.getSimpleName() + "WithParams",
            "            name: a",
            "          - type: " + ConfigEntityForTest.class.getSimpleName() + "WithParams",
            "            name: b",
            "            brooklyn.config:",
            "              num: 5678",
            "          - type: " + ConfigEntityForTest.class.getSimpleName() + "WithParams",
            "            name: c",
            "            brooklyn.config:",
            "              test: $brooklyn:config(\"num\")");
    final int NUM_CONFIG_KEYS_FROM_WITH_PARAMS_TEST_BLUEPRINT = 1;

    AbstractBrooklynObjectSpec<?,?> spec = peekSpec(ConfigEntityForTest.class.getSimpleName() + "WithParams", TEST_VERSION);
    List<SpecParameter<?>> params = spec.getParameters();
    assertEquals(params.size(), NUM_ENTITY_DEFAULT_CONFIG_KEYS + ConfigEntityForTest.NUM_CONFIG_KEYS_DEFINED_HERE + NUM_CONFIG_KEYS_FROM_WITH_PARAMS_TEST_BLUEPRINT,
        "params="+params);
    assertTrue(Iterables.tryFind(params, nameEqualTo("num")).isPresent());
    
    Application app = (Application) createAndStartApplication(
            "services:",
            "  - type: " + ver(SYMBOLIC_NAME));

    Iterable<Entity> children = app.getChildren();
    Optional<Entity> a = Iterables.tryFind(children, EntityPredicates.displayNameEqualTo("a"));
    assertTrue(a.isPresent());
    assertEquals(a.get().config().get(NUM).intValue(), 1234);
    Optional<Entity> as = Iterables.tryFind(a.get().getChildren(), EntityPredicates.displayNameEqualTo("s"));
    assertTrue(as.isPresent());
    assertEquals(as.get().config().get(ConfigKeys.newIntegerConfigKey("test")).intValue(), 1234);
    Optional<Entity> b = Iterables.tryFind(children, EntityPredicates.displayNameEqualTo("b"));
    assertTrue(b.isPresent());
    assertEquals(b.get().config().get(NUM).intValue(), 5678);
    Optional<Entity> bs = Iterables.tryFind(b.get().getChildren(), EntityPredicates.displayNameEqualTo("s"));
    assertTrue(bs.isPresent());
    assertEquals(bs.get().config().get(ConfigKeys.newIntegerConfigKey("test")).intValue(), 5678);
    Optional<Entity> c = Iterables.tryFind(children, EntityPredicates.displayNameEqualTo("c"));
    assertTrue(c.isPresent());
    assertEquals(c.get().config().get(ConfigKeys.newIntegerConfigKey("test")).intValue(), 1234);
    Optional<Entity> cs = Iterables.tryFind(c.get().getChildren(), EntityPredicates.displayNameEqualTo("s"));
    assertTrue(cs.isPresent());
    assertEquals(cs.get().config().get(ConfigKeys.newIntegerConfigKey("test")).intValue(), 1234);
}
 
Example 19
Source File: CouchbaseSyncGatewaySshDriver.java    From brooklyn-library with Apache License 2.0 4 votes vote down vote up
@Override
public void launch() {
    Entity cbNode = entity.getConfig(CouchbaseSyncGateway.COUCHBASE_SERVER);
    Entities.waitForServiceUp(cbNode, Duration.ONE_HOUR);
    DependentConfiguration.waitInTaskForAttributeReady(cbNode, CouchbaseCluster.IS_CLUSTER_INITIALIZED, Predicates.equalTo(true));
    // Even once the bucket has published its API URL, it can still take a couple of seconds for it to become available
    Time.sleep(10 * 1000);
    if (cbNode instanceof CouchbaseCluster) {
        // in_cluster now applies even to a node in a cluster of size 1
        Optional<Entity> cbClusterNode = Iterables.tryFind(cbNode.getAttribute(CouchbaseCluster.GROUP_MEMBERS),
            Predicates.and(Predicates.instanceOf(CouchbaseNode.class), EntityPredicates.attributeEqualTo(CouchbaseNode.IS_IN_CLUSTER, Boolean.TRUE)));
        
        if (!cbClusterNode.isPresent()) {
            throw new IllegalArgumentException(format("The cluster %s does not contain any suitable Couchbase nodes to connect to..", cbNode.getId()));
        }
        
        cbNode = cbClusterNode.get();
    }
    String hostname = cbNode.getAttribute(CouchbaseNode.HOSTNAME);
    String webPort = cbNode.getAttribute(CouchbaseNode.COUCHBASE_WEB_ADMIN_PORT).toString();


    String username = cbNode.getConfig(CouchbaseNode.COUCHBASE_ADMIN_USERNAME);
    String password = cbNode.getConfig(CouchbaseNode.COUCHBASE_ADMIN_PASSWORD);

    String bucketName = entity.getConfig(CouchbaseSyncGateway.COUCHBASE_SERVER_BUCKET);
    String pool = entity.getConfig(CouchbaseSyncGateway.COUCHBASE_SERVER_POOL);
    String pretty = entity.getConfig(CouchbaseSyncGateway.PRETTY) ? "-pretty" : "";
    String verbose = entity.getConfig(CouchbaseSyncGateway.VERBOSE) ? "-verbose" : "";

    String adminRestApiPort = entity.getConfig(CouchbaseSyncGateway.ADMIN_REST_API_PORT).iterator().next().toString();
    String syncRestApiPort = entity.getConfig(CouchbaseSyncGateway.SYNC_REST_API_PORT).iterator().next().toString();

    String serverWebAdminUrl = format("http://%s:%s@%s:%s", username, password, hostname, webPort);
    String options = format("-url %s -bucket %s -adminInterface 0.0.0.0:%s -interface 0.0.0.0:%s -pool %s %s %s",
            serverWebAdminUrl, bucketName, adminRestApiPort, syncRestApiPort, pool, pretty, verbose);

    newScript(ImmutableMap.of("usePidFile", true), LAUNCHING)
            .body.append(format("/opt/couchbase-sync-gateway/bin/sync_gateway %s ", options) + "> out.log 2> err.log < /dev/null &")
            .failOnNonZeroResultCode()
            .execute();
}
 
Example 20
Source File: FileSelection.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
public Optional<FileAttributes> getFirstFile() throws IOException {
  return Iterables.tryFind(fileAttributesList, FileAttributes::isRegularFile);
}