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:alfio.controller.api.admin.AdminReservationApiController.java

@RequestMapping(value = "/event/{eventName}/reservations/list", method = RequestMethod.GET)
public PageAndContent<List<TicketReservation>> findAll(@PathVariable("eventName") String eventName,
        @RequestParam(value = "page", required = false) Integer page,
        @RequestParam(value = "search", required = false) String search,
        @RequestParam(value = "status", required = false) List<TicketReservation.TicketReservationStatus> status,
        Principal principal) {//from   w  ww .j  a va  2 s. co m
    Event event = eventRepository.findByShortName(eventName);
    eventManager.checkOwnership(event, principal.getName(), event.getOrganizationId());
    Pair<List<TicketReservation>, Integer> res = ticketReservationManager
            .findAllReservationsInEvent(event.getId(), page, search, status);
    return new PageAndContent<>(res.getLeft(), res.getRight());
}

From source file:eu.bittrade.libs.steemj.communication.CommunicationHandler.java

/**
 * Perform a request to the web socket API whose response will automatically
 * get transformed into the given object.
 * /* www. ja va  2 s.  co m*/
 * @param requestObject
 *            A request object that contains all needed parameters.
 * @param targetClass
 *            The type the response should be transformed to.
 * @param <T>
 *            The type that should be returned.
 * @return The server response transformed into a list of given objects.
 * @throws SteemTimeoutException
 *             If the server was not able to answer the request in the given
 *             time (@see
 *             {@link eu.bittrade.libs.steemj.configuration.SteemJConfig#setResponseTimeout(int)
 *             setResponseTimeout()})
 * @throws SteemCommunicationException
 *             If there is a connection problem.
 * @throws SteemTransformationException
 *             If the SteemJ is unable to transform the JSON response into a
 *             Java object.
 * @throws SteemResponseException
 *             If the Server returned an error object.
 */
public <T> List<T> performRequest(JsonRPCRequest requestObject, Class<T> targetClass)
        throws SteemCommunicationException, SteemResponseException {
    try {
        Pair<URI, Boolean> endpoint = SteemJConfig.getInstance().getNextEndpointURI(numberOfConnectionTries++);
        JsonRPCResponse rawJsonResponse = client.invokeAndReadResponse(requestObject, endpoint.getLeft(),
                endpoint.getRight());
        LOGGER.debug("Received {} ", rawJsonResponse);

        if (rawJsonResponse.isError()) {
            throw rawJsonResponse.handleError(requestObject.getId());
        } else {
            // HANDLE NORMAL RESPONSE
            JavaType expectedResultType = mapper.getTypeFactory().constructCollectionType(List.class,
                    targetClass);
            return rawJsonResponse.handleResult(expectedResultType, requestObject.getId());
        }
    } catch (SteemCommunicationException e) {
        LOGGER.warn("The connection has been closed. Switching the endpoint and reconnecting.");
        LOGGER.debug("For the following reason: ", e);

        return performRequest(requestObject, targetClass);
    }
}

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

@SuppressWarnings("unchecked")
public void put(Pair<String, DataType> key, LookupValue value) {
    // Persist any new keys to Redis.
    Jedis jedis = pool.getResource();//from ww w  . j ava  2  s . c  o  m
    switch (key.getRight()) {
    case STRING:
        jedis.set(key.getLeft(), (String) value.getValue());
        break;
    case LIST:
        for (String element : (List<String>) value.getValue())
            jedis.lpush(key.getLeft(), element);
        break;
    case HASH:
        Map<String, String> map = (Map<String, String>) value.getValue();
        jedis.hmset(key.getLeft(), map);
        break;
    case SET:
        for (String element : (Set<String>) value.getValue())
            jedis.lpush(key.getLeft(), element);
        break;
    default:
        throw new IllegalStateException(Errors.REDIS_LOOKUP_04.getMessage());
    }
    jedis.close();
}

From source file:com.github.tddts.jet.service.impl.SearchOperationsImpl.java

@Override
@SendSearchEvents(before = SEARCHING_FOR_ROUTES, after = FINISHED)
public List<OrderSearchRow> searchForRoutes(Pair<List<ResultOrder>, Map<Integer, String>> searchPair) {
    List<ResultOrder> searchResults = searchPair.getLeft();
    Map<Integer, String> typeNames = searchPair.getRight();

    return searchResults.stream().map(searchResult -> findRoute(searchResult, searchParams.getRouteOption(),
            typeNames.get(searchResult.getTypeId()))).collect(Collectors.toList());
}

From source file:com.lyncode.jtwig.functions.repository.FunctionResolver.java

public CallableFunction get(String name, GivenParameters givenParameters)
        throws FunctionNotFoundException, ResolveException {
    if (!functions.containsKey(name))
        throw new FunctionNotFoundException("Function with name '" + name + "' not found.");
    if (!cachedFunctions.containsKey(name))
        cachedFunctions.put(name, new HashMap<Class[], Pair<FunctionReference, Boolean>>());

    if (cachedFunctions.get(name).containsKey(givenParameters.types())) {
        Pair<FunctionReference, Boolean> pair = cachedFunctions.get(name).get(givenParameters.types());
        Object[] arguments = pair.getRight()
                ? parameterResolver.resolveParameters(pair.getLeft(), givenParameters, parameterConverter)
                : parameterResolver.resolveParameters(pair.getLeft(), givenParameters, emptyConverter());
        return new CallableFunction(pair.getLeft(), arguments);
    }//from   ww w  . j a  va 2  s  .  co  m
    List<FunctionReference> functionList = functions.get(name);
    for (FunctionReference function : functionList) {
        Object[] arguments = parameterResolver.resolveParameters(function, givenParameters, emptyConverter());
        if (arguments != null) {
            cachedFunctions.get(name).put(givenParameters.types(), new ImmutablePair<>(function, false));
            return new CallableFunction(function, arguments);
        }
    }
    for (FunctionReference function : functionList) {
        Object[] arguments = parameterResolver.resolveParameters(function, givenParameters, parameterConverter);
        if (arguments != null) {
            cachedFunctions.get(name).put(givenParameters.types(), new ImmutablePair<>(function, true));
            return new CallableFunction(function, arguments);
        }
    }

    throw new FunctionNotFoundException("Function with name '" + name
            + "' and given parameters not found. Available:\n" + listAvailable(name, functions.get(name)));
}

From source file:it.polimi.diceH2020.SPACE4CloudWS.solvers.MINLPSolver.java

public Optional<Double> evaluate(@NonNull Matrix matrix, @NonNull Solution solution)
        throws MatrixHugeHoleException {
    try {/*from  w w w.j av a2 s . co m*/
        List<File> filesList = createWorkingFiles(matrix, solution);
        Pair<List<File>, List<File>> pair = new ImmutablePair<>(filesList, new ArrayList<>());
        Pair<Double, Boolean> result = run(pair, "Knapsack solution");
        File resultsFile = filesList.get(1);
        new MINLPSolFileParser().updateResults(solution, matrix, resultsFile);
        delete(filesList);
        return Optional.of(result.getLeft());
    } catch (IOException | JSchException e) {
        logger.error("Evaluate Matrix: no result due to an exception", e);
        return Optional.empty();
    }
}

From source file:com.streamsets.pipeline.stage.processor.jdbcmetadata.JdbcMetadataProcessor.java

/** {@inheritDoc} */
@Override/*from   w ww  . j a  v a 2 s . c o  m*/
protected List<ConfigIssue> init() {
    // Validate configuration values and open any required resources.
    List<ConfigIssue> issues = super.init();

    errorRecordHandler = new DefaultErrorRecordHandler(getContext());
    elEvals.init(getContext());

    Processor.Context context = getContext();

    issues.addAll(hikariConfigBean.validateConfigs(context, issues));

    if (issues.isEmpty() && null == dataSource) {
        try {
            dataSource = jdbcUtil.createDataSourceForWrite(hikariConfigBean, null, null, false, issues,
                    Collections.emptyList(), getContext());
        } catch (RuntimeException | SQLException | StageException e) {
            LOG.debug("Could not connect to data source", e);
            issues.add(getContext().createConfigIssue(Groups.JDBC.name(), CONNECTION_STRING, JdbcErrors.JDBC_00,
                    e.toString()));
        }
    }

    if (issues.isEmpty()) {
        try {
            schemaWriter = JdbcSchemaWriterFactory.create(hikariConfigBean.getConnectionString(), dataSource);
        } catch (JdbcStageCheckedException e) {
            issues.add(getContext().createConfigIssue(Groups.JDBC.name(), CONNECTION_STRING, e.getErrorCode(),
                    e.getParams()));
        }
        schemaReader = new JdbcSchemaReader(dataSource, schemaWriter);

        tableCache = CacheBuilder.newBuilder().maximumSize(50)
                .build(new CacheLoader<Pair<String, String>, LinkedHashMap<String, JdbcTypeInfo>>() {
                    @Override
                    public LinkedHashMap<String, JdbcTypeInfo> load(Pair<String, String> pair)
                            throws Exception {
                        return schemaReader.getTableSchema(pair.getLeft(), pair.getRight());
                    }
                });
    }

    // If issues is not empty, the UI will inform the user of each configuration issue in the list.
    return issues;
}

From source file:edu.sdsc.scigraph.internal.reachability.ReachabilityIndex.java

public Set<Pair<Node, Node>> getConnectedPairs(Set<Node> sources, Set<Node> targets) {
    return evaluatePairs(sources, targets, new Predicate<Pair<Node, Node>>() {
        @Override//ww w  .  j  a  v a  2  s . co  m
        public boolean apply(Pair<Node, Node> pair) {
            return canReach(pair.getLeft(), pair.getRight());
        }
    });
}

From source file:com.act.lcms.db.analysis.AnalysisHelper.java

/**
 * Process a list of wells (LCMS or Standard), producing a list of scan objects that encapsulate the plate,
 * scan file, and masses for that well./*  w w  w . jav a 2s  .com*/
 * @param db The DB from which to extract plate data.
 * @param lcmsDir The directory where the LCMS scans live.
 * @param searchMZs A list of target M/Zs to search for in the scans (see API for {@link MS1}.
 * @param kind The role of this well in this analysis (standard, positive sample, negative control).
 * @param plateCache A hash of Plates already accessed from the DB.
 * @param samples A list of wells to process.
 * @param useSNRForPeakIdentification If true, signal-to-noise ratio will be used for peak identification.  If not,
 *                                    peaks will be identified by intensity.
 * @param <T> The PlateWell type whose scans to process.
 * @return A list of ScanData objects that wraps the objects required to produce a graph for each specified well.
 * @throws Exception
 */
public static <T extends PlateWell<T>> Pair<List<ScanData<T>>, Double> processScans(DB db, File lcmsDir,
        List<Pair<String, Double>> searchMZs, ScanData.KIND kind, HashMap<Integer, Plate> plateCache,
        List<T> samples, boolean useFineGrainedMZTolerance, Set<String> includeIons, Set<String> excludeIons,
        boolean useSNRForPeakIdentification) throws Exception {
    Double maxIntensity = 0.0d;
    List<ScanData<T>> allScans = new ArrayList<>(samples.size());
    for (T well : samples) {
        // The foreign key constraint on wells ensure that plate will be non-null.
        Plate plate = plateCache.get(well.getPlateId());
        if (plate == null) {
            plate = Plate.getPlateById(db, well.getPlateId());
            plateCache.put(plate.getId(), plate);
        }

        LOGGER.info("Processing LCMS well %s %s", plate.getBarcode(), well.getCoordinatesString());

        List<ScanFile> scanFiles = ScanFile.getScanFileByPlateIDRowAndColumn(db, well.getPlateId(),
                well.getPlateRow(), well.getPlateColumn());
        if (scanFiles == null || scanFiles.size() == 0) {
            LOGGER.error("WARNING: No scan files available for %s %s", plate.getBarcode(),
                    well.getCoordinatesString());
            continue;
        }

        for (ScanFile sf : scanFiles) {
            if (sf.getFileType() != ScanFile.SCAN_FILE_TYPE.NC) {
                // TODO: Migrate sysem.err to LOGGER framework
                LOGGER.error("Skipping scan file with non-NetCDF format: %s", sf.getFilename());
                continue;
            }
            File localScanFile = new File(lcmsDir, sf.getFilename());
            if (!localScanFile.exists() && localScanFile.isFile()) {
                LOGGER.error("WARNING: could not find regular file at expected path: %s",
                        localScanFile.getAbsolutePath());
                continue;
            }

            MS1 mm = new MS1(useFineGrainedMZTolerance, useSNRForPeakIdentification);
            for (Pair<String, Double> searchMZ : searchMZs) {
                MS1.IonMode mode = MS1.IonMode.valueOf(sf.getMode().toString().toUpperCase());
                Map<String, Double> allMasses = mm.getIonMasses(searchMZ.getRight(), mode);
                Map<String, Double> metlinMasses = Utils.filterMasses(allMasses, includeIons, excludeIons);

                MS1ScanForWellAndMassCharge ms1ScanResults;

                List<ChemicalOfInterest> chemicalsOfInterest = ChemicalOfInterest.getInstance()
                        .getChemicalOfInterestByName(db, searchMZ.getLeft());

                // Check if in the input chemical is valid
                if (chemicalsOfInterest == null || chemicalsOfInterest.size() == 0) {
                    MS1 ms1 = new MS1();
                    ms1ScanResults = ms1.getMS1(metlinMasses, localScanFile.getAbsolutePath());
                } else {
                    MS1ScanForWellAndMassCharge ms1ScanResultsCache = new MS1ScanForWellAndMassCharge();
                    ms1ScanResults = ms1ScanResultsCache.getByPlateIdPlateRowPlateColUseSnrScanFileChemical(db,
                            plate, well, true, sf, searchMZ.getLeft(), metlinMasses, localScanFile);
                }

                maxIntensity = Math.max(ms1ScanResults.getMaxYAxis(), maxIntensity);

                LOGGER.info("Max intensity for target %s (%f) in %s is %f", searchMZ.getLeft(),
                        searchMZ.getRight(), sf.getFilename(), ms1ScanResults.getMaxYAxis());

                // TODO: purge the MS1 spectra from ms1ScanResults if this ends up hogging too much memory.
                allScans.add(new ScanData<T>(kind, plate, well, sf, searchMZ.getLeft(), metlinMasses,
                        ms1ScanResults));
            }
        }
    }
    return Pair.of(allScans, maxIntensity);
}

From source file:edu.sdsc.scigraph.internal.reachability.ReachabilityIndex.java

public Set<Pair<Node, Node>> getDisconnectedPairs(Set<Node> sources, Set<Node> targets) {
    return evaluatePairs(sources, targets, new Predicate<Pair<Node, Node>>() {
        @Override//from   www .  j ava  2s.  c  om
        public boolean apply(Pair<Node, Node> pair) {
            return !canReach(pair.getLeft(), pair.getRight());
        }
    });
}