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:com.google.security.zynamics.binnavi.Database.PostgreSQL.Savers.PostgreSQLNodeSaver.java

/**
 * Saves the mapping between code nodes and their instructions to the database.
 *
 * @param provider The provider used to access the database.
 * @param nodes The nodes to save./*w w w  . java  2  s .co  m*/
 * @param firstNode The database index of the first node.
 * @param codeNodeIndices Index into the nodes list that identifies the code nodes.
 *
 * @throws SQLException Thrown if saving the code node instructions failed.
 */
protected static ArrayList<Pair<INaviCodeNode, INaviInstruction>> saveCodeNodeInstructions(
        final SQLProvider provider, final List<INaviViewNode> nodes, final int firstNode,
        final List<Integer> codeNodeIndices) throws SQLException {
    if (!nodes.isEmpty()) {
        final Set<INaviInstruction> unsavedInstructions = new HashSet<INaviInstruction>();

        for (final int index : codeNodeIndices) {
            final CCodeNode node = (CCodeNode) nodes.get(index);

            final Iterable<INaviInstruction> instructions = node.getInstructions();

            for (final INaviInstruction instruction : instructions) {
                if (!(instruction.isStored())) {
                    unsavedInstructions.add(instruction);
                }
            }
        }

        PostgreSQLInstructionFunctions.createInstructions(provider, unsavedInstructions);

        final String query = "INSERT INTO " + CTableNames.CODENODE_INSTRUCTIONS_TABLE
                + " (module_id, node_id, position, address, comment_id) VALUES (?, ?, ?, ?, ?)";

        final PreparedStatement preparedStatement = provider.getConnection().getConnection()
                .prepareStatement(query);

        final ArrayList<Pair<INaviCodeNode, INaviInstruction>> instructionsWithUnsavedLocalComments = new ArrayList<Pair<INaviCodeNode, INaviInstruction>>();

        try {
            for (final Integer index : codeNodeIndices) {
                final INaviCodeNode codeNode = (INaviCodeNode) nodes.get(index);
                int position = 0;
                for (final INaviInstruction instruction : codeNode.getInstructions()) {
                    final List<IComment> comments = codeNode.getComments()
                            .getLocalInstructionComment(instruction);
                    final Integer commentId = comments == null ? null
                            : comments.size() == 0 ? null : Iterables.getLast(comments).getId();

                    if ((comments != null) && (comments.size() != 0) && (commentId == null)) {
                        instructionsWithUnsavedLocalComments
                                .add(new Pair<INaviCodeNode, INaviInstruction>(codeNode, instruction));
                    }

                    final int moduleId = instruction.getModule().getConfiguration().getId();

                    preparedStatement.setInt(1, moduleId);
                    preparedStatement.setInt(2, firstNode + index);
                    preparedStatement.setInt(3, position);
                    preparedStatement.setObject(4, instruction.getAddress().toBigInteger(), Types.BIGINT);
                    if (commentId == null) {
                        preparedStatement.setNull(5, Types.INTEGER);
                    } else {
                        preparedStatement.setInt(5, commentId);
                    }

                    position++;
                    preparedStatement.addBatch();
                }
            }
            preparedStatement.executeBatch();
        } finally {
            preparedStatement.close();
        }
        return instructionsWithUnsavedLocalComments;
    }
    return null;
}

From source file:com.palantir.atlasdb.keyvalue.impl.ValidatingQueryRewritingKeyValueService.java

@Override
public void putWithTimestamps(String tableName, Multimap<Cell, Value> cellValues)
        throws KeyAlreadyExistsException {
    if (cellValues.isEmpty()) {
        return;//from  ww  w . ja  v  a2s .  c o m
    }
    Validate.isTrue(!tableName.equals(TransactionConstants.TRANSACTION_TABLE), TRANSACTION_ERROR);

    long lastTimestamp = -1;
    boolean allAtSameTimestamp = true;
    for (Value value : cellValues.values()) {
        long timestamp = value.getTimestamp();
        Validate.isTrue(timestamp != Long.MAX_VALUE);
        Validate.isTrue(timestamp >= 0);
        if (lastTimestamp != -1 && timestamp != lastTimestamp) {
            allAtSameTimestamp = false;
        }
        lastTimestamp = timestamp;
    }

    if (allAtSameTimestamp) {
        Multimap<Cell, byte[]> cellValuesWithStrippedTimestamp = Multimaps.transformValues(cellValues,
                Value.GET_VALUE);

        Map<Cell, byte[]> putMap = Maps.transformValues(cellValuesWithStrippedTimestamp.asMap(),
                new Function<Collection<byte[]>, byte[]>() {

                    @Override
                    public byte[] apply(Collection<byte[]> input) {
                        try {
                            return Iterables.getOnlyElement(input);
                        } catch (IllegalArgumentException e) {
                            log.error(
                                    "Application tried to put multiple same-cell values in at same timestamp; attempting to perform last-write-wins, but ordering is not guaranteed.");
                            return Iterables.getLast(input);
                        }
                    }

                });

        put(tableName, putMap, lastTimestamp);
        return;
    }
    delegate.putWithTimestamps(tableName, cellValues);
}

From source file:org.onebusaway.nyc.vehicle_tracking.impl.inference.VehicleStateLibrary.java

static public BlockStopTimeEntry getPotentialLayoverSpot(ScheduledBlockLocation location) {

    final int time = location.getScheduledTime();

    /**/* ww  w .  j ava2  s  .  c  o m*/
     * We could be at a layover at a stop itself
     */
    final BlockStopTimeEntry closestStop = location.getClosestStop();
    final StopTimeEntry closestStopTime = closestStop.getStopTime();

    if (closestStopTime.getAccumulatedSlackTime() > 60 && closestStopTime.getArrivalTime() <= time
            && time <= closestStopTime.getDepartureTime())
        return closestStop;

    final BlockStopTimeEntry nextStop = location.getNextStop();

    /**
     * If we're at the first or last stop of a trip in our run, then
     * we're at a potential layover spot.
     */
    final BlockStopTimeEntry tripFirstStop = Iterables.getLast(location.getActiveTrip().getStopTimes());
    final BlockStopTimeEntry tripLastStop = Iterables.getFirst(location.getActiveTrip().getStopTimes(), null);
    if (tripFirstStop.equals(closestStop) || tripLastStop.equals(closestStop))
        return closestStop;

    /**
     * If the next stop is null, it means we're at the end of the block. Do we
     * consider this a layover spot? My sources say no. But now they say yes?
     */
    if (nextStop == null)
        return closestStop;

    /**
     * Is the next stop the first stop on the block? Then we're potentially at a
     * layover before the route starts
     */
    if (nextStop.getBlockSequence() == 0)
        return nextStop;

    final BlockTripEntry nextTrip = nextStop.getTrip();
    final BlockConfigurationEntry blockConfig = nextTrip.getBlockConfiguration();
    final List<BlockStopTimeEntry> stopTimes = blockConfig.getStopTimes();

    if (tripChangesBetweenPrevAndNextStop(stopTimes, nextStop, location))
        return nextStop;

    /**
     * Due to some issues in the underlying GTFS with stop locations, buses
     * sometimes make their layover after they have just passed the layover
     * point or right before they get there
     */
    if (nextStop.getBlockSequence() > 1) {
        final BlockStopTimeEntry previousStop = blockConfig.getStopTimes().get(nextStop.getBlockSequence() - 1);
        if (tripChangesBetweenPrevAndNextStop(stopTimes, previousStop, location))
            return previousStop;
    }

    if (nextStop.getBlockSequence() + 1 < stopTimes.size()) {
        final BlockStopTimeEntry nextNextStop = stopTimes.get(nextStop.getBlockSequence() + 1);
        if (tripChangesBetweenPrevAndNextStop(stopTimes, nextNextStop, location))
            return nextNextStop;
    }

    if (nextStop.getBlockSequence() + 2 < stopTimes.size()) {
        final BlockStopTimeEntry nextNextStop = stopTimes.get(nextStop.getBlockSequence() + 2);
        if (tripChangesBetweenPrevAndNextStop(stopTimes, nextNextStop, location))
            return nextNextStop;
    }

    return null;
}

From source file:com.dangdang.config.service.web.mb.PropertyGroupManagedBean.java

/**
 * @param inputstream//w  w w  .  java2  s  .  co  m
 * @return
 * @throws IOException
 */
private List<PropertyItemVO> parseInputFile(InputStream inputstream) throws IOException {
    List<String> lines = IOUtils.readLines(inputstream, Charsets.UTF_8.name());
    List<PropertyItemVO> items = Lists.newArrayList();
    String previousLine = null;
    for (int i = 1; i < lines.size(); i++) {
        String line = lines.get(i);
        if (!line.startsWith("#")) {
            Iterable<String> parts = PROPERTY_SPLITTER.split(line);
            if (Iterables.size(parts) == 2) {
                PropertyItemVO item = new PropertyItemVO(Iterables.getFirst(parts, null),
                        Iterables.getLast(parts));
                if (previousLine != null && previousLine.startsWith("#")) {
                    item.setComment(StringUtils.trimLeadingCharacter(previousLine, '#').trim());
                }
                items.add(item);
            }
        }

        previousLine = line;
    }
    return items;
}

From source file:org.glowroot.ui.TransactionCommonService.java

List<PercentileAggregate> getPercentileAggregates(String agentRollupId, AggregateQuery query,
        boolean autoRefresh) throws Exception {
    LiveResult<PercentileAggregate> liveResult;
    long revisedTo;
    if (autoRefresh) {
        liveResult = null;/* w  w  w  .  j a v  a2s .  co m*/
        revisedTo = query.to();
    } else {
        liveResult = liveAggregateRepository.getPercentileAggregates(agentRollupId, query);
        revisedTo = liveResult == null ? query.to() : liveResult.revisedTo();
    }
    AggregateQuery revisedQuery = ImmutableAggregateQuery.builder().copyFrom(query).to(revisedTo).build();
    List<PercentileAggregate> aggregates = aggregateRepository.readPercentileAggregates(agentRollupId,
            revisedQuery);
    if (revisedQuery.rollupLevel() == 0) {
        if (liveResult != null) {
            aggregates = Lists.newArrayList(aggregates);
            aggregates.addAll(liveResult.get());
        }
        return aggregates;
    }
    long nonRolledUpFrom = revisedQuery.from();
    if (!aggregates.isEmpty()) {
        nonRolledUpFrom = Iterables.getLast(aggregates).captureTime() + 1;
    }
    List<PercentileAggregate> orderedNonRolledUpAggregates = Lists.newArrayList();
    if (nonRolledUpFrom <= revisedTo) {
        orderedNonRolledUpAggregates
                .addAll(aggregateRepository.readPercentileAggregates(agentRollupId, ImmutableAggregateQuery
                        .builder().copyFrom(revisedQuery).from(nonRolledUpFrom).rollupLevel(0).build()));
    }
    if (liveResult != null) {
        orderedNonRolledUpAggregates.addAll(liveResult.get());
    }
    aggregates = Lists.newArrayList(aggregates);
    long fixedIntervalMillis = configRepository.getRollupConfigs().get(revisedQuery.rollupLevel())
            .intervalMillis();
    aggregates.addAll(rollUpPercentileAggregates(orderedNonRolledUpAggregates,
            new RollupCaptureTimeFn(fixedIntervalMillis)));
    if (aggregates.size() >= 2) {
        long currentTime = clock.currentTimeMillis();
        PercentileAggregate nextToLastAggregate = aggregates.get(aggregates.size() - 2);
        if (currentTime - nextToLastAggregate.captureTime() < 60000) {
            aggregates.remove(aggregates.size() - 1);
        }
    }
    return aggregates;
}

From source file:org.opendaylight.vpnservice.fcapsapp.performancecounter.FlowNodeConnectorInventoryTranslatorImpl.java

private boolean compareInstanceIdentifierTail(InstanceIdentifier<?> identifier1,
        InstanceIdentifier<?> identifier2) {
    return Iterables.getLast(identifier1.getPathArguments())
            .equals(Iterables.getLast(identifier2.getPathArguments()));
}

From source file:org.glowroot.ui.SyntheticResultJsonService.java

private List<SyntheticResult> getSyntheticResults(String agentRollupId, long from, long to,
        String syntheticMonitorId, int rollupLevel) throws Exception {
    List<SyntheticResult> syntheticResults = syntheticResultRepository.readSyntheticResults(agentRollupId,
            syntheticMonitorId, from, to, rollupLevel);
    if (rollupLevel == 0) {
        return syntheticResults;
    }//from  w  ww .j  a va  2  s . co  m
    long nonRolledUpFrom = from;
    if (!syntheticResults.isEmpty()) {
        nonRolledUpFrom = Iterables.getLast(syntheticResults).captureTime() + 1;
    }
    List<SyntheticResult> orderedNonRolledUpSyntheticResults = Lists.newArrayList();
    orderedNonRolledUpSyntheticResults.addAll(syntheticResultRepository.readSyntheticResults(agentRollupId,
            syntheticMonitorId, nonRolledUpFrom, to, 0));
    syntheticResults = Lists.newArrayList(syntheticResults);
    long fixedIntervalMillis = configRepository.getRollupConfigs().get(rollupLevel).intervalMillis();
    syntheticResults.addAll(rollUpSyntheticResults(orderedNonRolledUpSyntheticResults,
            new RollupCaptureTimeFn(fixedIntervalMillis)));
    return syntheticResults;
}

From source file:org.jboss.as.console.client.v3.widgets.wizard.Wizard.java

/**
 * @return the last state(s) which is the state of the last added step by default.
 *///from w  w  w . ja v  a2 s  .  com
protected EnumSet<S> lastStates() {
    assertSteps();
    return EnumSet.of(Iterables.getLast(steps.keySet()));
}

From source file:de.fau.osr.gui.Controller.GuiController.java

public void requirementsFromDBForRequirementTab() {
    Supplier<Collection<? extends DataElement>> fetching = () -> {
        try {//w w w . ja  va2  s . c o m
            return i_Collection_Model.getRequirements(requirementIDFiltering);
        } catch (IOException e) {
            popupManager.showErrorDialog("Internal Storage Error");
            return new ArrayList<DataElement>();
        }
    };

    Requirement_Detail_ElementHandler detail_handler = elementHandler.getRequirement_Detail_ElementHandler();
    Requirement_ElementHandler tabAndReqsList_elementHandler = elementHandler
            .getRequirement_ElementHandlerRequirementTab();

    Runnable buttonAction = () -> {
        Collection<DataElement> dataElements = tabAndReqsList_elementHandler.getSelection(new Visitor_Swing());
        Presenter[] presenters = Transformer.transformDataElementsToPresenters(dataElements);

        detail_handler.setScrollPane_Content(presenters);
    };

    Transformer.process(tabAndReqsList_elementHandler, buttonAction, fetching);

    detail_handler.setListenerOnSaveClick(e1 -> {
        Collection<DataElement> selectedReqs = tabAndReqsList_elementHandler.getSelection(new Visitor_Swing());
        if (selectedReqs.size() < 1) {
            popupManager.showErrorDialog("select a requirement");
            return;
        }

        Requirement lastSelected = (Requirement) Iterables.getLast(selectedReqs);

        String id = lastSelected.getID();
        String title = detail_handler.getTitle().getText();
        String description = detail_handler.getDescription().getText();

        String resultMsg = "Saved!";
        if (!getI_Collection_Model().updateRequirement(id, title, description)) {
            resultMsg = "Failed!";
        }
        popupManager.showInformationDialog(resultMsg);
    }

    );
}

From source file:com.google.devtools.build.lib.worker.WorkerSpawnStrategy.java

@Override
public void exec(Spawn spawn, ActionExecutionContext actionExecutionContext,
        AtomicReference<Class<? extends SpawnActionContext>> writeOutputFiles)
        throws ExecException, InterruptedException {
    Executor executor = actionExecutionContext.getExecutor();
    EventHandler eventHandler = executor.getEventHandler();
    StandaloneSpawnStrategy standaloneStrategy = Preconditions
            .checkNotNull(executor.getContext(StandaloneSpawnStrategy.class));

    if (executor.reportsSubcommands()) {
        executor.reportSubcommand(//from w  w w .java2s  .  co  m
                Label.print(spawn.getOwner().getLabel()) + " [" + spawn.getResourceOwner().prettyPrint() + "]",
                spawn.asShellCommand(executor.getExecRoot()));
    }

    if (!spawn.getExecutionInfo().containsKey("supports-workers")
            || !spawn.getExecutionInfo().get("supports-workers").equals("1")) {
        eventHandler.handle(Event
                .warn(String.format(ERROR_MESSAGE_PREFIX + REASON_NO_EXECUTION_INFO, spawn.getMnemonic())));
        standaloneStrategy.exec(spawn, actionExecutionContext);
        return;
    }

    // We assume that the spawn to be executed always gets a @flagfile argument, which contains the
    // flags related to the work itself (as opposed to start-up options for the executed tool).
    // Thus, we can extract the last element from its args (which will be the @flagfile), expand it
    // and put that into the WorkRequest instead.
    if (!Iterables.getLast(spawn.getArguments()).startsWith("@")) {
        throw new UserExecException(
                String.format(ERROR_MESSAGE_PREFIX + REASON_NO_FLAGFILE, spawn.getMnemonic()));
    }

    if (Iterables.isEmpty(spawn.getToolFiles())) {
        throw new UserExecException(String.format(ERROR_MESSAGE_PREFIX + REASON_NO_TOOLS, spawn.getMnemonic()));
    }

    executor.getEventBus().post(ActionStatusMessage.runningStrategy(spawn.getResourceOwner(), "worker"));

    FileOutErr outErr = actionExecutionContext.getFileOutErr();

    ImmutableList<String> args = ImmutableList.<String>builder()
            .addAll(spawn.getArguments().subList(0, spawn.getArguments().size() - 1)).add("--persistent_worker")
            .addAll(MoreObjects.firstNonNull(extraFlags.get(spawn.getMnemonic()), ImmutableList.<String>of()))
            .build();
    ImmutableMap<String, String> env = spawn.getEnvironment();

    try {
        ActionInputFileCache inputFileCache = actionExecutionContext.getActionInputFileCache();

        HashCode workerFilesHash = WorkerFilesHash.getWorkerFilesHash(spawn.getToolFiles(),
                actionExecutionContext);
        Map<PathFragment, Path> inputFiles = new SpawnHelpers(execRoot).getMounts(spawn,
                actionExecutionContext);
        Set<PathFragment> outputFiles = SandboxHelpers.getOutputFiles(spawn);
        WorkerKey key = new WorkerKey(args, env, execRoot, spawn.getMnemonic(), workerFilesHash, inputFiles,
                outputFiles, writeOutputFiles != null);

        WorkRequest.Builder requestBuilder = WorkRequest.newBuilder();
        expandArgument(requestBuilder, Iterables.getLast(spawn.getArguments()));

        List<ActionInput> inputs = ActionInputHelper.expandArtifacts(spawn.getInputFiles(),
                actionExecutionContext.getArtifactExpander());

        for (ActionInput input : inputs) {
            byte[] digestBytes = inputFileCache.getDigest(input);
            ByteString digest;
            if (digestBytes == null) {
                digest = ByteString.EMPTY;
            } else {
                digest = ByteString.copyFromUtf8(HashCode.fromBytes(digestBytes).toString());
            }

            requestBuilder.addInputsBuilder().setPath(input.getExecPathString()).setDigest(digest).build();
        }

        WorkResponse response = execInWorker(eventHandler, key, requestBuilder.build(), maxRetries,
                writeOutputFiles);

        outErr.getErrorStream().write(response.getOutputBytes().toByteArray());

        if (response.getExitCode() != 0) {
            throw new UserExecException(
                    String.format("Worker process sent response with exit code: %d.", response.getExitCode()));
        }
    } catch (IOException e) {
        String message = CommandFailureUtils.describeCommandFailure(verboseFailures, spawn.getArguments(), env,
                execRoot.getPathString());
        throw new UserExecException(message, e);
    }
}