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

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

Introduction

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

Prototype

E get(int index);

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:org.eclipse.milo.opcua.sdk.client.session.states.AbstractSessionState.java

private static void transferSubscriptions(Fsm fsm, OpcUaSession session,
        CompletableFuture<OpcUaSession> sessionFuture) {

    OpcUaClient client = fsm.getClient();
    UaTcpStackClient stackClient = client.getStackClient();
    OpcUaSubscriptionManager subscriptionManager = client.getSubscriptionManager();
    ImmutableList<UaSubscription> subscriptions = subscriptionManager.getSubscriptions();

    if (subscriptions.isEmpty()) {
        fsm.fireEvent(new TransferSuccessEvent(session, sessionFuture));
        return;//from  w  w  w.j a v  a2  s.co  m
    }

    UInteger[] subscriptionIdsArray = subscriptions.stream().map(UaSubscription::getSubscriptionId)
            .toArray(UInteger[]::new);

    TransferSubscriptionsRequest request = new TransferSubscriptionsRequest(
            client.newRequestHeader(session.getAuthenticationToken(), REQUEST_TIMEOUT), subscriptionIdsArray,
            true);

    LOGGER.debug("Sending TransferSubscriptionsRequest...");

    stackClient.<TransferSubscriptionsResponse>sendRequest(request).whenCompleteAsync((tsr, ex) -> {
        if (tsr != null) {
            List<TransferResult> results = l(tsr.getResults());

            client.getConfig().getExecutor().execute(() -> {
                for (int i = 0; i < results.size(); i++) {
                    TransferResult result = results.get(i);

                    if (!result.getStatusCode().isGood()) {
                        UaSubscription subscription = subscriptions.get(i);

                        subscriptionManager.transferFailed(subscription.getSubscriptionId(),
                                result.getStatusCode());
                    }
                }
            });

            if (LOGGER.isDebugEnabled()) {
                Stream<UInteger> subscriptionIds = subscriptions.stream()
                        .map(UaSubscription::getSubscriptionId);
                Stream<StatusCode> statusCodes = results.stream().map(TransferResult::getStatusCode);

                String[] ss = StreamUtils
                        .zip(subscriptionIds, statusCodes,
                                (i, s) -> String.format("id=%s/%s", i,
                                        StatusCodes.lookup(s.getValue()).map(sa -> sa[0]).orElse(s.toString())))
                        .toArray(String[]::new);

                LOGGER.debug("TransferSubscriptions results: {}", Arrays.toString(ss));
            }

            fsm.fireEvent(new TransferSuccessEvent(session, sessionFuture));
        } else {
            StatusCode statusCode = UaException.extract(ex).map(UaException::getStatusCode)
                    .orElse(StatusCode.BAD);

            // Bad_ServiceUnsupported is the correct response when transfers aren't supported but
            // server implementations tend to interpret the spec in their own unique way...
            if (statusCode.getValue() == StatusCodes.Bad_NotImplemented
                    || statusCode.getValue() == StatusCodes.Bad_NotSupported
                    || statusCode.getValue() == StatusCodes.Bad_OutOfService
                    || statusCode.getValue() == StatusCodes.Bad_ServiceUnsupported) {

                LOGGER.debug("TransferSubscriptions not supported: {}", statusCode);

                client.getConfig().getExecutor().execute(() -> {
                    // transferFailed() will remove the subscription, but that is okay
                    // because the list from getSubscriptions() above is a copy.
                    for (UaSubscription subscription : subscriptions) {
                        subscriptionManager.transferFailed(subscription.getSubscriptionId(), statusCode);
                    }
                });

                fsm.fireEvent(new TransferSuccessEvent(session, sessionFuture));
            } else {
                LOGGER.debug("TransferSubscriptions failed: {}", statusCode);

                fsm.fireEvent(new TransferFailureEvent(ex, session, sessionFuture));
            }
        }
    }, stackClient.getExecutorService());
}

From source file:org.gradle.model.internal.manage.schema.extract.ManagedImplTypeSchemaExtractionStrategySupport.java

public <R> ModelSchemaExtractionResult<R> extract(final ModelSchemaExtractionContext<R> extractionContext,
        ModelSchemaStore store, final ModelSchemaCache cache) {
    ModelType<R> type = extractionContext.getType();
    Class<? super R> clazz = type.getRawClass();
    if (isTarget(type)) {
        validateType(type, extractionContext);

        Iterable<Method> methods = Arrays.asList(clazz.getMethods());
        if (!clazz.isInterface()) {
            methods = filterIgnoredMethods(methods);
        }//www .  ja v a2 s.c o  m
        ImmutableListMultimap<String, Method> methodsByName = Multimaps.index(methods,
                new Function<Method, String>() {
                    public String apply(Method method) {
                        return method.getName();
                    }
                });

        ensureNoOverloadedMethods(extractionContext, methodsByName);

        List<ModelProperty<?>> properties = Lists.newLinkedList();
        List<Method> handled = Lists.newArrayListWithCapacity(clazz.getMethods().length);
        ReturnTypeSpecializationOrdering returnTypeSpecializationOrdering = new ReturnTypeSpecializationOrdering();

        for (String methodName : methodsByName.keySet()) {
            if (methodName.startsWith("get") && !methodName.equals("get")) {
                ImmutableList<Method> getterMethods = methodsByName.get(methodName);

                // The overload check earlier verified that all methods for are equivalent for our purposes
                // So, taking the first one with the most specialized return type is fine.
                Method sampleMethod = returnTypeSpecializationOrdering.max(getterMethods);

                boolean abstractGetter = Modifier.isAbstract(sampleMethod.getModifiers());

                if (sampleMethod.getParameterTypes().length != 0) {
                    throw invalidMethod(extractionContext, "getter methods cannot take parameters",
                            sampleMethod);
                }

                Character getterPropertyNameFirstChar = methodName.charAt(3);
                if (!Character.isUpperCase(getterPropertyNameFirstChar)) {
                    throw invalidMethod(extractionContext,
                            "the 4th character of the getter method name must be an uppercase character",
                            sampleMethod);
                }

                ModelType<?> returnType = ModelType.returnType(sampleMethod);

                String propertyNameCapitalized = methodName.substring(3);
                String propertyName = StringUtils.uncapitalize(propertyNameCapitalized);
                String setterName = "set" + propertyNameCapitalized;
                ImmutableList<Method> setterMethods = methodsByName.get(setterName);

                boolean isWritable = !setterMethods.isEmpty();
                if (isWritable) {
                    Method setter = setterMethods.get(0);

                    if (!abstractGetter) {
                        throw invalidMethod(extractionContext,
                                "setters are not allowed for non-abstract getters", setter);
                    }
                    validateSetter(extractionContext, returnType, setter);
                    handled.addAll(setterMethods);
                }

                if (abstractGetter) {
                    ImmutableSet<ModelType<?>> declaringClasses = ImmutableSet
                            .copyOf(Iterables.transform(getterMethods, new Function<Method, ModelType<?>>() {
                                public ModelType<?> apply(Method input) {
                                    return ModelType.of(input.getDeclaringClass());
                                }
                            }));

                    boolean unmanaged = Iterables.any(getterMethods, new Predicate<Method>() {
                        public boolean apply(Method input) {
                            return input.getAnnotation(Unmanaged.class) != null;
                        }
                    });

                    properties.add(ModelProperty.of(returnType, propertyName, isWritable, declaringClasses,
                            unmanaged));
                }
                handled.addAll(getterMethods);
            }
        }

        Iterable<Method> notHandled = Iterables.filter(methodsByName.values(),
                Predicates.not(Predicates.in(handled)));

        // TODO - should call out valid getters without setters
        if (!Iterables.isEmpty(notHandled)) {
            throw invalidMethods(extractionContext, "only paired getter/setter methods are supported",
                    notHandled);
        }

        Class<R> concreteClass = type.getConcreteClass();
        final ModelSchema<R> schema = createSchema(extractionContext, store, type, properties, concreteClass);
        Iterable<ModelSchemaExtractionContext<?>> propertyDependencies = Iterables.transform(properties,
                new Function<ModelProperty<?>, ModelSchemaExtractionContext<?>>() {
                    public ModelSchemaExtractionContext<?> apply(final ModelProperty<?> property) {
                        return toPropertyExtractionContext(extractionContext, property, cache);
                    }
                });

        return new ModelSchemaExtractionResult<R>(schema, propertyDependencies);
    } else {
        return null;
    }
}

From source file:com.facebook.buck.macho.ObjectPathsAbsolutifier.java

private SymTabCommand getSymTabCommand() {
    buffer.position(0);//from w  ww  .  j  a  va 2s  . c  o m
    ImmutableList<SymTabCommand> commands = LoadCommandUtils.findLoadCommandsWithClass(buffer,
            nulTerminatedCharsetDecoder, SymTabCommand.class);
    Preconditions.checkArgument(commands.size() == 1, "Found %d SymTabCommands, expected 1", commands.size());
    return commands.get(0);
}

From source file:com.android.manifmerger.XmlDocument.java

/**
 * Adds a new element of type nodeType with a specific keyValue if the element is absent in this
 * document. Will also add attributes expressed through key value pairs.
 *
 * @param actionRecorder to records creation actions.
 * @param nodeType the node type to crete
 * @param keyValue the optional key for the element.
 * @param attributes the optional array of key value pairs for extra element attribute.
 * @return the Xml element whether it was created or existed or {@link Optional#absent()} if
 * it does not exist in this document./*from  w  w  w  .jav  a  2  s.c  o  m*/
 */
private Optional<Element> addIfAbsent(@NonNull ActionRecorder actionRecorder,
        @NonNull ManifestModel.NodeTypes nodeType, @Nullable String keyValue, @Nullable String reason,
        @Nullable Pair<String, String>... attributes) {

    Optional<XmlElement> xmlElementOptional = getByTypeAndKey(nodeType, keyValue);
    if (xmlElementOptional.isPresent()) {
        return Optional.absent();
    }
    Element elementNS = getXml().createElementNS(SdkConstants.ANDROID_URI, "android:" + nodeType.toXmlName());

    ImmutableList<String> keyAttributesNames = nodeType.getNodeKeyResolver().getKeyAttributesNames();
    if (keyAttributesNames.size() == 1) {
        elementNS.setAttributeNS(SdkConstants.ANDROID_URI, "android:" + keyAttributesNames.get(0), keyValue);
    }
    if (attributes != null) {
        for (Pair<String, String> attribute : attributes) {
            elementNS.setAttributeNS(SdkConstants.ANDROID_URI, "android:" + attribute.getFirst(),
                    attribute.getSecond());
        }
    }

    // record creation.
    XmlElement xmlElement = new XmlElement(elementNS, this);
    actionRecorder.recordImpliedNodeAction(xmlElement, reason);

    getRootNode().getXml().appendChild(elementNS);
    return Optional.of(elementNS);
}

From source file:com.google.googlejavaformat.OpsBuilder.java

/** Output any remaining tokens from the input stream (e.g. terminal whitespace). */
public final void drain() {
    int inputPosition = input.getText().length() + 1;
    if (inputPosition > this.inputPosition) {
        ImmutableList<? extends Input.Token> tokens = input.getTokens();
        int tokensN = tokens.size();
        while (tokenI < tokensN && inputPosition > tokens.get(tokenI).getTok().getPosition()) {
            Input.Token token = tokens.get(tokenI++);
            add(Doc.Token.make(token, Doc.Token.RealOrImaginary.IMAGINARY, ZERO,
                    /* breakAndIndentTrailingComment= */ Optional.empty()));
        }//from   w  w w  .java  2  s  .  c o m
    }
    this.inputPosition = inputPosition;
    checkClosed(0);
}

From source file:solar.blaz.rondel.compiler.manager.AbstractInjectorManager.java

protected TypeElement[] parseViewComponent(ImmutableList<TypeMirror> components) {

    if (components == null || components.size() == 0) {
        return null;
    } else {//from   ww  w.ja v  a  2  s . c  o  m

        List<TypeElement> moduleElements = new ArrayList<>();
        for (int i = 0; i < components.size(); i++) {
            TypeMirror componentClass = components.get(i);

            TypeElement component = elementUtils.getTypeElement(componentClass.toString());

            if (component.getKind() == ElementKind.INTERFACE) {
                moduleElements.add(component);
            } else {
                messager.error("Component has to be interface.", component);
            }

        }

        if (moduleElements.isEmpty()) {
            return null;
        } else {
            return moduleElements.toArray(new TypeElement[moduleElements.size()]);
        }

    }

}

From source file:com.google.api.codegen.transformer.csharp.CSharpGapicSnippetsTransformer.java

private List<StaticLangApiMethodSnippetView> generateMethods(InterfaceContext context) {
    List<StaticLangApiMethodSnippetView> methods = new ArrayList<>();

    for (MethodModel method : csharpCommonTransformer.getSupportedMethods(context)) {
        MethodConfig methodConfig = context.getMethodConfig(method);
        MethodContext methodContext = context.asRequestMethodContext(method);
        if (methodConfig.isGrpcStreaming()) {
            methods.add(generateGrpcStreamingRequestMethod(methodContext));
        } else if (methodConfig.isLongRunningOperation()) {
            if (methodConfig.isFlattening()) {
                ImmutableList<FlatteningConfig> flatteningGroups = methodConfig.getFlatteningConfigs();
                boolean requiresNameSuffix = flatteningGroups.size() > 1;
                for (int i = 0; i < flatteningGroups.size(); i++) {
                    FlatteningConfig flatteningGroup = flatteningGroups.get(i);
                    String nameSuffix = requiresNameSuffix ? Integer.toString(i + 1) : "";
                    MethodContext methodContextFlat = context.asFlattenedMethodContext(method, flatteningGroup);
                    methods.add(generateOperationFlattenedAsyncMethod(methodContextFlat, nameSuffix));
                    methods.add(generateOperationFlattenedMethod(methodContextFlat, nameSuffix));
                }/* w  w w . ja  va2s.c  o m*/
            }
            methods.add(generateOperationRequestAsyncMethod(methodContext));
            methods.add(generateOperationRequestMethod(methodContext));
        } else if (methodConfig.isPageStreaming()) {
            if (methodConfig.isFlattening()) {
                ImmutableList<FlatteningConfig> flatteningGroups = methodConfig.getFlatteningConfigs();
                // Find flattenings that have ambiguous parameters, and mark them to use named arguments.
                // Ambiguity occurs in a page-stream flattening that has one or two extra string
                // parameters (that are not resource-names) compared to any other flattening of this same
                // method.
                // Create a string for each flattening, encoding which parameters are strings and
                // not-strings. Each character in the string refers to a parameter. Each string refers
                // to a flattening.
                String[] stringParams = flatteningGroups.stream().map(flat -> flat.getFlattenedFieldConfigs()
                        .values().stream()
                        .map(field -> field.getField().getType().isStringType()
                                && field.getResourceNameConfig() == null ? 's' : '.')
                        .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
                        .toString()).toArray(String[]::new);
                // Array of which flattenings need to use named arguments.
                // Each array entry refers to the correspondingly indexed flattening.
                Boolean[] requiresNamedParameters = Arrays.stream(stringParams)
                        .map(a -> Arrays.stream(stringParams)
                                .anyMatch(b -> a.startsWith(b + "s") || a.startsWith(b + "ss")))
                        .toArray(Boolean[]::new);
                boolean requiresNameSuffix = flatteningGroups.size() > 1;
                // Build method list.
                for (int i = 0; i < flatteningGroups.size(); i++) {
                    FlatteningConfig flatteningGroup = flatteningGroups.get(i);
                    String nameSuffix = requiresNameSuffix ? Integer.toString(i + 1) : "";
                    MethodContext methodContextFlat = context.asFlattenedMethodContext(method, flatteningGroup);
                    methods.add(generatePagedFlattenedAsyncMethod(methodContextFlat, nameSuffix,
                            requiresNamedParameters[i]));
                    methods.add(generatePagedFlattenedMethod(methodContextFlat, nameSuffix,
                            requiresNamedParameters[i]));
                }
            }
            methods.add(generatePagedRequestAsyncMethod(methodContext));
            methods.add(generatePagedRequestMethod(methodContext));
        } else {
            if (methodConfig.isFlattening()) {
                ImmutableList<FlatteningConfig> flatteningGroups = methodConfig.getFlatteningConfigs();
                boolean requiresNameSuffix = flatteningGroups.size() > 1;
                for (int i = 0; i < flatteningGroups.size(); i++) {
                    FlatteningConfig flatteningGroup = flatteningGroups.get(i);
                    String nameSuffix = requiresNameSuffix ? Integer.toString(i + 1) : "";
                    MethodContext methodContextFlat = context.asFlattenedMethodContext(method, flatteningGroup);
                    methods.add(generateFlattenedAsyncMethod(methodContextFlat, nameSuffix));
                    methods.add(generateFlattenedMethod(methodContextFlat, nameSuffix));
                }
            }
            methods.add(generateRequestAsyncMethod(methodContext));
            methods.add(generateRequestMethod(methodContext));
        }
    }

    return methods;
}

From source file:com.google.caliper.options.ParsedOptions.java

@Leftovers
private void setLeftovers(ImmutableList<String> leftovers) throws InvalidCommandException {
    if (leftovers.isEmpty()) {
        throw new InvalidCommandException("No benchmark class specified");
    }/*from  www  . ja va  2 s .c o m*/
    if (leftovers.size() > 1) {
        throw new InvalidCommandException("Extra stuff, expected only class name: " + leftovers);
    }
    this.benchmarkClassName = leftovers.get(0);
}

From source file:com.facebook.buck.macho.ObjectPathsAbsolutifier.java

private void updateBinaryUuid() {
    buffer.position(0);/*from www . j  a v a 2s . com*/
    ImmutableList<UUIDCommand> commands = LoadCommandUtils.findLoadCommandsWithClass(buffer,
            nulTerminatedCharsetDecoder, UUIDCommand.class);
    Preconditions.checkArgument(commands.size() == 1, "Found %d UUIDCommands, expected 1", commands.size());

    UUIDCommand uuidCommand = commands.get(0);
    UUIDCommand updatedCommand = uuidCommand.withUuid(UUID.randomUUID());
    UUIDCommandUtils.updateUuidCommand(buffer, uuidCommand, updatedCommand);
}

From source file:com.facebook.buck.config.resources.AbstractResourcesConfig.java

public ImmutableMap<String, ResourceAmounts> getResourceAmountsPerRuleType() {
    ImmutableMap.Builder<String, ResourceAmounts> result = ImmutableMap.builder();
    ImmutableMap<String, String> entries = getDelegate()
            .getEntriesForSection(RESOURCES_PER_RULE_SECTION_HEADER);
    for (String ruleName : entries.keySet()) {
        ImmutableList<String> configAmounts = getDelegate()
                .getListWithoutComments(RESOURCES_PER_RULE_SECTION_HEADER, ruleName);
        Preconditions.checkArgument(configAmounts.size() == ResourceAmounts.RESOURCE_TYPE_COUNT,
                "Buck config entry [%s].%s contains %s values, but expected to contain %s values "
                        + "in the following order: cpu, memory, disk_io, network_io",
                RESOURCES_PER_RULE_SECTION_HEADER, ruleName, configAmounts.size(),
                ResourceAmounts.RESOURCE_TYPE_COUNT);
        ResourceAmounts amounts = ResourceAmounts.of(Integer.parseInt(configAmounts.get(0)),
                Integer.parseInt(configAmounts.get(1)), Integer.parseInt(configAmounts.get(2)),
                Integer.parseInt(configAmounts.get(3)));
        result.put(ruleName, amounts);//from w  ww. j  a  v a2s  . com
    }
    return result.build();
}