Example usage for org.apache.commons.lang3.tuple ImmutablePair ImmutablePair

List of usage examples for org.apache.commons.lang3.tuple ImmutablePair ImmutablePair

Introduction

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

Prototype

public ImmutablePair(final L left, final R right) 

Source Link

Document

Create a new pair instance.

Usage

From source file:com.streamsets.pipeline.stage.it.DriftIT.java

@Test
public void testAddColumnToNonPartitionedTableExternal() throws Exception {
    HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder().table("ext_table")
            .partitions(new PartitionConfigBuilder().build()).external(true)
            .tablePathTemplate("/user/hive/external").build();

    HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build();
    List<Record> records = new LinkedList<>();

    Map<String, Field> map = new LinkedHashMap<>();
    map.put("id", Field.create(123));
    map.put("value", Field.create("testtest"));
    Record record = RecordCreator.create();
    record.set(Field.create(map));
    records.add(record);/* w ww.  java 2s  .com*/
    processRecords(processor, hiveTarget, records);

    assertQueryResult("select * from ext_table", new QueryValidator() {
        @Override
        public void validateResultSet(ResultSet rs) throws Exception {
            assertResultSetStructure(rs, new ImmutablePair("ext_table.id", Types.INTEGER),
                    new ImmutablePair("ext_table.value", Types.VARCHAR));
            Assert.assertTrue("Table ext_table doesn't contain any rows", rs.next());
            Assert.assertEquals(123, rs.getInt(1));
            Assert.assertEquals("testtest", rs.getString(2));
            Assert.assertFalse("Unexpected number of rows", rs.next());
        }
    });
}

From source file:com.codeveo.lago.bot.stomp.client.HttpLagoRequestHelper.java

public static Pair<Integer, String> signIn(final String serverUrl, final String user, final String password)
        throws Exception {
    try {//from   w  w w  .  ja va 2  s.c  o m
        Builder builder = new AsyncHttpClientConfig.Builder();
        Realm realm = new Realm.RealmBuilder().setPrincipal(user).setPassword(password)
                .setUsePreemptiveAuth(true).setScheme(AuthScheme.BASIC).build();
        builder.setRealm(realm).build();

        AsyncHttpClient client = new AsyncHttpClient(builder.build());

        String url = Utils.buildURL(serverUrl, WebServiceUserDesc.REST_AI + WebServiceUserDesc.User.ROOT
                + WebServiceUserDesc.User.AUTHENTICATE_PATH);

        Request request = new RequestBuilder().setUrl(url).setMethod(WebServiceUserDesc.Game.PUT_UNIT_METHOD)
                .addHeader("Accept", WebServiceUserDesc.User.AUTHENTICATE_PRODUCES).build();

        Response response = client.prepareRequest(request).execute().get();
        client.close();

        String cookie = null;
        Integer statusCode = response.getStatusCode();

        if (response.getStatusCode() == HttpStatus.CREATED.value()) {
            /* extract the cookie */
            cookie = response.getHeader("Set-Cookie");
        } else {
            cookie = response.getResponseBody();
        }

        Pair<Integer, String> statusWithCookieOrFaultJSON = new ImmutablePair<Integer, String>(statusCode,
                cookie);

        return statusWithCookieOrFaultJSON;
    } catch (Exception e) {
        throw new Exception("Error occured while signing in", e);
    }
}

From source file:main.java.framework.db.SonarDbClient.java

/**
 * Retrieves min and max value in a project for a metric
 * @param projectKey// w  w w.  j a  v  a 2 s.  c  om
 * @param metric
 * @return pair of the min an max values for the metric
 */
public Pair<Integer, Integer> getBoundariesForMetric(String projectKey, String metric) {
    try (Connection connection = this.dataSource.getConnection()) {
        try (PreparedStatement selectBoundaries = connection.prepareStatement(SELECT_BOUNDARIES_FOR_METRIC)) {
            selectBoundaries.setString(1, projectKey);
            selectBoundaries.setString(2, metric);
            try (ResultSet queryResult = selectBoundaries.executeQuery()) {
                if (queryResult.next()) {
                    int minValue = queryResult.getInt("min_value");
                    int maxValue = queryResult.getInt("max_value");
                    return new ImmutablePair<>(minValue, maxValue);
                }
            }
        }
    } catch (SQLException e) {
        log.warn("Can't retrieve boundaries for metric", e);
    }
    return null;
}

From source file:com.bluepowermod.part.tube.TubeLogic.java

/**
 * This method gets the end target and heading for a TubeStack. When the tubestack's target variable is null, this is an exporting item, meaning
 * the returned target will be the TileEntity the item is going to transport to. When the tubestack's target variable is not not, the item is
 * being retrieved to this inventory. The returned target is the inventory the item came/should come from.
 *
 * @param simulate//from w w  w.  j a va 2s .c o m
 *            The only difference between simulate and not simulate is the fact that the round robin handling will be updated in non-simulate.
 * @param from
 *            The direction this item came from, this direction will never be a valid heading. Is null in normal item routing, as the from
 *            direction IS a valid output.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
private Pair<ForgeDirection, TileEntity> getHeadingForItem(TubeStack stack, boolean simulate) {

    Map<TubeNode, Integer> distances = new HashMap<TubeNode, Integer>();
    Queue<TubeNode> traversingNodes = new LinkedBlockingQueue<TubeNode>();
    Queue<ForgeDirection> trackingExportDirection = new LinkedBlockingQueue<ForgeDirection>();
    Map<TubeEdge, ForgeDirection> validDestinations = new LinkedHashMap<TubeEdge, ForgeDirection>();// using a LinkedHashMap so the order doesn't
    // change, used for round robin.

    if (getNode() != null) {
        distances.put(getNode(), 0);// make this the origin.
        traversingNodes.add(getNode());
    }

    boolean firstRun = true;
    int closestDest = 0;
    while (!traversingNodes.isEmpty()) {
        TubeNode node = traversingNodes.poll();
        if (node.edges == null)
            node.init();
        ForgeDirection heading = firstRun ? null : trackingExportDirection.poll();
        for (int i = 0; i < 6; i++) {
            if (firstRun)
                heading = ForgeDirection.getOrientation(i);
            if (node.edges != null) {
                TubeEdge edge = node.edges[i];
                if (edge != null && canPassThroughMask(stack.color, edge.colorMask)) {// if this item can travel through this color mask proceed.
                    Integer distance = distances.get(edge.target);
                    if (distance == null || distances.get(node) + edge.distance < distance) {
                        distances.put(edge.target, distances.get(node) + edge.distance);
                        if (edge.target.target instanceof PneumaticTube) {
                            traversingNodes.add(edge.target);
                            trackingExportDirection.add(heading);
                        } else if (stack.getTarget(tube.getWorld()) == null
                                && edge.isValidForExportItem(stack.stack)
                                || stack.heading == null && edge.isValidForImportItem(stack)
                                || stack.heading != null
                                        && stack.getTarget(tube.getWorld()) == edge.target.target
                                        && edge.targetConnectionSide.getOpposite() == stack
                                                .getTargetEntryDir()) {
                            validDestinations.put(edge,
                                    stack.heading == null ? edge.targetConnectionSide : heading);
                        }
                    }
                }
            }
        }

        // Check the distances of the current breadth first search layer. if no points are closer than the currently valid destination(s), we're
        // done searching.
        boolean isDoneSearching = true;
        closestDest = getClosestDestination(validDestinations.keySet(), distances);
        for (TubeNode checkingNode : traversingNodes) {
            if (distances.get(checkingNode) <= closestDest) {
                isDoneSearching = false;
                break;
            }
        }
        if (isDoneSearching)
            break;
        firstRun = false;
    }

    if (validDestinations.size() == 0) {
        if (stack.getTarget(tube.getWorld()) != null && stack.heading != null && !simulate) {
            stack.setTarget(null, ForgeDirection.UNKNOWN);// if we can't reach the retrieving target anymore, reroute as normal.
            return getHeadingForItem(stack, simulate);
        } else {
            return null;
        }
    }

    List<Pair<ForgeDirection, TileEntity>> validDirections = new ArrayList<Pair<ForgeDirection, TileEntity>>();
    for (Map.Entry<TubeEdge, ForgeDirection> entry : validDestinations.entrySet()) {
        if (distances.get(entry.getKey().target) == closestDest) {
            validDirections.add(new ImmutablePair(entry.getValue(), entry.getKey().target.target));
        }
    }

    // handle round robin
    if (!simulate)
        roundRobinCounter++;
    if (roundRobinCounter >= validDirections.size())
        roundRobinCounter = 0;
    return validDirections.get(roundRobinCounter);
}

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

private Map<String, ?> getTopologyInfo(String topologyId, String asUser) {
    LOG.debug("[START] getTopologyInfo - topology id: {}, asUser: {}", topologyId, asUser);
    Stopwatch stopwatch = Stopwatch.createStarted();

    try {/*from w w w.j a v a2s  .c  o m*/
        Map<String, ?> responseMap;
        try {
            responseMap = topologyRetrieveCache.get(new ImmutablePair<>(topologyId, asUser));
        } catch (ExecutionException e) {
            if (e.getCause() != null) {
                throw new RuntimeException(e.getCause());
            } else {
                throw new RuntimeException(e);
            }

        } catch (UncheckedExecutionException e) {
            if (e.getCause() != null) {
                throw (RuntimeException) e.getCause();
            } else {
                throw new RuntimeException(e);
            }
        }

        LOG.debug("[END] getTopologyInfo - topology id: {}, elapsed: {} ms", topologyId,
                stopwatch.elapsed(TimeUnit.MILLISECONDS));

        return responseMap;
    } finally {
        stopwatch.stop();
    }
}

From source file:com.wolvereness.overmapped.OverMapped.java

@Override
public void uncaughtException(final Thread t, final Throwable e) {
    uncaught = new ImmutablePair<Thread, Throwable>(t, e);
}

From source file:com.mirth.connect.client.ui.codetemplate.CodeTemplatePanel.java

@Override
protected Component addAction(Action action, Set<String> options) {
    Component taskComponent = codeTemplateTasks.add(action);
    Component popupComponent = codeTemplatePopupMenu.add(action);

    if (options.contains(OPTION_ONLY_SINGLE_LIBRARIES)) {
        singleLibraryTaskComponents.add(new ImmutablePair<Component, Component>(taskComponent, popupComponent));
    } else if (options.contains(OPTION_ONLY_SINGLE_CODE_TEMPLATES)) {
        singleCodeTemplateTaskComponents
                .add(new ImmutablePair<Component, Component>(taskComponent, popupComponent));
    }//from ww w.ja  va 2s .com

    return taskComponent;
}

From source file:io.pravega.controller.server.SegmentHelper.java

private Pair<Byte, Integer> extractFromPolicy(ScalingPolicy policy) {
    final int desiredRate;
    final byte rateType;
    if (policy.getType().equals(ScalingPolicy.Type.FIXED_NUM_SEGMENTS)) {
        desiredRate = 0;//from  w w  w  . j a v a 2  s  .c  o m
        rateType = WireCommands.CreateSegment.NO_SCALE;
    } else {
        desiredRate = Math.toIntExact(policy.getTargetRate());
        if (policy.getType().equals(ScalingPolicy.Type.BY_RATE_IN_KBYTES_PER_SEC)) {
            rateType = WireCommands.CreateSegment.IN_KBYTES_PER_SEC;
        } else {
            rateType = WireCommands.CreateSegment.IN_EVENTS_PER_SEC;
        }
    }

    return new ImmutablePair<>(rateType, desiredRate);
}

From source file:com.streamsets.pipeline.stage.it.DriftIT.java

@Test
public void testAddPartitionToNonPartitionedTable() throws Exception {
    HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder().table("tbl_no_partition").build();

    HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build();
    List<Record> records = new LinkedList<>();

    Map<String, Field> map = new LinkedHashMap<>();
    map.put("city", Field.create("San Jose"));
    Record record = RecordCreator.create();
    record.set(Field.create(map));
    records.add(record);//from w  w w.j a v  a  2  s  . co  m

    try {
        processRecords(processor, hiveTarget, records);
        Assert.fail("Adding a partition to non-partitioned table should fail");
    } catch (StageException e) {
        Assert.assertEquals(e.getErrorCode(), Errors.HIVE_27);
    }

    assertQueryResult("select * from tbl_no_partition", new QueryValidator() {
        @Override
        public void validateResultSet(ResultSet rs) throws Exception {
            // Table structure should not be altered
            assertResultSetStructure(rs, new ImmutablePair("tbl_no_partition.city", Types.VARCHAR));
            // Alter Table query failed, so no data should be added to the table
            Assert.assertFalse("Table tbl_no_partition should not contain rows", rs.next());
        }
    });
}

From source file:com.intuit.wasabi.assignment.impl.AssignmentsImpl.java

/**
 * {@inheritDoc}// ww  w.ja v a2  s.com
 */
@Override
public Assignment putAssignment(User.ID userID, Application.Name applicationName,
        Experiment.Label experimentLabel, Context context, Bucket.Label desiredBucketLabel, boolean overwrite) {

    //check that the experiment is in a valid state
    EnumSet<Experiment.State> validStates = EnumSet.of(Experiment.State.RUNNING, Experiment.State.PAUSED);

    Experiment experiment = getExperiment(applicationName, experimentLabel);
    if (isNull(experiment)) {
        throw new ExperimentNotFoundException(experimentLabel);
    }

    Experiment.ID experimentID = experiment.getID();

    if (!validStates.contains(experiment.getState())) {
        throw new InvalidExperimentStateException(experiment.getID(), validStates, experiment.getState());
    }

    //throw exception if assignment already exists for user unless overwrite == true
    Assignment currentAssignment = assignmentsRepository.getAssignment(userID, applicationName, experimentID,
            context);
    if (!overwrite && currentAssignment != null && !currentAssignment.isBucketEmpty()) {
        throw new AssignmentExistsException(userID, applicationName, experimentLabel);
    }

    //check that the desired bucket is valid
    if (desiredBucketLabel != null) {
        BucketList buckets = getBucketList(experimentID);
        Boolean bucketFound = false;
        for (Bucket bucket : buckets.getBuckets()) {
            if (bucket.getLabel().equals(desiredBucketLabel) && !bucket.getState().equals(Bucket.State.EMPTY)) {
                bucketFound = true;
                break;
            }
        }
        if (!bucketFound) {
            throw new BucketNotFoundException(desiredBucketLabel);
        }
    }

    //create a newAssignment and persist into Cassandra
    Assignment.Builder builder = Assignment.newInstance(experimentID)
            .withExperimentLabel(getExperimentLabel(experimentID)).withApplicationName(applicationName)
            .withUserID(userID).withContext(context);
    if (desiredBucketLabel != null) {
        builder.withBucketLabel(desiredBucketLabel);
        builder.withPayload(getBucketPayload(experimentID, desiredBucketLabel.toString()));
    } else {
        //first need to delete existing assignment, since otherwise cassandra
        //will not update the assignment
        if (currentAssignment != null && currentAssignment.getBucketLabel() != null) {
            assignmentsRepository.deleteAssignment(experiment, userID, context, applicationName,
                    currentAssignment);
        }
        //then build one with no Bucket
        builder.withBucketLabel(null);
    }
    Date date = new Date();
    builder.withStatus(Assignment.Status.NEW_ASSIGNMENT)
            .withCreated(Optional.ofNullable(date).orElseGet(Date::new)).withCacheable(false);
    Assignment assignment = builder.build();

    // Ingest data to real time data ingestion systems if executors exist
    for (String name : executors.keySet()) {
        executors.get(name)
                .execute(new AssignmentEnvelopePayload(userID, context, false, true, false, null,
                        Assignment.Status.NEW_ASSIGNMENT, assignment.getBucketLabel(), null, applicationName,
                        experimentLabel, experimentID, date, null));
    }

    //Add new assignment in the database
    assignmentsRepository.assignUsersInBatch(newArrayList(new ImmutablePair<>(experiment, assignment)), date);

    //Convert new assignment object to response map and then return response map
    return assignment;
}