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:fr.ippon.wip.http.hc.TransformerResponseInterceptor.java

/**
 * If httpResponse must be transformed, creates an instance of
 * WIPTransformer, executes WIPTransformer#transform on the response content
 * and updates the response entity accordingly.
 * //from  w  w  w.j a  v a2  s .c  o  m
 * @param httpResponse
 * @param context
 * @throws HttpException
 * @throws IOException
 */
public void process(HttpResponse httpResponse, HttpContext context) throws HttpException, IOException {
    PortletRequest portletRequest = HttpClientResourceManager.getInstance().getCurrentPortletRequest();
    PortletResponse portletResponse = HttpClientResourceManager.getInstance().getCurrentPortletResponse();
    WIPConfiguration config = WIPUtil.getConfiguration(portletRequest);
    RequestBuilder request = HttpClientResourceManager.getInstance().getCurrentRequest();

    if (httpResponse == null) {
        // No response -> no transformation
        LOG.warning("No response to transform.");
        return;
    }

    HttpEntity entity = httpResponse.getEntity();
    if (entity == null) {
        // No entity -> no transformation
        return;
    }

    ContentType contentType = ContentType.getOrDefault(entity);
    String mimeType = contentType.getMimeType();

    String actualURL;
    RedirectLocations redirectLocations = (RedirectLocations) context
            .getAttribute("http.protocol.redirect-locations");
    if (redirectLocations != null)
        actualURL = Iterables.getLast(redirectLocations.getAll()).toString();
    else if (context.getAttribute(CachingHttpClient.CACHE_RESPONSE_STATUS) == CacheResponseStatus.CACHE_HIT) {
        actualURL = request.getRequestedURL();
    } else {
        HttpRequest actualRequest = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        HttpHost actualHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        actualURL = actualHost.toURI() + actualRequest.getRequestLine().getUri();
    }

    // Check if actual URI must be transformed
    if (!config.isProxyURI(actualURL))
        return;

    // a builder for creating a WIPTransformer instance
    TransformerBuilder transformerBuilder = new TransformerBuilder().setActualURL(actualURL)
            .setMimeType(mimeType).setPortletRequest(portletRequest).setPortletResponse(portletResponse)
            .setResourceType(request.getResourceType()).setXmlReaderPool(xmlReaderPool);

    // Creates an instance of Transformer depending on ResourceType and
    // MimeType
    int status = transformerBuilder.build();
    if (status == TransformerBuilder.STATUS_NO_TRANSFORMATION)
        return;

    WIPTransformer transformer = transformerBuilder.getTransformer();
    // Call WIPTransformer#transform method and update the response Entity
    // object
    try {
        String content = EntityUtils.toString(entity);
        String transformedContent = ((AbstractTransformer) transformer).transform(content);

        StringEntity transformedEntity;
        if (contentType.getCharset() != null) {
            transformedEntity = new StringEntity(transformedContent, contentType);
        } else {
            transformedEntity = new StringEntity(transformedContent);
        }
        transformedEntity.setContentType(contentType.toString());
        httpResponse.setEntity(transformedEntity);

    } catch (SAXException e) {
        LOG.log(Level.SEVERE, "Could not transform HTML", e);
        throw new IllegalArgumentException(e);
    } catch (TransformerException e) {
        LOG.log(Level.SEVERE, "Could not transform HTML", e);
        throw new IllegalArgumentException(e);
    }
}

From source file:org.apache.hadoop.hive.ql.index.SplitFilter.java

private boolean doesOverlap(List<HiveInputSplit> newSplits, Path path, long start) {
    if (newSplits.isEmpty()) {
        return false;
    }//from  www. j av a2  s  .  co  m
    HiveInputSplit lastSplit = Iterables.getLast(newSplits);
    if (lastSplit.getPath().equals(path)) {
        return lastSplit.getStart() + lastSplit.getLength() > start;
    }
    return false;
}

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

private static String getMessageOrFormat(MethodInvocationTree tree, VisitorState state) {
    if (tree.getArguments().size() > 1) {
        return "String.format("
                + state.getSourceCode().subSequence(((JCTree) tree.getArguments().get(0)).getStartPosition(),
                        state.getEndPosition(Iterables.getLast(tree.getArguments())))
                + ")";
    }//w  w  w .  j  a v  a 2s.  c o  m
    return state.getSourceForNode(getOnlyElement(tree.getArguments()));
}

From source file:org.apache.brooklyn.launcher.AbstractBrooklynLauncherRebindTestFixture.java

protected ManagementContext lastMgmt() {
    return Iterables.getLast(launchers).getServerDetails().getManagementContext();
}

From source file:org.sonar.java.ast.visitors.ComplexityVisitor.java

private void leaveMethod(MethodTree tree) {
    BlockTree block = tree.block();//from  w  w  w .  j a  v a 2s  . c  om
    if (block != null && !block.body().isEmpty()) {
        StatementTree last = Iterables.getLast(block.body());
        if (last.is(Tree.Kind.RETURN_STATEMENT)) {
            // minus one because we are going to count the return with +1
            blame.remove(last.firstToken());
        }
    }
}

From source file:org.pentaho.di.trans.dataservice.www.TransDataServlet.java

public void handleRequest(CarteRequest request) throws IOException {
    String sqlQuery = !Strings.isNullOrEmpty(request.getParameter(SQL)) ? request.getParameter(SQL)
            : request.getHeader(SQL);/*w  w w.  ja va2s.  c o  m*/
    if (Strings.isNullOrEmpty(sqlQuery)) {

        String sqlParamMissing = "SQL not specified";
        logError(sqlParamMissing);
        request.respond(400).withMessage(sqlParamMissing);
        return;
    }
    String maxRowsValue = !Strings.isNullOrEmpty(request.getParameter(MAX_ROWS))
            ? request.getParameter(MAX_ROWS)
            : request.getHeader(MAX_ROWS);
    final int maxRows = Const.toInt(maxRowsValue, -1);

    final String debugTransFile = request.getParameter("debugtrans");

    Map<String, String> parameters = collectParameters(request.getParameters());
    try {
        final Query query = client.prepareQuery(sqlQuery, maxRows, parameters);

        // For logging and tracking purposes, let's expose both the service transformation as well
        // as the generated transformation on this very carte instance
        List<Trans> transList = query.getTransList();
        for (Trans trans : transList) {
            monitorTransformation(trans);
        }

        if (!Strings.isNullOrEmpty(debugTransFile) && !transList.isEmpty()) {
            saveGeneratedTransformation(Iterables.getLast(transList).getTransMeta(), debugTransFile);
        }

        request.respond(200).with("binary/jdbc", new OutputStreamResponse() {
            @Override
            public void write(OutputStream outputStream) throws IOException {
                query.writeTo(outputStream);
            }
        });

    } catch (Exception e) {
        logError("Error executing SQL query: " + sqlQuery, e);
        request.respond(400).withMessage(Strings.nullToEmpty(e.getMessage()).trim());
    }
}

From source file:clocker.docker.location.strategy.basic.GroupPlacementStrategy.java

@Override
public List<DockerHostLocation> filterLocations(List<DockerHostLocation> locations, Entity entity) {
    if (locations == null || locations.isEmpty()) {
        return ImmutableList.of();
    }/*from w  w w.  ja  v  a2  s  . c o m*/
    if (getDockerInfrastructure() == null)
        config().set(DOCKER_INFRASTRUCTURE, Iterables.getLast(locations).getDockerInfrastructure());
    List<DockerHostLocation> available = MutableList.copyOf(locations);
    boolean requireExclusive = config().get(REQUIRE_EXCLUSIVE);

    try {
        acquireMutex(entity.getApplicationId(), "Filtering locations for " + entity);
    } catch (InterruptedException ie) {
        Exceptions.propagate(ie); // Should never happen...
    }

    // Find hosts with entities from our application deployed there
    Iterable<DockerHostLocation> sameApplication = Iterables.filter(available,
            hasApplicationId(entity.getApplicationId()));

    // Check if hosts have any deployed entities that share a parent with the input entity
    Optional<DockerHostLocation> sameParent = Iterables.tryFind(sameApplication,
            childrenOf(entity.getParent()));
    if (sameParent.isPresent()) {
        LOG.debug("Returning {} (same parent) for {} placement", sameParent.get(), entity);
        return ImmutableList.copyOf(sameParent.asSet());
    }

    // Remove hosts if they have any entities from our application deployed there
    Iterables.removeIf(available, hasApplicationId(entity.getApplicationId()));
    if (requireExclusive) {
        Iterables.removeIf(available, nonEmpty());
    }
    LOG.debug("Returning {} for {} placement", Iterables.toString(available), entity);
    return available;
}

From source file:org.apache.calcite.rel.type.RelDataTypeImpl.java

public RelDataTypeField getField(String fieldName, boolean caseSensitive, boolean elideRecord) {
    for (RelDataTypeField field : fieldList) {
        if (Util.matches(caseSensitive, field.getName(), fieldName)) {
            return field;
        }/*from   w  ww.  jav a  2s .com*/
    }
    if (elideRecord) {
        final List<Slot> slots = Lists.newArrayList();
        getFieldRecurse(slots, this, 0, fieldName, caseSensitive);
        loop: for (Slot slot : slots) {
            switch (slot.count) {
            case 0:
                break; // no match at this depth; try deeper
            case 1:
                return slot.field;
            default:
                break loop; // duplicate fields at this depth; abandon search
            }
        }
    }
    // Extra field
    if (fieldList.size() > 0) {
        final RelDataTypeField lastField = Iterables.getLast(fieldList);
        if (lastField.getName().equals("_extra")) {
            return new RelDataTypeFieldImpl(fieldName, -1, lastField.getType());
        }
    }

    // a dynamic * field will match any field name.
    for (RelDataTypeField field : fieldList) {
        if (field.isDynamicStar()) {
            // the requested field could be in the unresolved star
            return field;
        }
    }

    return null;
}

From source file:org.sosy_lab.cpachecker.util.refinement.PathExtractor.java

/**
 * This method returns an unsorted, non-empty collection of target states
 * found during the analysis./*from   www  .  j a v a  2 s .  c om*/
 *
 * @param pReached the set of reached states
 * @return the target states
 * @throws org.sosy_lab.cpachecker.exceptions.RefinementFailedException
 */
public Collection<ARGState> getTargetStates(final ARGReachedSet pReached) throws RefinementFailedException {

    // extract target locations from and exclude those found to be feasible before,
    // e.g., when analysis.stopAfterError is set to false
    List<ARGState> targets = extractTargetStatesFromArg(pReached)
            .filter(Predicates.not(Predicates.in(feasibleTargets))).toList();

    // set of targets may only be empty, if all of them were found feasible previously
    if (targets.isEmpty()) {
        assert feasibleTargets.containsAll(extractTargetStatesFromArg(pReached).toSet());

        throw new RefinementFailedException(Reason.RepeatedCounterexample,
                ARGUtils.getOnePathTo(Iterables.getLast(feasibleTargets)));
    }

    logger.log(Level.FINEST, "number of targets found: " + targets.size());

    targetCounter = targetCounter + targets.size();

    return targets;
}

From source file:org.opendaylight.sfc.scfofrenderer.utils.SfcNshHeader.java

public static SfcNshHeader getSfcNshHeader(RenderedServicePath theRsp) {

    RenderedServicePathHop theFirstHop = theRsp.getRenderedServicePathHop().get(0);
    RenderedServicePathHop lastRspHop = Iterables.getLast(theRsp.getRenderedServicePathHop());

    if (lastRspHop == null) {
        LOG.error("getSfcNshHeader: last rsp hop is null\n");
        return null;
    }/*from  w w  w  . j ava 2s. c  om*/

    RenderedServicePathFirstHop rspFirstHop = SfcProviderRenderedPathAPI
            .readRenderedServicePathFirstHop(theRsp.getName());
    if (rspFirstHop == null) {
        LOG.error("getSfcNshHeader: rsp first hop is null\n");
        return null;
    }

    SfcNshHeader sfcNshHeader = new SfcNshHeader().setRsp(theRsp).setNshNsp(theRsp.getPathId())
            .setNshStartNsi(theRsp.getStartingIndex())
            .setNshEndNsi((short) (lastRspHop.getServiceIndex().intValue() - 1))
            .setSffName(lastRspHop.getServiceFunctionForwarder())
            .setFirstSfName(theFirstHop.getServiceFunctionName());

    if (rspFirstHop.getIp() != null) {
        sfcNshHeader.setVxlanIpDst(rspFirstHop.getIp().getIpv4Address()).setVxlanUdpPort(rspFirstHop.getPort());
    }

    String context = theRsp.getContextMetadata();
    if (context == null) {
        LOG.error("getSfcNshHeader: context is null\n");
    }

    ContextMetadata md = SfcProviderServiceFunctionMetadataAPI.readContextMetadata(context);
    if (md == null) {
        LOG.error("getSfcNshHeader: metadata is null\n");
    } else {
        sfcNshHeader.setNshMetaC1(md.getContextHeader1()).setNshMetaC2(md.getContextHeader2())
                .setNshMetaC3(md.getContextHeader3()).setNshMetaC4(md.getContextHeader4());
    }

    return sfcNshHeader;
}