List of usage examples for org.apache.commons.lang3.tuple Pair getRight
public abstract R getRight();
Gets the right element from this pair.
When treated as a key-value pair, this is the value.
From source file:com.qq.tars.service.monitor.TARSPropertyMonitorService.java
private MultiKeyMap call(List<String> groupBy, List<String> conditions) throws IOException { String template = "{\"groupby\":%s,\"method\":\"query\",\"dataid\":\"tars_property\"," + "\"filter\":%s,\"indexs\":[\"value\"]}"; ObjectMapper mapper = new ObjectMapper(); String request = String.format(template, mapper.writeValueAsString(groupBy), mapper.writeValueAsString(conditions)); List<Pair<String, Integer>> addrs = adminService.getEndpoints("tars.tarsqueryproperty.NoTarsObj"); if (addrs.isEmpty()) { throw new IOException("tars.tarsqueryproperty.NoTarsObj not found"); }/*from ww w . j ava2 s. c o m*/ Pair<String, Integer> addr = addrs.get(0); log.info("tars.tarsqueryproperty.NoTarsObj, use {}:{}", addr.getLeft(), addr.getRight()); TCPClient client = new TCPClient(addr.getLeft(), addr.getRight()); List<String> response = client.sendAndReceive(request.getBytes(), 60000); log.debug("request={}", request); log.debug("reponse={}", StringUtils.join(response, "\n")); String line1 = response.get(0); if (!line1.startsWith("Ret:")) { throw new IOException(String.format("line #1, doesn't start with \"Ret:\", line=%s", line1)); } int ret = Integer.parseInt(line1.substring(line1.lastIndexOf(':') + 1)); if (ret == -1) { throw new IOException(String.format("line #1, Ret=%s", ret)); } String line6 = response.get(5); if (!line6.startsWith("linecount:")) { throw new IOException(String.format("line #6, doesn't start with \"linecount:\", line=%s", line6)); } int count = Integer.parseInt(line6.substring(line6.lastIndexOf(':') + 1)); if (count + 7 != response.size()) { throw new IOException(String.format("line #6, size not match, %s vs %s", count + 7, response.size())); } String lastLine = response.get(response.size() - 1); if (!"endline".equals(lastLine)) { throw new IOException( String.format("line #%s, doesn't equal to \"endline\", line=%s", response.size(), lastLine)); } MultiKeyMap result = new MultiKeyMap(); for (int i = 6; i < response.size() - 1; i++) { String line = StringUtils.removeEnd(response.get(i), ","); String[] tokens = line.split(","); if (tokens.length != groupBy.size() + 1) { throw new IOException(String.format("line format error, line=%s", line)); } String[] key = new String[groupBy.size()]; int j = 0; for (; j < key.length; j++) { key[j] = tokens[j]; } double[] value = new double[] { Double.parseDouble(tokens[j]) }; result.put(new MultiKey(key), value); } return result; }
From source file:io.lavagna.service.ProjectServiceTest.java
@Test public void testFindBoardsByUserActivityWithGlobalPermissions() { Pair<Project, User> prep = prepareOneActivity(); List<ProjectWithEventCounts> projects = projectService.findProjectsActivityByUser(prep.getRight().getId()); Assert.assertEquals(1, projects.size()); }
From source file:at.beris.virtualfile.FileContext.java
public Set<Protocol> enabledProtocols() { Map<Protocol, Pair<String, String>> protocolClassMap = new HashMap<>(); protocolClassMap.put(Protocol.SFTP, Pair.of("JSch", "com.jcraft.jsch.JSch")); protocolClassMap.put(Protocol.FTP, Pair.of("Apache Commons Net", "org.apache.commons.net.ftp.FTP")); Set<Protocol> enabledProtocols = new HashSet<>(); enabledProtocols.add(Protocol.FILE); for (Map.Entry<Protocol, Pair<String, String>> entry : protocolClassMap.entrySet()) { Protocol protocol = entry.getKey(); Pair<String, String> protocolLibrary = entry.getValue(); try {/* w ww . j a va 2s .com*/ if (Class.forName(protocolLibrary.getRight()) != null) enabledProtocols.add(protocol); } catch (ClassNotFoundException e) { } if (!enabledProtocols.contains(protocol)) LOGGER.info(protocolLibrary.getLeft() + " not installed. No support for protocol " + protocol); } return Collections.unmodifiableSet(enabledProtocols); }
From source file:com.hybris.datahub.outbound.adapter.TmallAdapter.java
private List<ErrorData> processItems(final TargetSystemPublication targetSystemPublication, final TargetItemMetadata targetItemMetadata) { final List<ErrorData> errors = Lists.newArrayList(); final TransactionTemplate template = new TransactionTemplate(transactionManager); Pair<Integer, Long> elementsAndLastId = new ImmutablePair<>(0, 0L); do {//from w w w .ja v a 2 s. c o m final Long lastProcessedId = elementsAndLastId.getRight(); elementsAndLastId = template.execute(status -> { final List<? extends TargetItem> items = getItems(targetItemMetadata, targetSystemPublication, makePageable(lastProcessedId)); final Pair<Integer, Long> pageElementsAndLastId; if (!CollectionUtils.isEmpty(items)) { for (final TargetItem targetItem : items) { errors.addAll(doPublish(targetItem, targetSystemPublication)); } pageElementsAndLastId = new ImmutablePair<>(items.size(), getLastProcessedId(lastProcessedId, items)); } else { pageElementsAndLastId = new ImmutablePair<>(0, 0L); } return pageElementsAndLastId; }); } while (elementsAndLastId.getRight() > 0); return errors; }
From source file:ca.on.oicr.pde.workflows.GATK3Workflow.java
private <S, T> Set<T> getRightCollection(Collection<Pair<S, T>> pairs) { Set<T> ts = new HashSet<>(); for (Pair<S, T> p : pairs) { ts.add(p.getRight()); }/*from w w w .j a v a 2 s .co m*/ return ts; }
From source file:com.devicehive.websockets.handlers.NotificationHandlers.java
@PreAuthorize("isAuthenticated() and hasPermission(null, 'GET_DEVICE_NOTIFICATION')") public WebSocketResponse processNotificationSubscribe(JsonObject request, WebSocketSession session) throws InterruptedException { HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();//from www . j a v a2 s. c o m Date timestamp = gson.fromJson(request.get(Constants.TIMESTAMP), Date.class); Set<String> devices = gson.fromJson(request.get(Constants.DEVICE_GUIDS), JsonTypes.STRING_SET_TYPE); Set<String> names = gson.fromJson(request.get(Constants.NAMES), JsonTypes.STRING_SET_TYPE); String deviceId = Optional.ofNullable(request.get(Constants.DEVICE_GUID)).map(JsonElement::getAsString) .orElse(null); logger.debug("notification/subscribe requested for devices: {}, {}. Timestamp: {}. Names {} Session: {}", devices, deviceId, timestamp, names, session.getId()); devices = prepareActualList(devices, deviceId); List<DeviceVO> actualDevices; if (devices != null) { actualDevices = deviceService.findByGuidWithPermissionsCheck(devices, principal); if (actualDevices.size() != devices.size()) { throw new HiveException(String.format(Messages.DEVICES_NOT_FOUND, devices), SC_FORBIDDEN); } } else { actualDevices = deviceService .list(null, null, null, null, null, null, null, true, null, null, principal).join(); devices = actualDevices.stream().map(DeviceVO::getGuid).collect(Collectors.toSet()); } BiConsumer<DeviceNotification, String> callback = (notification, subscriptionId) -> { JsonObject json = ServerResponsesFactory.createNotificationInsertMessage(notification, subscriptionId); sendMessage(json, session); }; Pair<String, CompletableFuture<List<DeviceNotification>>> pair = notificationService.subscribe(devices, names, timestamp, callback); pair.getRight().thenAccept(collection -> collection.forEach(notification -> { JsonObject json = ServerResponsesFactory.createNotificationInsertMessage(notification, pair.getLeft()); sendMessage(json, session); })); logger.debug("notification/subscribe done for devices: {}, {}. Timestamp: {}. Names {} Session: {}", devices, deviceId, timestamp, names, session.getId()); ((CopyOnWriteArraySet) session.getAttributes().get(SUBSCSRIPTION_SET_NAME)).add(pair.getLeft()); WebSocketResponse response = new WebSocketResponse(); response.addValue(SUBSCRIPTION_ID, pair.getLeft(), null); return response; }
From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.view.provider.KubernetesV2ManifestProvider.java
@Override public KubernetesV2Manifest getManifest(String account, String location, String name) { Pair<KubernetesKind, String> parsedName; try {//from w w w .j a v a2s .co m parsedName = KubernetesManifest.fromFullResourceName(name); } catch (Exception e) { return null; } KubernetesKind kind = parsedName.getLeft(); String key = Keys.infrastructure(kind, account, location, parsedName.getRight()); Optional<CacheData> dataOptional = cacheUtils.getSingleEntry(kind.toString(), key); if (!dataOptional.isPresent()) { return null; } CacheData data = dataOptional.get(); KubernetesResourceProperties properties = registry.get(account, kind); if (properties == null) { return null; } Function<KubernetesManifest, String> lastEventTimestamp = ( m) -> (String) m.getOrDefault("lastTimestamp", m.getOrDefault("firstTimestamp", "n/a")); List<KubernetesManifest> events = cacheUtils .getTransitiveRelationship(kind.toString(), Collections.singletonList(key), KubernetesKind.EVENT.toString()) .stream().map(KubernetesCacheDataConverter::getManifest) .sorted(Comparator.comparing(lastEventTimestamp)).collect(Collectors.toList()); KubernetesHandler handler = properties.getHandler(); KubernetesManifest manifest = KubernetesCacheDataConverter.getManifest(data); Moniker moniker = KubernetesCacheDataConverter.getMoniker(data); return new KubernetesV2Manifest().builder().account(account).location(location).manifest(manifest) .moniker(moniker).status(handler.status(manifest)).artifacts(handler.listArtifacts(manifest)) .events(events).build(); }
From source file:com.formkiq.core.service.generator.WorkflowOutputGenerator.java
/** * Generate Document from uploaded document. * * @param archive {@link ArchiveDTO}/*from w ww. j av a2 s . c o m*/ * @param filename {@link String} * @param data byte[] * @throws IOException IOException */ default void generate(final ArchiveDTO archive, final String filename, final byte[] data) throws IOException { Pair<FormJSON, List<WorkflowOutputFormField>> p = getOutputFormFields(filename, data); FormJSON form = p.getLeft(); WorkflowOutputDocument wo = createOrMergeWorkflowOutputDocument(archive, form, p.getRight()); String ext = wo.getInputDocumentType().getExtension(); if (ext.equals("pdf")) { archive.addPDF(wo.getName() + "." + ext, data); } else { archive.addObject(wo.getName() + "." + ext, data); } postGenerateCallback(archive, form); }
From source file:net.lldp.checksims.algorithm.smithwaterman.SmithWaterman.java
/** * Apply the Smith-Waterman algorithm to determine the similarity between two submissions. * * Token list types of A and B must match * * @param a First submission to apply to * @param b Second submission to apply to * @return Similarity results of comparing submissions A and B * @throws TokenTypeMismatchException Thrown on comparing submissions with mismatched token types * @throws InternalAlgorithmError Thrown on internal error *//*w ww . j av a 2 s .c o m*/ @Override public AlgorithmResults detectSimilarity(Pair<Submission, Submission> ab, PercentableTokenListDecorator a, PercentableTokenListDecorator b) throws TokenTypeMismatchException, InternalAlgorithmError { checkNotNull(a); checkNotNull(b); // Test for token type mismatch // TODO move this to the tokenizer /* if(!a.getTokenType().equals(b.getTokenType())) { throw new TokenTypeMismatchException("Token list type mismatch: submission " + a.getName() + " has type " + a.getTokenType().toString() + ", while submission " + b.getName() + " has type " + b.getTokenType().toString()); } */ // Handle a 0-token submission (no similarity) if (a.size() == 0 || b.size() == 0) { return new AlgorithmResults(ab, a, b); } else if (a.equals(b)) { PercentableTokenListDecorator aInval = new PercentableTokenListDecorator( TokenList.invalidList(b.size())); return new AlgorithmResults(ab, aInval, aInval); } // Alright, easy cases taken care of. Generate an instance to perform the actual algorithm SmithWatermanAlgorithm algorithm = new SmithWatermanAlgorithm(a.getDataCopy(), b.getDataCopy()); Pair<TokenList, TokenList> endLists = algorithm.computeSmithWatermanAlignmentExhaustive(); PercentableTokenListDecorator atb = new PercentableTokenListDecorator(endLists.getLeft()); PercentableTokenListDecorator bta = new PercentableTokenListDecorator(endLists.getRight()); double x = atb.getPercentageMatched().asDouble(); double y = bta.getPercentageMatched().asDouble(); ab.getLeft().increaseScore(y * y, y); ab.getRight().increaseScore(x * x, x); return new AlgorithmResults(ab, new PercentableTokenListDecorator(endLists.getLeft()), new PercentableTokenListDecorator(endLists.getRight())); }
From source file:edu.uci.ics.hyracks.api.rewriter.runtime.SuperActivityOperatorNodePushable.java
@Override public void setOutputFrameWriter(int clusterOutputIndex, IFrameWriter writer, RecordDescriptor recordDesc) throws HyracksDataException { /**//from w ww .j av a 2 s .c om * set the right output frame writer */ Pair<ActivityId, Integer> activityIdOutputIndex = parent.getActivityIdOutputIndex(clusterOutputIndex); IOperatorNodePushable opPushable = operatorNodePushables.get(activityIdOutputIndex.getLeft()); opPushable.setOutputFrameWriter(activityIdOutputIndex.getRight(), writer, recordDesc); }