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

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

Introduction

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

Prototype

public static <T> T getLast(Iterable<T> iterable) 

Source Link

Document

Returns the last element of iterable .

Usage

From source file:org.sosy_lab.cpachecker.cpa.value.refiner.utils.ErrorPathClassifier.java

private ARGPath obtainRefinementRootHeuristicBasedPrefix(List<ARGPath> pPrefixes,
        ErrorPathPrefixPreference preference, ARGPath originalErrorPath) {
    if (!classification.isPresent()) {
        return concatPrefixes(pPrefixes);
    }/*from ww  w . j a v a 2  s.  c  o  m*/

    MutableARGPath currentErrorPath = new MutableARGPath();
    Long bestScore = null;
    int bestIndex = 0;

    for (ARGPath currentPrefix : pPrefixes) {
        assert (Iterables.getLast(currentPrefix.asEdgesList()).getEdgeType() == CFAEdgeType.AssumeEdge);

        currentErrorPath.addAll(pathToList(currentPrefix));

        // gets the score for the prefix of how "local" it is
        AssumptionUseDefinitionCollector collector = new InitialAssumptionUseDefinitionCollector();
        collector.obtainUseDefInformation(currentErrorPath);
        Long score = Long.valueOf(collector.getDependenciesResolvedOffset() * (-1));

        if (preference.scorer.apply(Triple.of(score, bestScore, currentErrorPath.size()))) {
            bestScore = score;
            bestIndex = pPrefixes.indexOf(currentPrefix);
        }
    }

    return buildPath(bestIndex, pPrefixes, originalErrorPath);
}

From source file:org.jetbrains.jet.plugin.parameterInfo.JetFunctionParameterInfoHandler.java

@Override
public void updateUI(Pair<? extends FunctionDescriptor, ResolveSessionForBodies> itemToShow,
        ParameterInfoUIContext context) {
    //todo: when we will have ability to pass Array as vararg, implement such feature here too?
    if (context == null || context.getParameterOwner() == null || !context.getParameterOwner().isValid()) {
        context.setUIComponentEnabled(false);
        return;//w ww .jav  a  2 s  . co m
    }

    PsiElement parameterOwner = context.getParameterOwner();
    if (!(parameterOwner instanceof JetValueArgumentList)) {
        context.setUIComponentEnabled(false);
        return;
    }

    JetValueArgumentList argumentList = (JetValueArgumentList) parameterOwner;

    FunctionDescriptor functionDescriptor = itemToShow.first;
    ResolveSessionForBodies resolveSession = itemToShow.second;

    List<ValueParameterDescriptor> valueParameters = functionDescriptor.getValueParameters();
    List<JetValueArgument> valueArguments = argumentList.getArguments();

    int currentParameterIndex = context.getCurrentParameterIndex();
    int boldStartOffset = -1;
    int boldEndOffset = -1;
    boolean isGrey = false;
    boolean isDeprecated = KotlinBuiltIns.getInstance().isDeprecated(functionDescriptor);

    boolean[] usedIndexes = new boolean[valueParameters.size()];
    Arrays.fill(usedIndexes, false);

    boolean namedMode = false;

    if (!isIndexValid(valueParameters, currentParameterIndex)) {
        isGrey = true;
    }

    StringBuilder builder = new StringBuilder();

    PsiElement owner = context.getParameterOwner();
    BindingContext bindingContext = resolveSession.resolveToElement((JetElement) owner);

    for (int i = 0; i < valueParameters.size(); ++i) {
        if (i != 0) {
            builder.append(", ");
        }

        boolean highlightParameter = i == currentParameterIndex || (!namedMode && i < currentParameterIndex
                && Iterables.getLast(valueParameters).getVarargElementType() != null);

        if (highlightParameter) {
            boldStartOffset = builder.length();
        }

        if (!namedMode) {
            if (valueArguments.size() > i) {
                JetValueArgument argument = valueArguments.get(i);
                if (argument.isNamed()) {
                    namedMode = true;
                } else {
                    ValueParameterDescriptor param = valueParameters.get(i);
                    builder.append(renderParameter(param, false, bindingContext));
                    if (i <= currentParameterIndex && !isArgumentTypeValid(bindingContext, argument, param)) {
                        isGrey = true;
                    }
                    usedIndexes[i] = true;
                }
            } else {
                ValueParameterDescriptor param = valueParameters.get(i);
                builder.append(renderParameter(param, false, bindingContext));
            }
        }

        if (namedMode) {
            boolean takeAnyArgument = true;
            if (valueArguments.size() > i) {
                JetValueArgument argument = valueArguments.get(i);
                if (argument.isNamed()) {
                    for (int j = 0; j < valueParameters.size(); ++j) {
                        JetSimpleNameExpression referenceExpression = argument.getArgumentName()
                                .getReferenceExpression();
                        ValueParameterDescriptor param = valueParameters.get(j);
                        if (referenceExpression != null && !usedIndexes[j]
                                && param.getName().equals(referenceExpression.getReferencedNameAsName())) {
                            takeAnyArgument = false;
                            usedIndexes[j] = true;
                            builder.append(renderParameter(param, true, bindingContext));
                            if (i < currentParameterIndex
                                    && !isArgumentTypeValid(bindingContext, argument, param)) {
                                isGrey = true;
                            }
                            break;
                        }
                    }
                }
            }

            if (takeAnyArgument) {
                if (i < currentParameterIndex) {
                    isGrey = true;
                }

                for (int j = 0; j < valueParameters.size(); ++j) {
                    ValueParameterDescriptor param = valueParameters.get(j);
                    if (!usedIndexes[j]) {
                        usedIndexes[j] = true;
                        builder.append(renderParameter(param, true, bindingContext));
                        break;
                    }
                }
            }
        }

        if (highlightParameter) {
            boldEndOffset = builder.length();
        }
    }

    if (valueParameters.size() == 0) {
        builder.append(CodeInsightBundle.message("parameter.info.no.parameters"));
    }

    assert !builder.toString()
            .isEmpty() : "A message about 'no parameters' or some parameters should be present: "
                    + functionDescriptor;

    Color color = isResolvedToDescriptor(argumentList, functionDescriptor, bindingContext) ? GREEN_BACKGROUND
            : context.getDefaultParameterColor();
    context.setupUIComponentPresentation(builder.toString(), boldStartOffset, boldEndOffset, isGrey,
            isDeprecated, false, color);
}

From source file:org.lamport.tla.toolbox.jcloud.CloudDistributedTLCJob.java

@Override
protected IStatus run(final IProgressMonitor monitor) {
    monitor.beginTask("Starting TLC model checker in the cloud", 90 + (nodes > 1 ? 20 : 0));
    // Validate credentials and fail fast if null or syntactically incorrect
    if (!params.validateCredentials().equals(Status.OK_STATUS)) {
        return params.validateCredentials();
    }// ww w .  ja va2s  .c o  m

    ComputeServiceContext context = null;
    try {
        // Tweak tla2tools in a background thread. It takes a couple of seconds to run
        // pack200 to shrink the files size but we can lookup or launch a cloud instance
        // in the meantime.
        monitor.subTask("Tweaking tla2tools.jar to contain the spec & model (in background)");
        final ExecutorService executor = Executors.newSingleThreadExecutor();
        final Future<Payload> future = executor.submit(() -> {
            return PayloadHelper.appendModel2Jar(modelPath, props.getProperty(TLCJobFactory.MAIN_CLASS), props,
                    monitor);
        });
        executor.shutdown();
        // User has canceled the job, thus stop it (there will be more
        // cancelled checks down below).
        if (monitor.isCanceled()) {
            return Status.CANCEL_STATUS;
        }

        // example of specific properties, in this case optimizing image
        // list to only amazon supplied
        final Properties properties = new Properties();
        params.mungeProperties(properties);

        // Create compute environment in the cloud and inject an ssh
        // implementation. ssh is our means of communicating with the node.
        final Iterable<AbstractModule> modules = ImmutableSet.<AbstractModule>of(new SshjSshClientModule(),
                isCLI ? new ConsoleLoggingModule() : new SLF4JLoggingModule());

        final ContextBuilder builder = ContextBuilder.newBuilder(params.getCloudProvider())
                .credentials(params.getIdentity(), params.getCredentials()).modules(modules)
                .overrides(properties);
        params.mungeBuilder(builder);

        monitor.subTask("Initializing " + builder.getApiMetadata().getName());
        context = builder.buildView(ComputeServiceContext.class);
        final ComputeService compute = context.getComputeService();
        monitor.worked(10);
        if (monitor.isCanceled()) {
            return Status.CANCEL_STATUS;
        }

        //TODO Support instance reuse with Cloud distributed TLC.
        monitor.subTask("Looking for resusable nodes to quick-start model checking");
        final Set<NodeMetadata> createNodesInGroup = nodes > 1 ? new HashSet<>()
                : findReusableNodes(compute, monitor);
        monitor.worked(5);
        if (monitor.isCanceled()) {
            return Status.CANCEL_STATUS;
        } else if (createNodesInGroup.isEmpty()) {
            createNodesInGroup.addAll(provisionNodes(compute, monitor));
            if (monitor.isCanceled()) {
                return Status.CANCEL_STATUS;
            }
        } else {
            // skipped provisionNodes(...) which takes 35 steps.
            monitor.worked(35);
        }

        // Choose one of the nodes to be the master and create an
        // identifying predicate.
        final NodeMetadata master = Iterables.getLast(createNodesInGroup);
        final String hostname = Iterables.getOnlyElement(master.getPublicAddresses()); // master.getHostname() only returns internal name

        // Copy tlatools.jar to _one_ remote host (do not exhaust upload of
        // the machine running the toolbox).
        // TODO Share the tla2tools.jar with the worker nodes by making it
        // available on the master's webserver for the clients to download.
        // On the other hand this means we are making the spec
        // world-readable. It is cloud-readable already through the RMI api.
        monitor.subTask("Copying tla2tools.jar to master node at " + hostname);
        SshClient sshClient = context.utils().sshForNode().apply(master);
        sshClient.put("/tmp/tla2tools.pack.gz", future.get());
        monitor.worked(10);
        if (monitor.isCanceled()) {
            return Status.CANCEL_STATUS;
        }

        final String tlcMasterCommand = " shutdown -c && rm -rf /mnt/tlc/* && " // Cancel and remove any pending shutdown and leftovers from previous runs.
                + "cd /mnt/tlc/ && "
                // Decompress tla2tools.pack.gz
                + "unpack200 /tmp/tla2tools.pack.gz /tmp/tla2tools.jar" + " && "
                // Execute TLC (java) process inside screen
                // and shutdown on TLC's completion. But
                // detach from screen directly. Name screen 
                // session "tlc".
                // (see http://stackoverflow.com/a/10126799)
                + (isCLI ? "" : "screen -dm -S tlc bash -c \" ")
                // This requires a modified version where all parameters and
                // all spec modules are stored in files in a model/ folder
                // inside of the jar.
                // This is done in anticipation of other cloud providers
                // where one cannot easily pass in parameters on the command
                // line because there is no command line.
                + "java " + params.getJavaVMArgs() + " " + (doJfr ? params.getFlightRecording() + " " : "")
                // Write all tmp files to the ephemeral instance
                // storage which is expected to have a higher IOPS
                // compared to non-local storage.
                + "-Djava.io.tmpdir=/mnt/tlc/ "
                // These properties cannot be "backed" into
                // the payload jar as java itself does not 
                // support this.
                // It might be able to read the properties from 
                // the config file with 'com.sun.management.config.file=path',
                // but I haven't tried if the path can point into the jar.
                + "-Dcom.sun.management.jmxremote " + "-Dcom.sun.management.jmxremote.port=5400 "
                + "-Dcom.sun.management.jmxremote.ssl=false "
                + "-Dcom.sun.management.jmxremote.authenticate=false "
                // TLC tuning options
                + params.getJavaSystemProperties() + " " + "-jar /tmp/tla2tools.jar "
                + params.getTLCParameters() + " " + (isCLI ? "|& tee /mnt/tlc/MC.out " : "") + "&& "
                // Run any cloud specific cleanup tasks.
                // When CloudDistributedTLCJob runs in synchronous CLI mode (isCLI), it will destroy
                // the VMs (nodes) via the jclouds API. No need to deallocate nodes
                // via special logic.
                + (isCLI ? "/bin/true" : params.getCloudAPIShutdown()) + " && "
                // Let the machine power down immediately after
                // finishing model checking to cut costs. However,
                // do not shut down (hence "&&") when TLC finished
                // with an error.
                // It uses "sudo" because the script is explicitly
                // run as a user. No need to run the TLC process as
                // root.
                + "sudo shutdown -h +" + SHUTDOWN_AFTER + (isCLI ? "" : "\""); // closing opening '"' of screen/bash -c
        if (isCLI) {
            monitor.subTask("Starting TLC model checker process");
            // Execute command via ssh instead of as a script to get access to the TLC
            // processes' stdout and stderr.
            //TODO Better handle error case.
            ExecChannel channel = sshClient.execChannel(tlcMasterCommand);
            // Send remote TLC's stdout to local stdout (this throws a TransportException
            // unless shutdown is postponed by a few minutes above).
            ByteStreams.copy(channel.getOutput(), System.out);
            if (doJfr) {
                // Get Java Flight Recording from remote machine and save if to a local file in
                // the current working directory. We call "cat" because sftclient#get fails with
                // the old net.schmizz.sshj and an update to the newer com.hierynomus seems 
                // awful lot of work.
                channel = sshClient.execChannel("cat /mnt/tlc/tlc.jfr");
                final InputStream output = channel.getOutput();
                final String cwd = Paths.get(".").toAbsolutePath().normalize().toString() + File.separator;
                final File jfr = new File(cwd + "tlc.jfr");
                ByteStreams.copy(output, new FileOutputStream(jfr));
                if (jfr.length() == 0) {
                    System.err.println("Received empty Java Flight recording. Not creating tlc.jfr file");
                    jfr.delete();
                }
            }
            // Finally close the ssh connection.
            sshClient.disconnect();
            monitor.subTask("TLC model checker process finished");
            // Eagerly destroy the instance after we pulled the tlc.jfr file from it. No
            // point in waiting for shutdown -h +10 to shutdown the instance.
            destroyNodes(context, groupNameUUID);
        } else {
            sshClient.disconnect();

            // Run model checker master on master
            monitor.subTask("Starting TLC model checker process on the master node (in background)");
            final ExecResponse response = compute.runScriptOnNode(master.getId(), exec(tlcMasterCommand),
                    new TemplateOptions().overrideLoginCredentials(master.getCredentials()).runAsRoot(false)
                            .wrapInInitScript(true).blockOnComplete(false).blockUntilRunning(false));
            throwExceptionOnErrorResponse(master, response,
                    "Starting TLC model checker process on the master node");
            monitor.worked(5);

            if (nodes > 1) {
                // The predicate will be applied to ALL instances owned by the
                // cloud account (ie AWS), even the ones in different regions
                // completely unrelated to TLC.
                final Predicate<NodeMetadata> isMaster = new Predicate<NodeMetadata>() {
                    private final String masterHostname = master.getHostname();

                    public boolean apply(NodeMetadata nodeMetadata) {
                        // hostname can be null if instance is terminated.
                        final String hostname = nodeMetadata.getHostname();
                        return masterHostname.equals(hostname);
                    };
                };
                // copy the tla2tools.jar to the root of the master's webserver
                // to make it available to workers. However, strip the spec
                // (*.tla/*.cfg/...) from the jar file to not share the spec
                // with the world.
                monitor.subTask("Make TLC code available to all worker node(s)");
                Map<? extends NodeMetadata, ExecResponse> execResponse = compute.runScriptOnNodesMatching(
                        isMaster,
                        exec("cp /tmp/tla2tools.jar /var/www/html/tla2tools.jar && "
                                + "zip -d /var/www/html/tla2tools.jar model/*.tla model/*.cfg model/generated.properties"),
                        new TemplateOptions().runAsRoot(true).wrapInInitScript(false));
                throwExceptionOnErrorResponse(execResponse, "Make TLC code available to all worker node");
                monitor.worked(10);
                if (monitor.isCanceled()) {
                    return Status.CANCEL_STATUS;
                }

                // The predicate will be applied to ALL instances owned by the
                // AWS account, even the ones in different regions completely
                // unrelated to TLC.
                final Predicate<NodeMetadata> onWorkers = new Predicate<NodeMetadata>() {
                    // Remove the master from the set of our nodes.
                    private final Iterable<? extends NodeMetadata> workers = Iterables
                            .filter(createNodesInGroup, new Predicate<NodeMetadata>() {
                                private final String masterHostname = master.getHostname();

                                public boolean apply(NodeMetadata nodeMetadata) {
                                    // nodeMetadata.getHostname is null for terminated hosts.
                                    return !masterHostname.equals(nodeMetadata.getHostname());
                                };
                            });

                    public boolean apply(NodeMetadata nodeMetadata) {
                        return Iterables.contains(workers, nodeMetadata);
                    };
                };

                // see master startup for comments
                monitor.subTask("Starting TLC workers on the remaining node(s) (in background)");
                final String privateHostname = Iterables.getOnlyElement(master.getPrivateAddresses());
                execResponse = compute.runScriptOnNodesMatching(onWorkers,
                        exec("cd /mnt/tlc/ && " + "wget http://" + privateHostname + "/tla2tools.jar && "
                                + "screen -dm -S tlc bash -c \" " + "java " + params.getJavaWorkerVMArgs() + " "
                                + "-Djava.io.tmpdir=/mnt/tlc/ " + "-Dcom.sun.management.jmxremote "
                                + "-Dcom.sun.management.jmxremote.port=5400 "
                                + "-Dcom.sun.management.jmxremote.ssl=false "
                                + "-Dcom.sun.management.jmxremote.authenticate=false "
                                + params.getJavaWorkerSystemProperties() + " " + "-cp /mnt/tlc/tla2tools.jar "
                                + params.getTLCWorkerParameters() + " " + privateHostname + " " // Use host's internal ip due to firewall reasons.
                                + "&& "
                                // Terminate regardless of TLCWorker process
                                // exit value. E.g. TLCWorker can terminate due
                                // to a NoRouteToHostException when the master
                                // shut down caused by a violation among the
                                // init states.
                                // Run any cloud specific cleanup tasks.
                                + params.getCloudAPIShutdown() + " && " + "sudo shutdown -h now" + "\""),
                        new TemplateOptions().runAsRoot(false).wrapInInitScript(true).blockOnComplete(false)
                                .blockUntilRunning(false));
                throwExceptionOnErrorResponse(execResponse, "Starting TLC workers");
                monitor.worked(10);
            }

        }

        // Get the output from the remote instance and attach the corresponding
        // InputStream to the CloudStatus. A UI can then read the InputStream and show
        // the output of the TLC process to a user. The SSH connection automatically
        // terminates when the TLC process finishes.
        // https://askubuntu.com/questions/509881/tail-reading-an-entire-file-and-then-following         
        ExecChannel execChannel = null;
        if (!isCLI) {
            execChannel = sshClient
                    .execChannel("tail -q -f -n +1 /mnt/tlc/MC.out --pid $(pgrep -f tla2tools.jar)");
        }

        // Communicate result to user
        monitor.done();
        return new CloudStatus(Status.OK, "org.lamport.tla.toolbox.jcloud", Status.OK,
                String.format(
                        "TLC is model checking at host %s. "
                                + "Expect to receive an email at %s with the model checking result eventually.",
                        hostname, props.get("result.mail.address")),
                null, new URL("http://" + hostname + "/munin/"),
                execChannel == null ? null : execChannel.getOutput(), sshClient);
    } catch (ExecutionException | InterruptedException | RunNodesException | IOException
            | RunScriptOnNodesException | NoSuchElementException | AuthorizationException | SshException e) {
        e.printStackTrace();
        if (context != null) {
            destroyNodes(context, groupNameUUID);
        }
        // signal error to caller
        return new Status(Status.ERROR, "org.lamport.tla.toolbox.jcloud", e.getMessage(), e);
    } catch (ScriptException e) {
        if (context != null) {
            destroyNodes(context, groupNameUUID);
        }
        // signal error to caller
        return new Status(Status.ERROR, "org.lamport.tla.toolbox.jcloud", e.getTitle(), e);
    } finally {
        if (context != null) {
            // The user has canceled the Toolbox job, take this as a request
            // to destroy all nodes this job has created.
            if (monitor.isCanceled()) {
                destroyNodes(context, groupNameUUID);
            }
            context.close();
        }
    }
}

From source file:com.google.errorprone.bugpatterns.TypeParameterNaming.java

private static String suggestedNameFollowedWithT(String identifier) {
    Preconditions.checkArgument(!identifier.isEmpty());

    // Some early checks:
    // TFoo => FooT
    if (identifier.length() > 2 && identifier.charAt(0) == 'T' && Ascii.isUpperCase(identifier.charAt(1))
            && Ascii.isLowerCase(identifier.charAt(2))) {
        // splitToLowercaseTerms thinks "TFooBar" is ["tfoo", "bar"], so we remove "t", have it parse
        // as ["foo", "bar"], then staple "t" back on the end.
        ImmutableList<String> tokens = NamingConventions.splitToLowercaseTerms(identifier.substring(1));
        return Streams.concat(tokens.stream(), Stream.of("T")).map(TypeParameterNaming::upperCamelToken)
                .collect(Collectors.joining());
    }/*w  w  w .j  ava2 s  .  c o m*/

    ImmutableList<String> tokens = NamingConventions.splitToLowercaseTerms(identifier);

    // UPPERCASE => UppercaseT
    if (tokens.size() == 1) {
        String token = tokens.get(0);
        if (Ascii.toUpperCase(token).equals(identifier)) {
            return upperCamelToken(token) + "T";
        }
    }

    // FooType => FooT
    if (Iterables.getLast(tokens).equals("type")) {
        return Streams.concat(tokens.subList(0, tokens.size() - 1).stream(), Stream.of("T"))
                .map(TypeParameterNaming::upperCamelToken).collect(Collectors.joining());
    }

    return identifier + "T";
}

From source file:de.cismet.cids.jsonpatch.operation.cidsbean.AddOperation.java

/**
 * DOCUMENT ME!//from   w w w  .  j ava  2 s .  c om
 *
 * @param   parentBean  DOCUMENT ME!
 *
 * @throws  JsonPatchException  DOCUMENT ME!
 */
protected void addToObject(final CidsBean parentBean) throws JsonPatchException {
    final String property = Iterables.getLast(path).getToken().getRaw();

    final ObjectAttribute objectAttribute = parentBean.getMetaObject().getAttributeByFieldName(property);
    if (objectAttribute == null) {
        LOGGER.error(RESOURCE_BUNDLE.getString("jsonPatch.noSuchProperty") + ": " + this.path.toString());
        throw new JsonPatchException(RESOURCE_BUNDLE.getString("jsonPatch.noSuchProperty"));
    }

    final Object valueObject = UTILS.deserializeAndVerifyCidsBean(this.value);
    if (CidsBean.class.isAssignableFrom(valueObject.getClass())) {
        if (!objectAttribute.getMai().isForeignKey()) {
            LOGGER.error(RESOURCE_BUNDLE.getString("jsonPatch.propertyValueMissmatch") + ": "
                    + "cids bean provided but not expected at " + this.path.toString());
            throw new JsonPatchException(RESOURCE_BUNDLE.getString("jsonPatch.propertyValueMissmatch"));
        }

        if (!this.overwrite && (parentBean.getProperty(property) != null)) {
            LOGGER.error(RESOURCE_BUNDLE.getString("jsonPatch.propertyNotEmpty") + ": " + property);
            throw new JsonPatchException(RESOURCE_BUNDLE.getString("jsonPatch.propertyNotEmpty"));
        }

        try {
            parentBean.setProperty(property, (CidsBean) valueObject);
        } catch (Exception ex) {
            LOGGER.error(RESOURCE_BUNDLE.getString("jsonPatch.setPropertyFailed") + ": " + property, ex);
            throw new JsonPatchException(RESOURCE_BUNDLE.getString("jsonPatch.setPropertyFailed"), ex);
        }
    } else if (List.class.isAssignableFrom(valueObject.getClass())) {
        final List<CidsBean> beanCollectionProperty = parentBean.getBeanCollectionProperty(property);
        if (!objectAttribute.getMai().isArray() || (beanCollectionProperty == null)) {
            LOGGER.error(RESOURCE_BUNDLE.getString("jsonPatch.propertyValueMissmatch") + ": "
                    + "cids bean array provided but not expected at " + this.path.toString());
            throw new JsonPatchException(RESOURCE_BUNDLE.getString("jsonPatch.propertyValueMissmatch"));
        }

        if (!this.overwrite && !beanCollectionProperty.isEmpty()) {
            LOGGER.error(RESOURCE_BUNDLE.getString("jsonPatch.propertyNotEmpty") + ": array " + property
                    + "size: " + beanCollectionProperty.size());
            throw new JsonPatchException(RESOURCE_BUNDLE.getString("jsonPatch.propertyNotEmpty"));
        } else if (this.overwrite) {
            beanCollectionProperty.clear();
            beanCollectionProperty.addAll((List<CidsBean>) valueObject);
        } else {
            beanCollectionProperty.addAll((List<CidsBean>) valueObject);
        }
    } else if (ValueNode.class.isAssignableFrom(valueObject.getClass())) {
        if (!this.overwrite && (parentBean.getProperty(property) != null)) {
            LOGGER.error(RESOURCE_BUNDLE.getString("jsonPatch.propertyNotEmpty") + ": " + property);
            throw new JsonPatchException(RESOURCE_BUNDLE.getString("jsonPatch.propertyNotEmpty"));
        }

        final Class attrClass = BlacklistClassloading.forName(objectAttribute.getMai().getJavaclassname());
        if (attrClass == null) {
            LOGGER.error(RESOURCE_BUNDLE.getString("jsonPatch.noSuchProperty") + ": " + this.path.toString());
            throw new JsonPatchException(RESOURCE_BUNDLE.getString("jsonPatch.noSuchProperty"));
        }

        final ValueNode valueNode = (ValueNode) valueObject;

        try {
            if (valueNode.isNumber()) {
                if (attrClass.equals(Integer.class)) {
                    final int i = valueNode.asInt();
                    parentBean.setProperty(property, i);
                } else if (attrClass.equals(Long.class)) {
                    final long l = valueNode.asLong();
                    parentBean.setProperty(property, l);
                } else if (attrClass.equals(Float.class)) {
                    final float f = (float) valueNode.asDouble();
                    parentBean.setProperty(property, f);
                } else if (attrClass.equals(Double.class)) {
                    final double d = valueNode.asDouble();
                    parentBean.setProperty(property, d);
                } else if (attrClass.equals(java.sql.Timestamp.class)) {
                    final Timestamp ts = new Timestamp(valueNode.asLong());
                    parentBean.setProperty(property, ts);
                } else if (attrClass.equals(BigDecimal.class)) {
                    final BigDecimal bd = new BigDecimal(valueNode.asText());
                    parentBean.setProperty(property, bd);
                } else {
                    throw new Exception("no numeric handler available for class " + attrClass.getSimpleName());
                }
            } else if (valueNode.isBoolean()) {
                final boolean bl = valueNode.asBoolean();
                parentBean.setProperty(property, bl);
            } else if (valueNode.isMissingNode() || NullNode.class.isAssignableFrom(valueNode.getClass())) {
                parentBean.setProperty(property, null);
            } else if (valueNode.isTextual()) {
                final String str = valueNode.textValue();
                if (attrClass.equals(Geometry.class)) {
                    final Geometry geom = UTILS.fromEwkt(str);
                    parentBean.setProperty(property, geom);
                } else if (attrClass.equals(String.class)) {
                    parentBean.setProperty(property, str);
                } else {
                    LOGGER.warn("expected geometry or string property but got " + attrClass.getSimpleName());
                    parentBean.setProperty(property, str);
                }
            } else {
                throw new Exception("no handler available for value " + valueNode.toString());
            }
        } catch (Exception ex) {
            LOGGER.error(RESOURCE_BUNDLE.getString("jsonPatch.setPropertyFailed") + ": " + property, ex);
            throw new JsonPatchException(RESOURCE_BUNDLE.getString("jsonPatch.setPropertyFailed"), ex);
        }
    }
}

From source file:com.google.gerrit.server.index.ChangeSchemas.java

public static Schema<ChangeData> getLatest() {
    return Iterables.getLast(ALL.values());
}

From source file:org.jetbrains.kotlin.idea.parameterInfo.JetFunctionParameterInfoHandler.java

@Override
public void updateUI(Pair<? extends FunctionDescriptor, ResolutionFacade> itemToShow,
        @NotNull ParameterInfoUIContext context) {
    //todo: when we will have ability to pass Array as vararg, implement such feature here too?
    if (context == null || context.getParameterOwner() == null || !context.getParameterOwner().isValid()) {
        context.setUIComponentEnabled(false);
        return;/*from w w  w.j a v a  2s.  c om*/
    }

    PsiElement parameterOwner = context.getParameterOwner();
    if (!(parameterOwner instanceof JetValueArgumentList)) {
        context.setUIComponentEnabled(false);
        return;
    }

    JetValueArgumentList argumentList = (JetValueArgumentList) parameterOwner;

    FunctionDescriptor functionDescriptor = itemToShow.first;
    ResolutionFacade resolutionFacade = itemToShow.second;

    List<ValueParameterDescriptor> valueParameters = functionDescriptor.getValueParameters();
    List<JetValueArgument> valueArguments = argumentList.getArguments();

    int currentParameterIndex = context.getCurrentParameterIndex();
    int boldStartOffset = -1;
    int boldEndOffset = -1;
    boolean isGrey = false;
    boolean isDeprecated = KotlinBuiltIns.isDeprecated(functionDescriptor);

    boolean[] usedIndexes = new boolean[valueParameters.size()];
    Arrays.fill(usedIndexes, false);

    boolean namedMode = false;

    if (!isIndexValid(valueParameters, currentParameterIndex)) {
        isGrey = true;
    }

    StringBuilder builder = new StringBuilder();

    PsiElement owner = context.getParameterOwner();
    BindingContext bindingContext = resolutionFacade.analyze((JetElement) owner, BodyResolveMode.FULL);

    for (int i = 0; i < valueParameters.size(); ++i) {
        if (i != 0) {
            builder.append(", ");
        }

        boolean highlightParameter = i == currentParameterIndex || (!namedMode && i < currentParameterIndex
                && Iterables.getLast(valueParameters).getVarargElementType() != null);

        if (highlightParameter) {
            boldStartOffset = builder.length();
        }

        if (!namedMode) {
            if (valueArguments.size() > i) {
                JetValueArgument argument = valueArguments.get(i);
                if (argument.isNamed()) {
                    namedMode = true;
                } else {
                    ValueParameterDescriptor param = valueParameters.get(i);
                    builder.append(renderParameter(param, false));
                    if (i <= currentParameterIndex && !isArgumentTypeValid(bindingContext, argument, param)) {
                        isGrey = true;
                    }
                    usedIndexes[i] = true;
                }
            } else {
                ValueParameterDescriptor param = valueParameters.get(i);
                builder.append(renderParameter(param, false));
            }
        }

        if (namedMode) {
            boolean takeAnyArgument = true;
            if (valueArguments.size() > i) {
                JetValueArgument argument = valueArguments.get(i);
                if (argument.isNamed()) {
                    for (int j = 0; j < valueParameters.size(); ++j) {
                        JetSimpleNameExpression referenceExpression = argument.getArgumentName()
                                .getReferenceExpression();
                        ValueParameterDescriptor param = valueParameters.get(j);
                        if (referenceExpression != null && !usedIndexes[j]
                                && param.getName().equals(referenceExpression.getReferencedNameAsName())) {
                            takeAnyArgument = false;
                            usedIndexes[j] = true;
                            builder.append(renderParameter(param, true));
                            if (i < currentParameterIndex
                                    && !isArgumentTypeValid(bindingContext, argument, param)) {
                                isGrey = true;
                            }
                            break;
                        }
                    }
                }
            }

            if (takeAnyArgument) {
                if (i < currentParameterIndex) {
                    isGrey = true;
                }

                for (int j = 0; j < valueParameters.size(); ++j) {
                    ValueParameterDescriptor param = valueParameters.get(j);
                    if (!usedIndexes[j]) {
                        usedIndexes[j] = true;
                        builder.append(renderParameter(param, true));
                        break;
                    }
                }
            }
        }

        if (highlightParameter) {
            boldEndOffset = builder.length();
        }
    }

    if (valueParameters.size() == 0) {
        builder.append(CodeInsightBundle.message("parameter.info.no.parameters"));
    }

    assert !builder.toString()
            .isEmpty() : "A message about 'no parameters' or some parameters should be present: "
                    + functionDescriptor;

    Color color = isResolvedToDescriptor(argumentList, functionDescriptor, bindingContext) ? GREEN_BACKGROUND
            : context.getDefaultParameterColor();
    context.setupUIComponentPresentation(builder.toString(), boldStartOffset, boldEndOffset, isGrey,
            isDeprecated, false, color);
}

From source file:com.google.javascript.jscomp.CrossChunkReferenceCollector.java

private static <T> T peek(List<T> list) {
    return Iterables.getLast(list);
}

From source file:org.tensorflow.tensorboard.vulcanize.Vulcanize.java

private static Webpath me() {
    return Iterables.getLast(stack);
}

From source file:org.opendaylight.groupbasedpolicy.renderer.ofoverlay.sf.ChainAction.java

@Override
public List<ActionBuilder> updateAction(List<ActionBuilder> actions, Map<String, Object> params, Integer order,
        NetworkElements netElements, PolicyPair policyPair, OfWriter ofWriter, OfContext ctx,
        Direction direction) {/*w w  w . j a  va2 s  .  c  om*/
    /*
     * Get the named chain
     */
    String chainName = null;
    if (params != null) {
        LOG.debug("updateAction: Searching for named chain");
        for (String name : params.keySet()) {
            if (name.equals(ChainActionDefinition.SFC_CHAIN_NAME)) {
                chainName = (String) params.get(name);
                if (chainName == null) {
                    LOG.error("updateAction: Chain name was null");
                    return null;
                }
            }
        }
    } else {
        LOG.error("updateAction: Parameters null for chain action");
        return null;
    }

    if (chainName == null) {
        LOG.error("updateAction: Chain name was null");
        return null;
    }

    Long returnVnId;

    /*
     * If path is symmetrical then there are two RSPs.
     * if srcEp is in consumer EPG use "rspName"
     * else srcEp is in provider EPG, "rspName-Reverse".
     */
    ServiceFunctionPath sfcPath = getSfcPath(new SfcName(chainName));
    if (sfcPath == null || sfcPath.getName() == null) {
        LOG.error("updateAction: SFC Path was invalid. Either null or name was null.", sfcPath);
        return null;
    }
    // TODO Need helper function to get getTenantName() that returns Name or UUID if Name is
    // null

    String tenantName = netElements.getSrcEp().getTenant().getValue();
    // Find existing RSP based on following naming convention, else create it.
    RspName rspName = new RspName(sfcPath.getName().getValue() + tenantName + "-gbp-rsp");
    ReadOnlyTransaction rTx = ctx.getDataBroker().newReadOnlyTransaction();
    RenderedServicePath renderedServicePath;
    RenderedServicePath rsp = getRspByName(rspName, rTx);
    returnVnId = (long) resolveTunnelId(netElements, false);
    if (rsp == null) {
        renderedServicePath = createRsp(sfcPath, rspName);
        if (renderedServicePath != null) {
            LOG.info("updateAction: Could not find RSP {} for Chain {}, created.", rspName, chainName);
        } else {
            LOG.error("updateAction: Could not create RSP {} for Chain {}", rspName, chainName);
            return null;
        }
    } else {
        renderedServicePath = rsp;
    }

    try {
        if (sfcPath.isSymmetric() && direction.equals(Direction.Out)) {
            rspName = new RspName(rspName.getValue() + "-Reverse");
            rsp = getRspByName(rspName, rTx);
            returnVnId = (long) resolveTunnelId(netElements, true);
            if (rsp == null) {
                LOG.info("updateAction: Could not find Reverse RSP {} for Chain {}", rspName, chainName);
                renderedServicePath = createSymmetricRsp(renderedServicePath);
                if (renderedServicePath == null) {
                    LOG.error("updateAction: Could not create RSP {} for Chain {}", rspName, chainName);
                    return null;
                }
            } else {
                renderedServicePath = rsp;
            }
        }
    } catch (Exception e) {
        LOG.error("updateAction: Attempting to determine if srcEp {} was consumer.",
                netElements.getSrcEp().getKey(), e);
        return null;
    }

    RenderedServicePathFirstHop rspFirstHop = SfcProviderRenderedPathAPI
            .readRenderedServicePathFirstHop(rspName);
    if (!isValidRspFirstHop(rspFirstHop)) {
        // Errors logged in method.
        return null;
    }

    NodeId tunnelDestNodeId = netElements.getDstNodeId();

    IpAddress tunnelDest = ctx.getSwitchManager().getTunnelIP(tunnelDestNodeId, TunnelTypeVxlanGpe.class);
    if (tunnelDest == null || tunnelDest.getIpv4Address() == null) {
        LOG.error("updateAction: Invalid tunnelDest for NodeId: {}", tunnelDestNodeId);
        return null;
    }

    RenderedServicePathHop firstRspHop = renderedServicePath.getRenderedServicePathHop().get(0);
    RenderedServicePathHop lastRspHop = Iterables.getLast(renderedServicePath.getRenderedServicePathHop());
    SfcNshHeader sfcNshHeader = new SfcNshHeaderBuilder().setNshTunIpDst(rspFirstHop.getIp().getIpv4Address())
            .setNshTunUdpPort(rspFirstHop.getPort()).setNshNsiToChain(firstRspHop.getServiceIndex())
            .setNshNspToChain(renderedServicePath.getPathId())
            .setNshNsiFromChain((short) (lastRspHop.getServiceIndex().intValue() - 1))
            .setNshNspFromChain(renderedServicePath.getPathId())
            .setNshMetaC1(SfcNshHeader.convertIpAddressToLong(tunnelDest.getIpv4Address()))
            .setNshMetaC2(returnVnId).build();

    // Cannot set all actions here. Some actions are destination specific, and we don't know
    // a destination is to be
    // chained until we reach this point. Need to write match/action in External Table for
    // chained packets.
    actions = addActionBuilder(actions, nxSetNsiAction(sfcNshHeader.getNshNsiToChain()), order);
    actions = addActionBuilder(actions, nxSetNspAction(sfcNshHeader.getNshNspToChain()), order);
    createChainTunnelFlows(sfcNshHeader, netElements, ofWriter, ctx);
    return actions;
}