Example usage for com.google.common.collect Iterables get

List of usage examples for com.google.common.collect Iterables get

Introduction

In this page you can find the example usage for com.google.common.collect Iterables get.

Prototype

public static <T> T get(Iterable<T> iterable, int position) 

Source Link

Document

Returns the element at the specified position in an iterable.

Usage

From source file:com.github.richardwilly98.esdms.services.UserProvider.java

@Override
public User findByLogin(String login) throws ServiceException {
    QueryBuilder query = QueryBuilders.matchQuery("login", login);
    SearchResult<User> searchResult = search(query, 0, 1);
    if (searchResult.getTotalHits() == 1) {
        return Iterables.get(searchResult.getItems(), 0);
    }/*from  w  w  w . jav  a2  s.c  o m*/

    if (searchResult.getTotalHits() > 1) {
        if (log.isTraceEnabled()) {
            for (User user : searchResult.getItems()) {
                log.warn("USER WITH SAME LOGIN: " + user);
            }
        }
        throw new ServiceException(String.format(
                "Found more than one user with the same login %s. Possible data integrity issue", login));
    }
    throw new ServiceException(String.format("Cannot find user with login %s", login));
}

From source file:org.jclouds.aliyun.ecs.compute.ECSComputeServiceAdapter.java

@Override
public NodeAndInitialCredentials<Instance> createNodeWithGroupEncodedIntoName(String group, String name,
        Template template) {/*from www . j av  a2s .  com*/
    String instanceType = template.getHardware().getId();
    String regionId = template.getLocation().getId();
    String imageId = template.getImage().getId();

    ECSServiceTemplateOptions templateOptions = template.getOptions().as(ECSServiceTemplateOptions.class);

    String keyPairName = templateOptions.getKeyPairName();
    String securityGroupId = Iterables.getOnlyElement(templateOptions.getGroups());
    String vSwitchId = templateOptions.getVSwitchId();
    Instance.InternetChargeType internetChargeType = Instance.InternetChargeType
            .fromValue(templateOptions.getInternetChargeType());
    int internetMaxBandwidthOut = templateOptions.getInternetMaxBandwidthOut();
    String instanceChargeType = templateOptions.getInstanceChargeType();

    Map<String, String> tags = ComputeServiceUtils.metadataAndTagsAsValuesOfEmptyString(templateOptions);
    tags = new ImmutableMap.Builder().putAll(tags).put(vSwitchId, "").build();
    TagOptions tagOptions = TagOptions.Builder.tags(tags);

    InstanceRequest instanceRequest = api.instanceApi().create(regionId,
            RegionAndId.fromSlashEncoded(imageId).id(), securityGroupId, name, instanceType,
            CreateInstanceOptions.Builder.vSwitchId(vSwitchId).internetChargeType(internetChargeType.toString())
                    .internetMaxBandwidthOut(internetMaxBandwidthOut).instanceChargeType(instanceChargeType)
                    .instanceName(name).keyPairName(keyPairName).tagOptions(tagOptions));

    String regionAndInstanceId = slashEncodeRegionAndId(regionId, instanceRequest.getInstanceId());
    if (!instanceSuspendedPredicate.apply(regionAndInstanceId)) {
        final String message = format(
                "Instance %s was not created correctly. The associated resources created for it will be destroyed",
                instanceRequest.getInstanceId());
        logger.warn(message);
        cleanupResources.cleanupNode(RegionAndId.create(regionId, instanceRequest.getInstanceId()));
        cleanupResources.cleanupSecurityGroupIfOrphaned(regionId, securityGroupId);
    }

    api.instanceApi().allocatePublicIpAddress(regionId, instanceRequest.getInstanceId());
    api.instanceApi().powerOn(instanceRequest.getInstanceId());
    Instance instance = Iterables.get(api.instanceApi().list(regionId,
            ListInstancesOptions.Builder.instanceIds(instanceRequest.getInstanceId())), 0);

    // Safe to pass null credentials here, as jclouds will default populate
    // the node with the default credentials from the image, or the ones in
    // the options, if provided.
    return new NodeAndInitialCredentials(instance,
            slashEncodeRegionAndId(regionId, instanceRequest.getInstanceId()), null);
}

From source file:com.vmware.thinapp.manualmode.server.RequestFactory.java

private ThinAppRuntime getThinAppRuntime(final Long runtimeId) {
    Collection<ThinAppRuntime> runtime = Collections2.filter(runtimeManager.getRuntimes(),
            new Predicate<ThinAppRuntime>() {
                @Override//  w  w w . j  ava  2 s. c  o  m
                public boolean apply(ThinAppRuntime thinAppRuntime) {
                    return thinAppRuntime.getId() == runtimeId;
                }
            });

    assert runtime.size() == 1;

    return Iterables.get(runtime, 0);
}

From source file:com.google.devtools.build.lib.analysis.util.BuildViewTestBase.java

protected void runTestForMultiCpuAnalysisFailure(String badCpu, String goodCpu) throws Exception {
    reporter.removeHandler(failFastHandler);
    useConfiguration("--experimental_multi_cpu=" + badCpu + "," + goodCpu);
    scratch.file("multi/BUILD", "config_setting(", "    name = 'config',",
            "    values = {'cpu': '" + badCpu + "'})", "cc_library(", "    name = 'cpu',",
            "    deps = select({", "        ':config': [':fail'],", "        '//conditions:default': []}))",
            "genrule(", "    name = 'fail',", "    outs = ['file1', 'file2'],", "    executable = 1,",
            "    cmd = 'touch $@')");
    update(defaultFlags().with(Flag.KEEP_GOING), "//multi:cpu");
    AnalysisResult result = getAnalysisResult();
    assertThat(result.getTargetsToBuild()).hasSize(1);
    ConfiguredTarget targetA = Iterables.get(result.getTargetsToBuild(), 0);
    assertEquals(goodCpu, targetA.getConfiguration().getCpu());
    // Unfortunately, we get the same error twice - we can't distinguish the configurations.
    assertContainsEvent("if genrules produce executables, they are allowed only one output");
}

From source file:org.hbs.neo4j.importers.CsvImporter.java

/**
 * Insert a node from a CSV line./*from w  w w.jav  a 2 s .co  m*/
 * 
 * @param header CSV file Header.
 * @param line CSV line to insert.
 */
protected void insertNode(Iterable<String> header, String line) {
    Iterable<String> values = Splitter.on(SEPARATOR).trimResults().split(line);
    String nodeKey = Iterables.get(values, NODES_FILE_LINE_KEY_IDX);
    String nodeDisplayName = Iterables.get(values, NODES_FILE_LINE_DISP_NANE_IDX);
    Node alreadyExist = index.get(NodeEntity.Keys.KEY, nodeKey).getSingle();
    if (alreadyExist != null) {
        throw new IllegalArgumentException("Node with key " + nodeKey + " already exists. Won't be inserted.");
    }
    Node node = db.createNode();
    node.setProperty(NodeEntity.Keys.KEY, nodeKey);
    index.add(node, NodeEntity.Keys.KEY, nodeKey);
    node.setProperty(NodeEntity.Keys.DISPLAY_NAME, nodeDisplayName);
    index.add(node, NodeEntity.Keys.DISPLAY_NAME, nodeDisplayName);
    for (int idx = NODES_FILE_HEADER_MIN_SIZE; idx < Iterables.size(header); idx++) {
        node.setProperty(Iterables.get(header, idx), Iterables.get(values, idx));
    }
}

From source file:org.jclouds.azurecompute.compute.strategy.GetOrCreateStorageServiceAndVirtualNetworkThenCreateNodes.java

@Override
public Map<?, ListenableFuture<Void>> execute(final String group, final int count, final Template template,
        final Set<NodeMetadata> goodNodes, final Map<NodeMetadata, Exception> badNodes,
        final Multimap<NodeMetadata, CustomizationResponse> customizationResponses) {

    final AzureComputeTemplateOptions templateOptions = template.getOptions()
            .as(AzureComputeTemplateOptions.class);
    final String storageAccountName = templateOptions.getStorageAccountName()
            .or(generateStorageServiceName(DEFAULT_STORAGE_ACCOUNT_PREFIX));
    final String location = template.getLocation().getId();
    final String storageAccountType = templateOptions.getStorageAccountType().or(DEFAULT_STORAGE_SERVICE_TYPE);
    final String virtualNetworkName = templateOptions.getVirtualNetworkName().or(DEFAULT_VIRTUAL_NETWORK_NAME);
    final String subnetName = templateOptions.getSubnetName().or(DEFAULT_SUBNET_NAME);
    final String addressSpaceAddressPrefix = templateOptions.getAddressSpaceAddressPrefix()
            .or(DEFAULT_ADDRESS_SPACE_ADDRESS_PREFIX);
    final String subnetAddressPrefix = templateOptions.getSubnetAddressPrefix()
            .or(DEFAULT_SUBNET_ADDRESS_PREFIX);
    final Set<String> networkSecurityGroupNames = templateOptions.getGroups().isEmpty()
            ? Sets.<String>newHashSet()
            : templateOptions.getGroups();

    // get or create storage service
    final StorageService storageService = tryFindExistingStorageServiceAccountOrCreate(api, location,
            storageAccountName, storageAccountType);
    templateOptions.storageAccountName(storageService.serviceName());

    // check existence or create virtual network
    checkExistingVirtualNetworkNamedOrCreate(virtualNetworkName, location, subnetName,
            addressSpaceAddressPrefix, subnetAddressPrefix);
    templateOptions.virtualNetworkName(virtualNetworkName);
    templateOptions.subnetName(subnetName);

    // add network security group to the subnet
    if (!networkSecurityGroupNames.isEmpty()) {
        String networkSecurityGroupName = Iterables.get(networkSecurityGroupNames, 0);
        logger.warn("Only network security group '%s' will be applied to subnet '%s'.",
                networkSecurityGroupName, subnetName);
        final NetworkSecurityGroup networkSecurityGroupAppliedToSubnet = api.getNetworkSecurityGroupApi()
                .getNetworkSecurityGroupAppliedToSubnet(virtualNetworkName, subnetName);
        if (networkSecurityGroupAppliedToSubnet != null) {
            if (!networkSecurityGroupAppliedToSubnet.name().equals(networkSecurityGroupName)) {
                logger.debug("Removing a networkSecurityGroup %s is already applied to subnet '%s' ...",
                        networkSecurityGroupName, subnetName);
                // remove existing nsg from subnet
                String removeFromSubnetRequestId = api.getNetworkSecurityGroupApi().removeFromSubnet(
                        virtualNetworkName, subnetName, networkSecurityGroupAppliedToSubnet.name());
                if (!operationSucceededPredicate.apply(removeFromSubnetRequestId)) {
                    final String warnMessage = format(
                            "Remove existing networkSecurityGroup(%s) to subnet(%s) has not been completed "
                                    + "within %sms.",
                            networkSecurityGroupName, subnetName, azureComputeConstants.operationTimeout());
                    logger.warn(warnMessage);
                    final String illegalStateExceptionMessage = format(
                            "%s. Please, try by increasing `%s` and try again",
                            AzureComputeProperties.OPERATION_TIMEOUT, warnMessage);
                    throw new IllegalStateException(illegalStateExceptionMessage);
                }/*  w  w w .  j a v a2s  .  co  m*/
            }
        }
        // add nsg to subnet
        logger.debug(
                "Adding a networkSecurityGroup %s is already applied to subnet '%s' of virtual network %s ...",
                networkSecurityGroupName, subnetName, virtualNetworkName);
        final String addToSubnetId = api.getNetworkSecurityGroupApi().addToSubnet(virtualNetworkName,
                subnetName, networkSecurityGroupName);
        if (!operationSucceededPredicate.apply(addToSubnetId)) {
            final String warnMessage = format(
                    "Add networkSecurityGroup(%s) to subnet(%s) has not been completed " + "within %sms.",
                    networkSecurityGroupName, subnetName, azureComputeConstants.operationTimeout());
            logger.warn(warnMessage);
            final String illegalStateExceptionMessage = format(
                    "%s. Please, try by increasing `%s` and try again",
                    AzureComputeProperties.OPERATION_TIMEOUT, warnMessage);
            throw new IllegalStateException(illegalStateExceptionMessage);
        }
    }
    return super.execute(group, count, template, goodNodes, badNodes, customizationResponses);
}

From source file:com.opengamma.integration.tool.marketdata.MarketDataSnapshotTool.java

@Override
protected void doRun() throws Exception {
    final String viewDefinitionName = getCommandLine().getOptionValue(VIEW_NAME_OPTION);

    final String valuationTimeArg = getCommandLine().getOptionValue(VALUATION_TIME_OPTION);
    Instant valuationInstant;//from w w w  .j  a  va 2 s  .  c o m
    if (!StringUtils.isBlank(valuationTimeArg)) {
        final LocalTime valuationTime = LocalTime.parse(valuationTimeArg, VALUATION_TIME_FORMATTER);
        valuationInstant = ZonedDateTime.now().with(valuationTime.truncatedTo(SECONDS)).toInstant();
    } else {
        valuationInstant = Instant.now();
    }
    final boolean historicalInput = getCommandLine().hasOption(HISTORICAL_OPTION);

    final MarketDataSpecification marketDataSpecification = historicalInput
            ? new LatestHistoricalMarketDataSpecification()
            : MarketData.live();
    final ViewExecutionOptions viewExecutionOptions = ExecutionOptions.singleCycle(valuationInstant,
            marketDataSpecification, EnumSet.of(ViewExecutionFlags.AWAIT_MARKET_DATA));

    final List<RemoteViewProcessor> viewProcessors = getRemoteComponentFactory().getViewProcessors();
    if (viewProcessors.size() == 0) {
        s_logger.warn("No view processors found at {}", getRemoteComponentFactory().getBaseUri());
        return;
    }
    final MarketDataSnapshotMaster marketDataSnapshotMaster = getRemoteComponentFactory()
            .getMarketDataSnapshotMaster(DEFAULT_PREFERRED_CLASSIFIERS);
    if (marketDataSnapshotMaster == null) {
        s_logger.warn("No market data snapshot masters found at {}", getRemoteComponentFactory().getBaseUri());
        return;
    }
    final Collection<ConfigMaster> configMasters = getRemoteComponentFactory().getConfigMasters().values();
    if (configMasters.size() == 0) {
        s_logger.warn("No config masters found at {}", getRemoteComponentFactory().getBaseUri());
        return;
    }

    final RemoteViewProcessor viewProcessor = viewProcessors.get(0);
    final MarketDataSnapshotter marketDataSnapshotter = viewProcessor.getMarketDataSnapshotter();

    Set<ConfigDocument> viewDefinitions = Sets.newHashSet();

    for (final ConfigMaster configMaster : configMasters) {
        final ConfigSearchRequest<ViewDefinition> request = new ConfigSearchRequest<ViewDefinition>(
                ViewDefinition.class);
        request.setName(viewDefinitionName);
        Iterables.addAll(viewDefinitions, ConfigSearchIterator.iterable(configMaster, request));
    }

    if (viewDefinitions.isEmpty()) {
        endWithError("Unable to resolve any view definitions with name '%s'", viewDefinitionName);
    }

    if (viewDefinitions.size() > 1) {
        endWithError("Multiple view definitions resolved when searching for string '%s': %s",
                viewDefinitionName, viewDefinitions);
    }
    ConfigItem<?> value = Iterables.get(viewDefinitions, 0).getValue();
    StructuredMarketDataSnapshot snapshot = makeSnapshot(marketDataSnapshotter, viewProcessor,
            (ViewDefinition) value.getValue(), viewExecutionOptions);

    final ManageableMarketDataSnapshot manageableMarketDataSnapshot = new ManageableMarketDataSnapshot(
            snapshot);
    manageableMarketDataSnapshot.setName(snapshot.getBasisViewName() + "/" + valuationInstant);
    marketDataSnapshotMaster.add(new MarketDataSnapshotDocument(manageableMarketDataSnapshot));
}

From source file:msi.gaml.expressions.PrimitiveOperator.java

@Override
public IExpression arg(final int i) {
    if (i < 0 || i > parameters.size()) {
        return null;
    }/*from   ww  w  . j a  va2s  .  c om*/
    return Iterables.get(parameters.values(), i).getExpression();
}

From source file:com.isotrol.impe3.nr.api.NodeQueries.java

/**
 * Merges all queries with must boolean operator
 * @param queries NodeQuery queries/* w  w  w  . ja v  a  2 s .  c  o m*/
 * @return NodeQuery with must operator with all queries.
 */
public static NodeQuery all(Iterable<? extends NodeQuery> queries) {
    queries = Iterables.filter(queries, Predicates.notNull());
    final int n = Iterables.size(queries);
    if (n == 0) {
        return null;
    } else if (n == 1) {
        return Iterables.get(queries, 0);
    }
    final NRBooleanQuery q = bool();
    for (NodeQuery c : queries) {
        q.must(c);
    }
    return q;
}

From source file:org.sonar.server.debt.DebtModelOperations.java

@CheckForNull
private CharacteristicDto findCharacteristicToSwitchWith(final CharacteristicDto dto,
        final boolean moveUpOrDown, SqlSession session) {
    // characteristics should be sort by 'order'
    List<CharacteristicDto> rootCharacteristics = dbClient.debtCharacteristicDao()
            .selectEnabledRootCharacteristics(session);
    int currentPosition = Iterables.indexOf(rootCharacteristics, new Predicate<CharacteristicDto>() {
        @Override//from ww w.j  a va  2  s  . c o m
        public boolean apply(@Nullable CharacteristicDto input) {
            return input != null && input.getKey().equals(dto.getKey());
        }
    });
    Integer nextPosition = moveUpOrDown ? (currentPosition > 0 ? currentPosition - 1 : null)
            : (currentPosition < rootCharacteristics.size() - 1 ? currentPosition + 1 : null);
    return nextPosition != null ? Iterables.get(rootCharacteristics, nextPosition) : null;
}