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.opendaylight.yangtools.yang.parser.stmt.rfc6020.TypeUtils.java

public static List<LengthConstraint> parseLengthListFromString(final StmtContext<?, ?, ?> ctx,
        final String lengthArgument) {
    final Optional<String> description = Optional.absent();
    final Optional<String> reference = Optional.absent();

    final List<LengthConstraint> lengthConstraints = new ArrayList<>();

    for (final String singleRange : PIPE_SPLITTER.split(lengthArgument)) {
        final Iterator<String> boundaries = TWO_DOTS_SPLITTER.splitToList(singleRange).iterator();
        final Number min = parseIntegerConstraintValue(ctx, boundaries.next());

        final Number max;
        if (boundaries.hasNext()) {
            max = parseIntegerConstraintValue(ctx, boundaries.next());

            // if min larger than max then error
            Preconditions.checkArgument(compareNumbers(min, max) != 1,
                    "Length constraint %s has descending order of boundaries; should be ascending. Statement source at %s",
                    singleRange, ctx.getStatementSourceReference());
            Preconditions.checkArgument(!boundaries.hasNext(),
                    "Wrong number of boundaries in length constraint %s. Statement source at %s", singleRange,
                    ctx.getStatementSourceReference());
        } else {/*from ww  w  . j a  v  a  2  s .c om*/
            max = min;
        }

        // some of intervals overlapping
        if (lengthConstraints.size() > 1
                && compareNumbers(min, Iterables.getLast(lengthConstraints).getMax()) != 1) {
            throw new InferenceException(ctx.getStatementSourceReference(),
                    "Some of the length ranges in %s are not disjoint", lengthArgument);
        }

        lengthConstraints.add(new LengthConstraintEffectiveImpl(min, max, description, reference));
    }

    return lengthConstraints;
}

From source file:org.jclouds.gogrid.GoGridLiveTestDisabled.java

/**
 * Starts a servers, verifies that jobs are created correctly and an be retrieved from the job
 * services//from w w  w .j  ava  2  s.c  o m
 */
@Test(dependsOnMethods = "testServerLifecycle", enabled = true)
public void testJobs() {
    final String nameOfServer = "Server" + String.valueOf(new Date().getTime()).substring(6);
    serversToDeleteAfterTheTests.add(nameOfServer);

    Set<Ip> availableIps = api.getIpServices().getUnassignedPublicIpList();

    String ram = Iterables.get(api.getServerServices().getRamSizes(), 0).getName();

    Server createdServer = api.getServerServices().addServer(nameOfServer,
            "GSI-f8979644-e646-4711-ad58-d98a5fa3612c", ram, Iterables.getLast(availableIps).getIp());

    assert serverLatestJobCompleted.apply(createdServer);

    // restart the server
    api.getServerServices().power(nameOfServer, PowerCommand.RESTART);

    Set<Job> jobs = api.getJobServices().getJobsForObjectName(nameOfServer);

    Job latestJob = Iterables.getLast(jobs);
    Long latestJobId = latestJob.getId();

    Job latestJobFetched = Iterables.getOnlyElement(api.getJobServices().getJobsById(latestJobId));

    assert latestJob.equals(latestJobFetched) : "Job and its representation found by ID don't match";

    long[] idsOfAllJobs = new long[jobs.size()];
    int i = 0;
    for (Job job : jobs) {
        idsOfAllJobs[i++] = job.getId();
    }

    Set<Job> jobsFetched = api.getJobServices().getJobsById(idsOfAllJobs);
    assert jobsFetched.size() == jobs.size() : format(
            "Number of jobs fetched by ids doesn't match the number of jobs "
                    + "requested. Requested/expected: %d. Found: %d.",
            jobs.size(), jobsFetched.size());

    // delete the server
    api.getServerServices().deleteByName(nameOfServer);
}

From source file:com.google.security.zynamics.reil.translators.ReilTranslator.java

/**
 * This function is responsible for modifying the generated graph at all likely delayed branches.
 * /*from w  ww  .  ja  v  a  2 s.c o  m*/
 * @param nodes
 * @param edges
 * @param delayedTrueBranches
 */
private static void handleDelayedTrueBranches(final List<ReilBlock> nodes, final List<ReilEdge> edges,
        final List<List<ReilInstruction>> delayedTrueBranches) {
    for (final List<ReilInstruction> lastReil : delayedTrueBranches) {
        // In this post-processing step we consider all the delayed branches where the delayed
        // instruction is only executed if the branch is taken.
        //
        // We solve the problem by removing the branch-delayed instruction from the original
        // block. Then we take the removed instructions to form a new block. The true branch
        // of the original block is connected with the new block. The false branch of the
        // original block remains unchanged.

        final ReilInstruction lastReilInstruction = lastReil.get(lastReil.size() - 1);

        for (final ReilBlock node : nodes) {
            final Iterable<ReilInstruction> nodeInstructions = node.getInstructions();

            if (Iterables.getLast(nodeInstructions) == lastReilInstruction) {
                // The situation we are having here is that have located the
                // node that contains the delayed instruction. In fact this node
                // contains only the code of the delayed instruction. It has one
                // incoming edge and two outgoing edges.
                //
                // We now have to rewrite the edges to make sure the jump has
                // the two outgoing edges.

                final ReilEdge incomingEdge = node.getIncomingEdges().get(0);

                final ReilBlock parentNode = incomingEdge.getSource();

                edges.remove(incomingEdge);

                boolean first = true;

                for (final ReilEdge outgoingEdge : node.getOutgoingEdges()) {
                    if (first) {
                        first = false;

                        final ReilEdge newEdge = new ReilEdge(parentNode, node, EdgeType.JUMP_CONDITIONAL_TRUE);

                        ReilBlock.link(parentNode, node, newEdge);

                        edges.add(newEdge);

                        final ReilEdge newEdge2 = new ReilEdge(parentNode, outgoingEdge.getTarget(),
                                EdgeType.JUMP_CONDITIONAL_FALSE);

                        ReilBlock.link(parentNode, outgoingEdge.getTarget(), newEdge2);

                        edges.add(newEdge2);
                    } else {
                        final ReilEdge newEdge2 = new ReilEdge(node, outgoingEdge.getTarget(),
                                outgoingEdge.getType());

                        ReilBlock.link(node, outgoingEdge.getTarget(), newEdge2);

                        edges.add(newEdge2);
                    }

                    edges.remove(outgoingEdge);

                    ReilBlock.unlink(outgoingEdge.getSource(), outgoingEdge.getTarget(), outgoingEdge);
                }
            }
        }
    }
}

From source file:com.b2international.snowowl.snomed.importer.rf2.validation.SnomedValidationContext.java

private void addRefSetFile(final URL url) throws IOException {

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), Charsets.UTF_8))) {
        final String header = reader.readLine();

        // guard against invalid files/folders in the SCT RF2 archive/root folder
        if (StringUtils.isEmpty(header)) {
            return;
        }/*from   ww w  .j a  v  a2  s . c  o m*/

        List<String> headerElements = TAB_SPLITTER.splitToList(header);
        final String lastColumn = Iterables.getLast(headerElements);

        if (lastColumn.equalsIgnoreCase(SnomedRf2Headers.FIELD_REFERENCED_COMPONENT_ID)) {
            releaseFileValidators.add(new SnomedSimpleTypeRefSetValidator(configuration, url, this));
        } else if (lastColumn.equalsIgnoreCase(SnomedRf2Headers.FIELD_VALUE_ID)) {
            releaseFileValidators.add(new SnomedAttributeValueRefSetValidator(configuration, url, this));
        } else if (lastColumn.equalsIgnoreCase(SnomedRf2Headers.FIELD_CHARACTERISTIC_TYPE_ID)) {
            releaseFileValidators
                    .add(new SnomedConcreteDataTypeRefSetValidator(configuration, url, this, true));
        } else if (lastColumn.equalsIgnoreCase(SnomedRf2Headers.FIELD_VALUE)) { // AU CDT refset
            releaseFileValidators
                    .add(new SnomedConcreteDataTypeRefSetValidator(configuration, url, this, false));
        } else if (lastColumn.equalsIgnoreCase(SnomedRf2Headers.FIELD_MAP_TARGET)) {
            releaseFileValidators.add(new SnomedSimpleMapTypeRefSetValidator(configuration, url, this));
        } else if (lastColumn.equalsIgnoreCase(SnomedRf2Headers.FIELD_CORRELATION_ID)) {
            releaseFileValidators.add(new SnomedComplexMapTypeRefSetValidator(configuration, url, this));
        } else if (lastColumn.equalsIgnoreCase(SnomedRf2Headers.FIELD_DESCRIPTION_LENGTH)) {
            releaseFileValidators.add(new SnomedDescriptionTypeRefSetValidator(configuration, url, this));
        } else if (lastColumn.equalsIgnoreCase(SnomedRf2Headers.FIELD_TARGET_COMPONENT)
                || lastColumn.equalsIgnoreCase(SnomedRf2Headers.FIELD_TARGET_COMPONENT_ID)) {
            releaseFileValidators.add(new SnomedAssociationRefSetValidator(configuration, url, this));
        } else if (lastColumn.equalsIgnoreCase(SnomedRf2Headers.FIELD_ACCEPTABILITY_ID)) {
            releaseFileValidators.add(new SnomedLanguageRefSetValidator(configuration, url, this));
        } else if (lastColumn.equalsIgnoreCase(SnomedRf2Headers.FIELD_TARGET_EFFECTIVE_TIME)) {
            releaseFileValidators.add(new SnomedModuleDependencyRefSetValidator(configuration, url, this));
        } else if (lastColumn.equals(SnomedRf2Headers.FIELD_MAP_CATEGORY_ID)) {
            releaseFileValidators.add(new SnomedExtendedMapTypeRefSetValidator(configuration, url, this));
        } else if (lastColumn.equalsIgnoreCase(SnomedRf2Headers.FIELD_MAP_TARGET_DESCRIPTION)) {
            releaseFileValidators
                    .add(new SnomedSimpleMapWithDescriptionRefSetValidator(configuration, url, this));
        } else if (lastColumn.equalsIgnoreCase(SnomedRf2Headers.FIELD_OWL_EXPRESSION)) {
            releaseFileValidators.add(new SnomedOWLExpressionRefSetValidator(configuration, url, this));
        } else if (lastColumn.equalsIgnoreCase(SnomedRf2Headers.FIELD_MRCM_EDITORIAL_GUIDE_REFERENCE)) {
            releaseFileValidators.add(new SnomedMRCMDomainRefSetValidator(configuration, url, this));
        } else if (lastColumn.equalsIgnoreCase(SnomedRf2Headers.FIELD_MRCM_RULE_REFSET_ID)) {
            releaseFileValidators.add(new SnomedMRCMModuleScopeRefSetValidator(configuration, url, this));
        } else if (lastColumn.equalsIgnoreCase(SnomedRf2Headers.FIELD_MRCM_CONTENT_TYPE_ID)) {
            if (headerElements.contains(SnomedRf2Headers.FIELD_MRCM_DOMAIN_ID)) {
                releaseFileValidators
                        .add(new SnomedMRCMAttributeDomainRefSetValidator(configuration, url, this));
            } else if (headerElements.contains(SnomedRf2Headers.FIELD_MRCM_RANGE_CONSTRAINT)) {
                releaseFileValidators
                        .add(new SnomedMRCMAttributeRangeRefSetValidator(configuration, url, this));
            }
        } else {
            logger.warn("Couldn't determine reference set type for file '"
                    + configuration.getMappedName(url.getPath()) + "', not validating.");
        }
    }
}

From source file:org.glowroot.central.repo.FullQueryTextDao.java

private int getTTL() throws Exception {
    CentralStorageConfig storageConfig = configRepository.getCentralStorageConfig();
    int queryRollupExpirationHours = Iterables
            .getLast(storageConfig.queryAndServiceCallRollupExpirationHours());
    int expirationHours = Math.max(queryRollupExpirationHours, storageConfig.traceExpirationHours());
    List<RollupConfig> rollupConfigs = configRepository.getRollupConfigs();
    RollupConfig lastRollupConfig = Iterables.getLast(rollupConfigs);
    // adding largest rollup interval to account for query being retained longer by rollups
    long ttl = MILLISECONDS.toSeconds(lastRollupConfig.intervalMillis())
            // adding 2 days to account for worst case client side rate limiter + server side
            // rate limiter
            + DAYS.toSeconds(2) + HOURS.toSeconds(expirationHours);
    return Ints.saturatedCast(ttl);
}

From source file:de.cau.cs.kieler.klay.layered.p5edges.splines.NubSpline.java

/**
 * Creates a new NubSpline with the given, precalculated values.
 * There is no error checking! So if the spline shall be clamped, uniform or bezier, you have to 
 * ensure the correctness of the knot vector on your own. 
 * /*from  w  w  w  .j a v a 2s.  co  m*/
 * @param clamped {@code true}, if the NubSpline is clamped.
 * @param uniform {@code true}, if the NubSpline is uniform.
 * @param bezier {@code true}, if the NubSpline is in bezier form.
 * @param dim The dimension of the NubSpline.
 * @param knotVec The knot vector if the NubSpline.
 * @param polarVectors The control points of the NubSpline already in polar form.
 */
private NubSpline(final boolean clamped, final boolean uniform, final boolean bezier, final int dim,
        final List<Double> knotVec, final List<PolarCP> polarVectors) {
    isClamped = clamped;
    isUniform = uniform;
    isBezier = bezier;
    dimNUBS = dim;
    knotVector = knotVec;
    controlPoints = polarVectors;
    minKnot = knotVec.iterator().next();
    maxKnot = Iterables.getLast(knotVec);
}

From source file:org.jboss.hal.core.finder.Finder.java

void revealHiddenColumns(FinderColumn firstVisibleColumn) {
    // show the last hidden column
    List<FinderColumn> hiddenColumns = columns.values().stream()
            .filter(column -> !Elements.isVisible(column.element())).collect(toList());
    if (!hiddenColumns.isEmpty()) {
        Elements.setVisible(Iterables.getLast(hiddenColumns).element(), true);
    }// w ww . j ava 2s. c o m
    firstVisibleColumn.markHiddenColumns(false);
    firstVisibleColumn.selectedRow().click();
    markHiddenColumns();
}

From source file:com.google.security.zynamics.binnavi.API.disassembly.Instruction.java

/**
 * Appends a comment to the list of global instruction comments.
 * //from  w  ww .j a v  a  2 s.  c o m
 * @param commentText The comment which is appended to the list of global instruction comments.
 * 
 * @throws CouldntSaveDataException if the comment could not be saved to the database.
 * @throws CouldntLoadDataException
 */
public List<IComment> appendComment(final String commentText)
        throws CouldntSaveDataException, CouldntLoadDataException {

    List<IComment> comments = Lists.newArrayList();

    try {
        comments = m_instruction.appendGlobalComment(commentText);
    } catch (final com.google.security.zynamics.binnavi.Database.Exceptions.CouldntSaveDataException exception) {
        throw new CouldntSaveDataException(exception);
    }

    for (final IInstructionListener listener : m_listeners) {
        listener.appendedComment(this, Iterables.getLast(comments));
    }

    return comments;
}

From source file:org.agorava.core.cdi.AgoravaExtension.java

/**
 * This observer decorates the produced {@link OAuthAppSettings} by injecting its own qualifier and service name
 * and build the list of Qualifiers bearing the ServiceRelated meta annotation (configured services)
 *
 * @param pp the Process producer event//from w  w  w  .ja  v a 2 s  .co m
 */
public void processOAuthSettingsProducer(@Observes final ProcessProducer<?, OAuthAppSettings> pp) {
    final AnnotatedMember<OAuthAppSettings> annotatedMember = (AnnotatedMember<OAuthAppSettings>) pp
            .getAnnotatedMember();
    final Annotation qual = Iterables
            .getLast(AgoravaExtension.getAnnotationsWithMeta(annotatedMember, ServiceRelated.class));
    final Producer<OAuthAppSettings> oldProducer = pp.getProducer();

    if (annotatedMember.isAnnotationPresent(OAuthApplication.class)) {
        /* TODO:CODE below for future support of OAuthAppSettings creation via annotation
                
        final OAuthApplication app = annotatedMember.getAnnotation(OAuthApplication.class);
                
           Class<? extends OAuthAppSettingsBuilder> builderClass = app.builder();
           OAuthAppSettingsBuilder builderOAuthApp = null;
           try {
               builderOAuthApp = builderClass.newInstance();
           } catch (Exception e) {
               throw new AgoravaException("Unable to create Settings Builder with class " + builderClass, e);
           }
                
           final OAuthAppSettingsBuilder finalBuilderOAuthApp = builderOAuthApp; */
    }

    pp.setProducer(new OAuthAppSettingsProducerDecorator(oldProducer, qual));

    log.log(INFO, "Found settings for {0}", qual);
    servicesQualifiersConfigured.add(qual);

    //settings = builderOAuthApp.name(servicesHub.getSocialMediaName()).params(app.params()).build();
}

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

private ARGPath obtainDomainTypeHeuristicBasedPrefix(List<ARGPath> pPrefixes,
        ErrorPathPrefixPreference preference, ARGPath originalErrorPath) {
    if (!classification.isPresent()) {
        return concatPrefixes(pPrefixes);
    }//  w w w . jav a2 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));

        Set<String> useDefinitionInformation = obtainUseDefInformationOfErrorPath(currentErrorPath);

        Long score = obtainDomainTypeScoreForVariables(useDefinitionInformation);

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

    return buildPath(bestIndex, pPrefixes, originalErrorPath);
}