Example usage for org.apache.commons.lang3.tuple Pair getLeft

List of usage examples for org.apache.commons.lang3.tuple Pair getLeft

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple Pair getLeft.

Prototype

public abstract L getLeft();

Source Link

Document

Gets the left element from this pair.

When treated as a key-value pair, this is the key.

Usage

From source file:com.facebook.presto.accumulo.index.ColumnCardinalityCache.java

/**
 * Gets the cardinality for each {@link AccumuloColumnConstraint}.
 * Given constraints are expected to be indexed! Who knows what would happen if they weren't!
 *
 * @param schema Schema name// w  w w.j a va2  s .com
 * @param table Table name
 * @param auths Scan authorizations
 * @param idxConstraintRangePairs Mapping of all ranges for a given constraint
 * @param earlyReturnThreshold Smallest acceptable cardinality to return early while other tasks complete
 * @param pollingDuration Duration for polling the cardinality completion service
 * @return An immutable multimap of cardinality to column constraint, sorted by cardinality from smallest to largest
 * @throws TableNotFoundException If the metrics table does not exist
 * @throws ExecutionException If another error occurs; I really don't even know anymore.
 */
public Multimap<Long, AccumuloColumnConstraint> getCardinalities(String schema, String table,
        Authorizations auths, Multimap<AccumuloColumnConstraint, Range> idxConstraintRangePairs,
        long earlyReturnThreshold, Duration pollingDuration) throws ExecutionException, TableNotFoundException {
    // Submit tasks to the executor to fetch column cardinality, adding it to the Guava cache if necessary
    CompletionService<Pair<Long, AccumuloColumnConstraint>> executor = new ExecutorCompletionService<>(
            executorService);
    idxConstraintRangePairs.asMap().forEach((key, value) -> executor.submit(() -> {
        long cardinality = getColumnCardinality(schema, table, auths, key.getFamily(), key.getQualifier(),
                value);
        LOG.debug("Cardinality for column %s is %s", key.getName(), cardinality);
        return Pair.of(cardinality, key);
    }));

    // Create a multi map sorted by cardinality
    ListMultimap<Long, AccumuloColumnConstraint> cardinalityToConstraints = MultimapBuilder.treeKeys()
            .arrayListValues().build();
    try {
        boolean earlyReturn = false;
        int numTasks = idxConstraintRangePairs.asMap().entrySet().size();
        do {
            // Sleep for the polling duration to allow concurrent tasks to run for this time
            Thread.sleep(pollingDuration.toMillis());

            // Poll each task, retrieving the result if it is done
            for (int i = 0; i < numTasks; ++i) {
                Future<Pair<Long, AccumuloColumnConstraint>> futureCardinality = executor.poll();
                if (futureCardinality != null && futureCardinality.isDone()) {
                    Pair<Long, AccumuloColumnConstraint> columnCardinality = futureCardinality.get();
                    cardinalityToConstraints.put(columnCardinality.getLeft(), columnCardinality.getRight());
                }
            }

            // If the smallest cardinality is present and below the threshold, set the earlyReturn flag
            Optional<Entry<Long, AccumuloColumnConstraint>> smallestCardinality = cardinalityToConstraints
                    .entries().stream().findFirst();
            if (smallestCardinality.isPresent()) {
                if (smallestCardinality.get().getKey() <= earlyReturnThreshold) {
                    LOG.info("Cardinality %s, is below threshold. Returning early while other tasks finish",
                            smallestCardinality);
                    earlyReturn = true;
                }
            }
        } while (!earlyReturn && cardinalityToConstraints.entries().size() < numTasks);
    } catch (ExecutionException | InterruptedException e) {
        if (e instanceof InterruptedException) {
            Thread.currentThread().interrupt();
        }
        throw new PrestoException(UNEXPECTED_ACCUMULO_ERROR, "Exception when getting cardinality", e);
    }

    // Create a copy of the cardinalities
    return ImmutableMultimap.copyOf(cardinalityToConstraints);
}

From source file:com.hortonworks.streamline.streams.metrics.storm.topology.StormTopologyMetricsImpl.java

/**
 * {@inheritDoc}//www . ja  v a 2  s.  com
 */
@Override
public void init(Map<String, Object> conf) throws ConfigException {
    String stormApiRootUrl = null;
    Subject subject = null;
    if (conf != null) {
        stormApiRootUrl = (String) conf.get(TopologyLayoutConstants.STORM_API_ROOT_URL_KEY);
        subject = (Subject) conf.get(TopologyLayoutConstants.SUBJECT_OBJECT);
    }
    Client restClient = ClientBuilder.newClient(new ClientConfig());
    this.client = new StormRestAPIClient(restClient, stormApiRootUrl, subject);
    timeSeriesMetrics = new StormTopologyTimeSeriesMetricsImpl(client);
    topologyRetrieveCache = CacheBuilder.newBuilder().maximumSize(MAX_SIZE_TOPOLOGY_CACHE)
            .expireAfterWrite(CACHE_DURATION_SECS, TimeUnit.SECONDS)
            .build(new CacheLoader<Pair<String, String>, Map<String, ?>>() {
                @Override
                public Map<String, ?> load(Pair<String, String> stormTopologyIdAndAsUser) {
                    String stormTopologyId = stormTopologyIdAndAsUser.getLeft();
                    String asUser = stormTopologyIdAndAsUser.getRight();
                    LOG.debug("retrieving topology info - topology id: {}, asUser: {}", stormTopologyId,
                            asUser);
                    return client.getTopology(stormTopologyId, asUser);
                }
            });
    componentRetrieveCache = CacheBuilder.newBuilder().maximumSize(MAX_SIZE_COMPONENT_CACHE)
            .expireAfterWrite(CACHE_DURATION_SECS, TimeUnit.SECONDS)
            .build(new CacheLoader<Pair<Pair<String, String>, String>, Map<String, ?>>() {
                @Override
                public Map<String, ?> load(Pair<Pair<String, String>, String> componentIdAndAsUserPair) {
                    String topologyId = componentIdAndAsUserPair.getLeft().getLeft();
                    String componentId = componentIdAndAsUserPair.getLeft().getRight();
                    String asUser = componentIdAndAsUserPair.getRight();
                    LOG.debug("retrieving component info - topology id: {}, component id: {}, asUser: {}",
                            topologyId, componentId, asUser);
                    return client.getComponent(topologyId, componentId, asUser);
                }
            });
}

From source file:com.teambr.bookshelf.client.gui.component.control.GuiComponentSideSelector.java

/**
 * Draws the highlights onto the block/* ww  w  . ja va2s.c  om*/
 * @param selections The colors to render
 */
private void drawHighlights(List<Pair<SidePicker.Side, Color>> selections) {
    GlStateManager.disableLighting();
    GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
    GlStateManager.enableBlend();
    GlStateManager.enableAlpha();
    GlStateManager.disableDepth();
    GlStateManager.disableTexture2D();

    GL11.glBegin(GL11.GL_QUADS);
    for (Pair<SidePicker.Side, Color> pair : selections) {
        if (pair.getRight() != null)
            RenderUtils.setColor(pair.getRight());

        switch (pair.getLeft()) {
        case XPos:
            GL11.glVertex3d(0.5, -0.5, -0.5);
            GL11.glVertex3d(0.5, 0.5, -0.5);
            GL11.glVertex3d(0.5, 0.5, 0.5);
            GL11.glVertex3d(0.5, -0.5, 0.5);
            break;
        case YPos:
            GL11.glVertex3d(-0.5, 0.5, -0.5);
            GL11.glVertex3d(-0.5, 0.5, 0.5);
            GL11.glVertex3d(0.5, 0.5, 0.5);
            GL11.glVertex3d(0.5, 0.5, -0.5);
            break;
        case ZPos:
            GL11.glVertex3d(-0.5, -0.5, 0.5);
            GL11.glVertex3d(0.5, -0.5, 0.5);
            GL11.glVertex3d(0.5, 0.5, 0.5);
            GL11.glVertex3d(-0.5, 0.5, 0.5);
            break;
        case XNeg:
            GL11.glVertex3d(-0.5, -0.5, -0.5);
            GL11.glVertex3d(-0.5, -0.5, 0.5);
            GL11.glVertex3d(-0.5, 0.5, 0.5);
            GL11.glVertex3d(-0.5, 0.5, -0.5);
            break;
        case YNeg:
            GL11.glVertex3d(-0.5, -0.5, -0.5);
            GL11.glVertex3d(0.5, -0.5, -0.5);
            GL11.glVertex3d(0.5, -0.5, 0.5);
            GL11.glVertex3d(-0.5, -0.5, 0.5);
            break;
        case ZNeg:
            GL11.glVertex3d(-0.5, -0.5, -0.5);
            GL11.glVertex3d(-0.5, 0.5, -0.5);
            GL11.glVertex3d(0.5, 0.5, -0.5);
            GL11.glVertex3d(0.5, -0.5, -0.5);
            break;
        default:
        }
    }

    GL11.glEnd();

    GlStateManager.disableBlend();
    GlStateManager.enableDepth();
    GlStateManager.enableTexture2D();
}

From source file:com.vmware.identity.openidconnect.server.LoginTest.java

@Test
public void testSessionLogin() throws Exception {
    Cookie sessionCookie = new Cookie(SESSION_COOKIE_NAME, SESSION_ID);
    Pair<ModelAndView, MockHttpServletResponse> result = doRequest(null /* loginString */, sessionCookie);
    ModelAndView modelView = result.getLeft();
    MockHttpServletResponse response = result.getRight();
    Assert.assertNull("modelView", modelView);
    validateAuthnSuccessResponse(response, Flow.AUTHZ_CODE, Scope.OPENID, false, false, STATE, NONCE);
}

From source file:de.hub.cs.dbis.lrb.operators.AverageVehicleSpeedBolt.java

@Override
public void execute(Tuple input) {
    this.inputPositionReport.clear();
    this.inputPositionReport.addAll(input.getValues());
    LOGGER.trace(this.inputPositionReport.toString());

    Integer vid = this.inputPositionReport.getVid();
    short minute = this.inputPositionReport.getMinuteNumber();
    int speed = this.inputPositionReport.getSpeed().intValue();
    this.segment.set(this.inputPositionReport);

    assert (minute >= this.currentMinute);

    if (minute > this.currentMinute) {
        // emit all values for last minute
        // (because input tuples are ordered by ts, we can close the last minute safely)
        for (Entry<Integer, Pair<AvgValue, SegmentIdentifier>> entry : this.avgSpeedsMap.entrySet()) {
            Pair<AvgValue, SegmentIdentifier> value = entry.getValue();
            SegmentIdentifier segId = value.getRight();

            // VID, Minute-Number, X-Way, Segment, Direction, Avg(speed)
            this.collector.emit(new AvgVehicleSpeedTuple(entry.getKey(), new Short(this.currentMinute),
                    segId.getXWay(), segId.getSegment(), segId.getDirection(), value.getLeft().getAverage()));
        }/*from w w  w .  j  a  va 2  s. c  o m*/

        this.avgSpeedsMap.clear();
        this.currentMinute = minute;
    }

    Pair<AvgValue, SegmentIdentifier> vehicleEntry = this.avgSpeedsMap.get(vid);
    if (vehicleEntry != null && !vehicleEntry.getRight().equals(this.segment)) {
        SegmentIdentifier segId = vehicleEntry.getRight();

        // VID, Minute-Number, X-Way, Segment, Direction, Avg(speed)
        this.collector.emit(new AvgVehicleSpeedTuple(vid, new Short(this.currentMinute), segId.getXWay(),
                segId.getSegment(), segId.getDirection(), vehicleEntry.getLeft().getAverage()));

        // set to null to get new vehicle entry below
        vehicleEntry = null;
    }

    if (vehicleEntry == null) {
        vehicleEntry = new MutablePair<AvgValue, SegmentIdentifier>(new AvgValue(speed), this.segment.copy());
        this.avgSpeedsMap.put(vid, vehicleEntry);
    } else {
        vehicleEntry.getLeft().updateAverage(speed);
    }

    this.collector.ack(input);
}

From source file:com.vmware.identity.openidconnect.server.LoginTest.java

@Test
public void testLoginStringWithSessionCookieNonMatching() throws Exception {
    // if request has both a loginString and session cookie, then if the session cookie does not match, process the loginString
    String loginString = passwordLoginString();
    Cookie nonMatchingsessionCookie = new Cookie(SESSION_COOKIE_NAME, SESSION_ID + "_nonmatching");
    Pair<ModelAndView, MockHttpServletResponse> result = doRequest(loginString, nonMatchingsessionCookie);
    ModelAndView modelView = result.getLeft();
    MockHttpServletResponse response = result.getRight();
    Assert.assertNull("modelView", modelView);
    validateAuthnSuccessResponse(response, Flow.AUTHZ_CODE, Scope.OPENID, false, true, STATE, NONCE);
}

From source file:edu.uci.ics.hyracks.api.job.JobSpecification.java

public RecordDescriptor getConnectorRecordDescriptor(IConnectorDescriptor conn) {
    Pair<Pair<IOperatorDescriptor, Integer>, Pair<IOperatorDescriptor, Integer>> connInfo = connectorOpMap
            .get(conn.getConnectorId());
    return connInfo.getLeft().getLeft().getOutputRecordDescriptors()[connInfo.getLeft().getRight()];
}

From source file:edu.uci.ics.hyracks.api.job.JobSpecification.java

public IOperatorDescriptor getProducer(IConnectorDescriptor conn) {
    Pair<Pair<IOperatorDescriptor, Integer>, Pair<IOperatorDescriptor, Integer>> connInfo = connectorOpMap
            .get(conn.getConnectorId());
    return connInfo.getLeft().getLeft();
}

From source file:edu.uci.ics.hyracks.api.job.JobSpecification.java

public int getProducerOutputIndex(IConnectorDescriptor conn) {
    Pair<Pair<IOperatorDescriptor, Integer>, Pair<IOperatorDescriptor, Integer>> connInfo = connectorOpMap
            .get(conn.getConnectorId());
    return connInfo.getLeft().getRight();
}