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

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

Introduction

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

Prototype

public static <L, R> Pair<L, R> of(final L left, final R right) 

Source Link

Document

Obtains an immutable pair of from two objects inferring the generic types.

This factory allows the pair to be created using inference to obtain the generic types.

Usage

From source file:com.streamsets.pipeline.lib.parser.excel.TestWorkbookParser.java

@Test
public void testParseCorrectlyEmptyLeadingRowsAndColumns()
        throws IOException, InvalidFormatException, DataParserException {
    Workbook workbook = createWorkbook("/excel/TestExcelEmptyRowsCols.xlsx");

    WorkbookParser parser = new WorkbookParser(settingsWithHeader, getContext(), workbook, "Sheet1::0");

    // column header prefix, row value multiplier
    List<Pair<String, Integer>> sheetParameters = Arrays.asList(Pair.of("column", 1), Pair.of("header", 10));

    for (int sheet = 1; sheet <= sheetParameters.size(); sheet++) {
        for (int row = 1; row <= 2; row++) {
            Record parsedRow = parser.parse();
            LinkedHashMap<String, Field> contentMap = new LinkedHashMap<>();
            String columnPrefix = sheetParameters.get(sheet - 1).getLeft();
            Integer valueMultiplier = sheetParameters.get(sheet - 1).getRight();
            for (int column = 1; column <= 3 + sheet; column++) {
                contentMap.put(columnPrefix + column,
                        Field.create(BigDecimal.valueOf(column * valueMultiplier)));
            }//from  w  w w. ja  v  a 2 s .  com
            Field expectedRow = Field.createListMap(contentMap);
            assertEquals(String.format("Parsed value for sheet %1d, row %2d did not match expected value",
                    sheet, row), expectedRow, parsedRow.get());
        }
    }
}

From source file:com.streamsets.pipeline.stage.processor.kv.redis.RedisLookupIT.java

@Test
@SuppressWarnings("unchecked")
public void testGetSingleKey() throws Exception {
    final String expected = "value1";
    RedisLookupConfig conf = new RedisLookupConfig();
    conf.cache.enabled = false;/*from w ww .j  a v a2 s  . c  o  m*/
    conf.uri = "redis://" + redis.getContainerIpAddress() + ":" + redis.getMappedPort(REDIS_PORT);
    RedisStore redisStore = new RedisStore(conf);
    LookupValue value = redisStore.get(Pair.of("key1", DataType.STRING));
    redisStore.close();
    assertTrue(Optional.fromNullable((String) value.getValue()).isPresent());
    assertEquals(expected, Optional.fromNullable((String) value.getValue()).get());
}

From source file:io.atomix.core.list.DistributedListTest.java

/**
 * Tests a map with complex types.//  w w w. j  a  v  a2  s .  c o  m
 */
@Test
public void testRequiredComplexTypes() throws Throwable {
    DistributedList<Pair<String, Integer>> list = atomix()
            .<Pair<String, Integer>>listBuilder("testRequiredComplexTypes").withRegistrationRequired()
            .withElementType(ImmutablePair.class).withProtocol(protocol()).build();

    list.add(Pair.of("foo", 1));
    assertEquals("foo", list.iterator().next().getLeft());
    assertEquals(Integer.valueOf(1), list.iterator().next().getRight());
}

From source file:it.polimi.diceH2020.SPACE4CloudWS.solvers.solversImpl.GLPKSolver.GLPKSolver.java

protected Pair<Double, Boolean> run(@NotNull Pair<List<File>, List<File>> pFiles, String remoteName)
        throws JSchException, IOException {
    List<File> exchangedFiles = pFiles.getLeft();
    boolean stillNotOk = true;
    for (int iteration = 0; stillNotOk && iteration < MAX_ITERATIONS; ++iteration) {
        File dataFile = exchangedFiles.get(0);
        String fullRemotePath = connSettings.getRemoteWorkDir();
        connector.sendFile(dataFile.getAbsolutePath(), fullRemotePath + "/data", getClass());
        logger.info(remoteName + "-> GLPK .data file sent");

        String remoteRelativeDataPath = "data/" + dataFile.getName();
        String remoteRelativeSolutionPath = ".." + RESULTS_SOLFILE;
        Matcher matcher = Pattern.compile("([\\w.-]*)(?:-\\d*)\\.dat").matcher(dataFile.getName());
        if (!matcher.matches()) {
            throw new RuntimeException(String.format("problem matching %s", dataFile.getName()));
        }/* ww  w  .  j  a  v  a 2  s.  com*/
        logger.debug(remoteName + "-> Cleaning result directory");
        clearResultDir();

        logger.info(remoteName + "-> Processing execution...");
        String command = String.format("cd %s && %s %s", connSettings.getRemoteWorkDir(),
                ((GLPKSettings) connSettings).getExecutable(),
                "--math models/model_glpk.mod -d " + remoteRelativeDataPath);
        List<String> remoteMsg = connector.exec(command, getClass());
        if (remoteMsg.contains("exit-status: 0")) {
            stillNotOk = false;
            logger.info(remoteName + "-> The remote optimization process completed correctly");
        } else {
            logger.info("Remote exit status: " + remoteMsg);
            if (remoteMsg.get(0).contains("error processing param")) {
                iteration = MAX_ITERATIONS;
                logger.info(remoteName + "-> Wrong parameters. Aborting");
            } else {
                logger.info(remoteName + "-> Restarted. Iteration " + iteration);
            }
        }
    }

    if (stillNotOk) {
        logger.info(remoteName + "-> Error in remote optimization");
        throw new IOException("Error in the initial solution creation process");
    } else {
        File solutionFile = exchangedFiles.get(1);
        String fullRemotePath = connSettings.getRemoteWorkDir() + RESULTS_SOLFILE;
        connector.receiveFile(solutionFile.getAbsolutePath(), fullRemotePath, getClass());
        Double objFunctionValue = analyzeSolution(solutionFile, ((GLPKSettings) connSettings).isVerbose());
        logger.info(remoteName + "-> The value of the objective function is: " + objFunctionValue);
        // TODO: this always returns false, should check if every error just throws
        return Pair.of(objFunctionValue, false);
    }
}

From source file:com.twitter.graphjet.bipartite.edgepool.RegularDegreeEdgePoolTest.java

@Test
public void testConcurrentReadWrites() {
    int maxNumNodes = 4;
    int maxDegree = 3;
    RegularDegreeEdgePool regularDegreeEdgePool = new RegularDegreeEdgePool(maxNumNodes, maxDegree,
            new NullStatsReceiver());

    @SuppressWarnings("unchecked")
    List<Pair<Integer, Integer>> edgesToAdd = Lists.newArrayList(Pair.of(1, 11), Pair.of(1, 12), Pair.of(4, 41),
            Pair.of(2, 21), Pair.of(4, 42), Pair.of(3, 31), Pair.of(2, 22), Pair.of(1, 13), Pair.of(4, 43),
            Pair.of(5, 51) // violates the max num nodes assumption
    );/*  ww  w  .java  2  s.co m*/

    // Sets up a concurrent read-write situation with the given pool and edges
    List<EdgePoolReader> readers = runConcurrentReadWriteThreads(regularDegreeEdgePool, edgesToAdd);

    // First check that the graph populated correctly
    testAndResetPool(regularDegreeEdgePool, true, 0.00762939453125);

    // Now test all the readers
    assertEquals(1, readers.get(0).getQueryNodeDegree());
    assertEquals(new IntArrayList(new int[] { 11 }), readers.get(0).getQueryNodeEdges());
    assertEquals(2, readers.get(1).getQueryNodeDegree());
    assertEquals(new IntArrayList(new int[] { 11, 12 }), readers.get(1).getQueryNodeEdges());
    assertEquals(1, readers.get(2).getQueryNodeDegree());
    assertEquals(new IntArrayList(new int[] { 41 }), readers.get(2).getQueryNodeEdges());
    assertEquals(1, readers.get(3).getQueryNodeDegree());
    assertEquals(new IntArrayList(new int[] { 21 }), readers.get(3).getQueryNodeEdges());
    assertEquals(2, readers.get(4).getQueryNodeDegree());
    assertEquals(new IntArrayList(new int[] { 41, 42 }), readers.get(4).getQueryNodeEdges());
    assertEquals(1, readers.get(5).getQueryNodeDegree());
    assertEquals(new IntArrayList(new int[] { 31 }), readers.get(5).getQueryNodeEdges());
    assertEquals(2, readers.get(6).getQueryNodeDegree());
    assertEquals(new IntArrayList(new int[] { 21, 22 }), readers.get(6).getQueryNodeEdges());
    assertEquals(3, readers.get(7).getQueryNodeDegree());
    assertEquals(new IntArrayList(new int[] { 11, 12, 13 }), readers.get(7).getQueryNodeEdges());
    assertEquals(3, readers.get(8).getQueryNodeDegree());
    assertEquals(new IntArrayList(new int[] { 41, 42, 43 }), readers.get(8).getQueryNodeEdges());
    assertEquals(1, readers.get(9).getQueryNodeDegree());
    assertEquals(new IntArrayList(new int[] { 51 }), readers.get(9).getQueryNodeEdges());
}

From source file:com.samsung.sjs.theorysolver.TheorySolver.java

/**
 * Given a fixing set finder, a solver for some particular theory, and some constraints,
 * this procedure either finds a model or it finds a minimum set of constraints
 * which, if broken, make the system satisfiable (a "fixing set").
 *
 * <p>A <em>theory</em> is a solver that solves simple conjunctions of constraints.
 * The performance of this algorithm highly depends on the ability of the theory to
 * produce small unsatisfiable cores.//from w w  w.  j  a va  2s.  c o m
 *
 * @param <Constraint>    the type of constraint solved by the theory
 * @param <Model>         the type of model produced by the theory
 * @param theorySolver    a solver for some theory
 * @param fixingSetFinder a strategy for finding a fixing set
 * @param hardConstraints the hard constraints which MUST be satisfied
 * @param softConstraints the labeled soft constraints from which the fixing set is drawn
 * @return A pair (m,l) where l is the fixing set (a minimum set of constraints which had
 *   to be weakened to satisfy the system), and m is the resulting model after weakening.
 *   Note that <code>l.isEmpty()</code> means the entire set of constraints is satisfiable.
 * @see SatSolver
 * @see Theory
 */
public static <Constraint, Model> Pair<Model, Collection<Constraint>> solve(
        Theory<Constraint, Model> theorySolver, FixingSetFinder<Constraint> fixingSetFinder,
        List<Constraint> hardConstraints, List<Constraint> softConstraints) {

    FixingSetListener<Constraint, Model> listener = NOISY ? loggingListener()
            : FixingSetListener.dummyListener();

    fixingSetFinder.setup(softConstraints);

    // These two are complements of each other:
    //    - fixingSet is the constraints we are going to remove
    //    - positive  is the constraints we are going to keep
    //      (i.e. all those not in the fixing set)
    Collection<Constraint> fixingSet = new ArrayList<>();
    Collection<Constraint> positive = new LinkedHashSet<>();
    for (;;) {

        // Be polite---interruptions mean that someone else wants
        // this thread to stop what it's doing.
        if (Thread.currentThread().isInterrupted()) {
            throw new RuntimeException("thread was interrupted");
        }

        positive.addAll(hardConstraints);
        positive.addAll(softConstraints);
        positive.removeAll(fixingSet);

        // Check the proposed fixing set against the theory.
        Either<Model, Collection<Constraint>> result = timed(() -> theorySolver.check(positive),
                "CHECKING THEORY");

        if (result.right == null) {
            // The proposed fixing set works! We are done!
            if (NOISY)
                System.out.println("VALID MODEL");
            listener.onFixingSet(result.left, fixingSet);
            return Pair.of(result.left, fixingSet);
        } else {
            // The proposed fixing set didn't work. We will use the core
            // to adjust what fixing set gets returned next.

            // Inform the listener
            listener.onCore(result.right);

            // The fixing set finder shouldn't care about hard constraints
            Collection<Constraint> softCore = result.right.stream().filter(c -> !hardConstraints.contains(c))
                    .collect(Collectors.toList());

            if (softCore.isEmpty()) {
                throw new IllegalStateException("Hard clauses are unsat!");
            }

            // Push the core to the fixing set finder
            fixingSet.clear();
            fixingSetFinder.addCore(softCore);
            timed(() -> fixingSetFinder.currentFixingSet(fixingSet, listener), "FINDING FIXING SET");
            System.out.println("  --> PROPOSAL SIZE = " + fixingSet.size());
        }

    }

}

From source file:de.l3s.boilerpipe.sax.BoilerpipeHTMLContentHandler.java

public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
    labelStacks.add(null);//ww w .j  a  v  a2  s . c  o  m

    TagAction ta = tagActions.get(localName);
    if (ta != null) {
        if (ta.changesTagLevel()) {
            tagLevel++;
        }
        flush = ta.start(this, localName, qName, atts) | flush;
    } else {
        tagLevel++;
        flush = true;
    }

    lastEvent = Event.START_TAG;
    lastStartTag = localName;

    if (currentTag != null) {

        tagStack.push(currentTag);
    }
    currentTag = Pair.of(qName, this.convertAttributes(atts));
}

From source file:com.act.lcms.MzMLParser.java

protected static <K, V> List<Pair<K, V>> zipLists(List<K> keys, List<V> vals) {
    if (keys.size() != vals.size()) {
        throw new RuntimeException(String.format("Mismatched list sizes: %d vs %d", keys.size(), vals.size()));
    }/* w w  w  .  j av  a2 s.com*/
    List<Pair<K, V>> res = new ArrayList<>(keys.size());
    Iterator<K> ki = keys.listIterator();
    Iterator<V> vi = vals.listIterator();
    while (ki.hasNext() && vi.hasNext()) { // Length check should ensure these are exhausted simultaneously.
        K k = ki.next();
        V v = vi.next();
        res.add(Pair.of(k, v));
    }
    return res;
}

From source file:com.uber.hoodie.common.util.CompactionUtils.java

/**
 * Get all file-ids with pending Compaction operations and their target compaction instant time
 *
 * @param metaClient Hoodie Table Meta Client
 *//*from  w w  w .  j a va 2s.co  m*/
public static Map<String, Pair<String, HoodieCompactionOperation>> getAllPendingCompactionOperations(
        HoodieTableMetaClient metaClient) {
    List<Pair<HoodieInstant, HoodieCompactionPlan>> pendingCompactionPlanWithInstants = getAllPendingCompactionPlans(
            metaClient);

    Map<String, Pair<String, HoodieCompactionOperation>> fileIdToPendingCompactionWithInstantMap = new HashMap<>();
    pendingCompactionPlanWithInstants.stream().flatMap(instantPlanPair -> {
        HoodieInstant instant = instantPlanPair.getKey();
        HoodieCompactionPlan compactionPlan = instantPlanPair.getValue();
        List<HoodieCompactionOperation> ops = compactionPlan.getOperations();
        if (null != ops) {
            return ops.stream().map(op -> {
                return Pair.of(op.getFileId(), Pair.of(instant.getTimestamp(), op));
            });
        } else {
            return Stream.empty();
        }
    }).forEach(pair -> {
        // Defensive check to ensure a single-fileId does not have more than one pending compaction
        if (fileIdToPendingCompactionWithInstantMap.containsKey(pair.getKey())) {
            String msg = "Hoodie File Id (" + pair.getKey()
                    + ") has more thant 1 pending compactions. Instants: " + pair.getValue() + ", "
                    + fileIdToPendingCompactionWithInstantMap.get(pair.getKey());
            throw new IllegalStateException(msg);
        }
        fileIdToPendingCompactionWithInstantMap.put(pair.getKey(), pair.getValue());
    });
    return fileIdToPendingCompactionWithInstantMap;
}

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

public Pair<ModelAndView, HttpResponse> process() {
    // parse authn request (and if that fails, see if you can still construct an error response off of the partially parsed request)
    ClientID clientId;//from   www.  ja va 2 s .co m
    URI redirectUri;
    AuthenticationErrorResponse parseErrorResponse;
    try {
        this.authnRequest = AuthenticationRequest.parse(this.httpRequest);
        clientId = this.authnRequest.getClientID();
        redirectUri = this.authnRequest.getRedirectURI();
        parseErrorResponse = null;
    } catch (AuthenticationRequest.ParseException e) {
        if (e.getClientID() != null && e.getRedirectURI() != null
                && e.createAuthenticationErrorResponse(this.isAjaxRequest) != null) {
            clientId = e.getClientID();
            redirectUri = e.getRedirectURI();
            parseErrorResponse = e.createAuthenticationErrorResponse(this.isAjaxRequest);
        } else {
            LoggerUtils.logFailedRequest(logger, e.getErrorObject(), e);
            return Pair.of((ModelAndView) null, HttpResponse.createErrorResponse(e.getErrorObject()));
        }
    }

    // check that tenant, client, and redirect_uri are registered (if not, return error to browser, not client)
    try {
        if (this.tenant == null) {
            this.tenant = this.tenantInfoRetriever.getDefaultTenantName();
        }
        this.tenantInfo = this.tenantInfoRetriever.retrieveTenantInfo(this.tenant);
        this.clientInfo = this.clientInfoRetriever.retrieveClientInfo(this.tenant, clientId);
        if (!this.clientInfo.getRedirectURIs().contains(redirectUri)) {
            throw new ServerException(ErrorObject.invalidRequest("unregistered redirect_uri"));
        }
    } catch (ServerException e) {
        LoggerUtils.logFailedRequest(logger, e);
        return Pair.of((ModelAndView) null, HttpResponse.createErrorResponse(e.getErrorObject()));
    }

    // if tenant, client, and redirect_uri are registered, we can return authn error response to the client instead of browser
    if (parseErrorResponse != null) {
        LoggerUtils.logFailedRequest(logger, parseErrorResponse.getErrorObject());
        return Pair.of((ModelAndView) null, parseErrorResponse.toHttpResponse());
    }

    // authenticate client
    try {
        authenticateClient();
    } catch (ServerException e) {
        LoggerUtils.logFailedRequest(logger, e);
        return Pair.of((ModelAndView) null, authnErrorResponse(e).toHttpResponse());
    }

    // process login information (username/password or session), if failed, return error message to browser so javascript can consume it
    LoginProcessor p = new LoginProcessor(this.personUserAuthenticator, this.sessionManager, this.messageSource,
            this.locale, this.httpRequest, this.tenant);
    Triple<PersonUser, SessionID, LoginMethod> loginResult;
    try {
        loginResult = p.process();
    } catch (LoginProcessor.LoginException e) {
        LoggerUtils.logFailedRequest(logger, e.getErrorObject(), e);
        return Pair.of((ModelAndView) null, e.toHttpResponse());
    }
    PersonUser personUser = loginResult.getLeft();
    SessionID sessionId = loginResult.getMiddle();
    LoginMethod loginMethod = loginResult.getRight();

    // if no person user, return login form
    if (personUser == null) {
        try {
            return Pair.of(generateLoginForm(), (HttpResponse) null);
        } catch (ServerException e) {
            LoggerUtils.logFailedRequest(logger, e);
            return Pair.of((ModelAndView) null, authnErrorResponse(e).toHttpResponse());
        }
    }

    // we have a person user, process authn request for this person user
    try {
        AuthenticationSuccessResponse authnSuccessResponse = (this.authnRequest.getResponseType()
                .contains(ResponseTypeValue.AUTHORIZATION_CODE))
                        ? processAuthzCodeResponse(personUser, sessionId)
                        : processIDTokenResponse(personUser, sessionId);
        if (loginMethod == null) {
            this.sessionManager.update(sessionId, this.clientInfo);
        } else {
            this.sessionManager.add(sessionId, personUser, loginMethod, this.clientInfo);
        }
        HttpResponse httpResponse = authnSuccessResponse.toHttpResponse();
        httpResponse.addCookie(loggedInSessionCookie(sessionId));
        return Pair.of((ModelAndView) null, httpResponse);
    } catch (ServerException e) {
        LoggerUtils.logFailedRequest(logger, e);
        return Pair.of((ModelAndView) null, authnErrorResponse(e).toHttpResponse());
    }
}