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.cheusov.Jrep.java

private static String getLineToPrint(String line, List<Pair<Integer, Integer>> startend) {
    StringBuilder sb = new StringBuilder();
    Collections.sort(startend, new Comparator<Pair<Integer, Integer>>() {
        public int compare(Pair<Integer, Integer> a, Pair<Integer, Integer> b) {
            if (a.getLeft() < b.getLeft())
                return -1;
            if (a.getLeft() > b.getLeft())
                return 1;
            return b.getRight() - a.getRight();
        }//w w w. j av a2 s .c o  m
    });

    int prev = 0;
    for (Pair<Integer, Integer> p : startend) {
        int start = p.getLeft();
        int end = p.getRight();
        if (end < prev)
            continue;
        if (start < prev)
            start = prev;
        sb.append(line.substring(prev, start));
        if (start < end) {
            sb.append(colorEscStart);
            sb.append(line.substring(start, end));
            sb.append(colorEscEnd);
        }
        prev = end;
    }

    return (sb.toString() + line.substring(prev));
}

From source file:com.google.dart.java2dart.engine.EngineSemanticProcessor.java

/**
 * Find code like:/*from w  ww .  ja v a  2s .c  o  m*/
 * 
 * <pre>
 *   Field scopeField = visitor.getClass().getSuperclass().getDeclaredField("nameScope");
 *   scopeField.setAccessible(true);
 *   Scope outerScope = (Scope) scopeField.get(visitor);
 * </pre>
 * 
 * and replaces it with direct calling of generated public accessors.
 */
static void rewriteReflectionFieldsWithDirect(final Context context, CompilationUnit unit) {
    final Map<String, String> varToField = Maps.newHashMap();
    final Map<String, String> varToMethod = Maps.newHashMap();
    final Set<Pair<String, String>> refClassFields = Sets.newHashSet();
    final String accessorSuffix = "_J2DAccessor";
    unit.accept(new RecursiveASTVisitor<Void>() {

        @Override
        public Void visitBlock(Block node) {
            List<Statement> statements = ImmutableList.copyOf(node.getStatements());
            for (Statement statement : statements) {
                statement.accept(this);
            }
            return null;
        }

        @Override
        public Void visitExpressionStatement(ExpressionStatement node) {
            if (node.getExpression() instanceof MethodInvocation) {
                MethodInvocation invocation = (MethodInvocation) node.getExpression();
                if (JavaUtils.isMethod(context.getNodeBinding(invocation), "java.lang.reflect.AccessibleObject",
                        "setAccessible")) {
                    ((Block) node.getParent()).getStatements().remove(node);
                    return null;
                }
            }
            return super.visitExpressionStatement(node);
        }

        @Override
        public Void visitMethodInvocation(MethodInvocation node) {
            List<Expression> arguments = node.getArgumentList().getArguments();
            if (JavaUtils.isMethod(context.getNodeBinding(node), "java.lang.reflect.Field", "get")) {
                Expression target = arguments.get(0);
                String varName = ((SimpleIdentifier) node.getTarget()).getName();
                String fieldName = varToField.get(varName);
                String accessorName = fieldName + accessorSuffix;
                SemanticProcessor.replaceNode(node, propertyAccess(target, identifier(accessorName)));
                return null;
            }
            if (JavaUtils.isMethod(context.getNodeBinding(node), "java.lang.reflect.Field", "set")) {
                Expression target = arguments.get(0);
                String varName = ((SimpleIdentifier) node.getTarget()).getName();
                String fieldName = varToField.get(varName);
                String accessorName = fieldName + accessorSuffix;
                SemanticProcessor.replaceNode(node, assignmentExpression(
                        propertyAccess(target, identifier(accessorName)), TokenType.EQ, arguments.get(1)));
                return null;
            }
            if (JavaUtils.isMethod(context.getNodeBinding(node), "java.lang.reflect.Method", "invoke")) {
                Expression target = arguments.get(0);
                String varName = ((SimpleIdentifier) node.getTarget()).getName();
                String methodName = varToMethod.get(varName);
                List<Expression> methodArgs;
                if (arguments.size() == 1) {
                    methodArgs = Lists.newArrayList();
                } else if (arguments.size() == 2 && arguments.get(1) instanceof ListLiteral) {
                    methodArgs = ((ListLiteral) arguments.get(1)).getElements();
                } else {
                    methodArgs = Lists.newArrayList(arguments);
                    methodArgs.remove(0);
                }
                if (methodName != null) {
                    SemanticProcessor.replaceNode(node, methodInvocation(target, methodName, methodArgs));
                }
                return null;
            }
            return super.visitMethodInvocation(node);
        }

        @Override
        public Void visitVariableDeclarationStatement(VariableDeclarationStatement node) {
            super.visitVariableDeclarationStatement(node);
            VariableDeclarationList variableList = node.getVariables();
            ITypeBinding typeBinding = context.getNodeTypeBinding(variableList.getType());
            List<VariableDeclaration> variables = variableList.getVariables();
            if (JavaUtils.isTypeNamed(typeBinding, "java.lang.reflect.Field") && variables.size() == 1) {
                VariableDeclaration variable = variables.get(0);
                if (variable.getInitializer() instanceof MethodInvocation) {
                    MethodInvocation initializer = (MethodInvocation) variable.getInitializer();
                    if (JavaUtils.isMethod(context.getNodeBinding(initializer), "java.lang.Class",
                            "getDeclaredField")) {
                        Expression getFieldArgument = initializer.getArgumentList().getArguments().get(0);
                        String varName = variable.getName().getName();
                        String fieldName = ((SimpleStringLiteral) getFieldArgument).getValue();
                        varToField.put(varName, fieldName);
                        ((Block) node.getParent()).getStatements().remove(node);
                        // add (Class, Field) pair to generate accessor later
                        addClassFieldPair(initializer.getTarget(), fieldName);
                    }
                }
            }
            if (JavaUtils.isTypeNamed(typeBinding, "java.lang.reflect.Method") && variables.size() == 1) {
                VariableDeclaration variable = variables.get(0);
                if (variable.getInitializer() instanceof MethodInvocation) {
                    MethodInvocation initializer = (MethodInvocation) variable.getInitializer();
                    if (JavaUtils.isMethod(context.getNodeBinding(initializer), "java.lang.Class",
                            "getDeclaredMethod")) {
                        Expression getMethodArgument = initializer.getArgumentList().getArguments().get(0);
                        String varName = variable.getName().getName();
                        String methodName = ((SimpleStringLiteral) getMethodArgument).getValue();
                        varToMethod.put(varName, methodName);
                        ((Block) node.getParent()).getStatements().remove(node);
                    }
                }
            }
            return null;
        }

        private void addClassFieldPair(Expression target, String fieldName) {
            while (target instanceof MethodInvocation) {
                target = ((MethodInvocation) target).getTarget();
            }
            // we expect: object.runtimeType
            if (target instanceof PropertyAccess) {
                Expression classTarget = ((PropertyAccess) target).getTarget();
                ITypeBinding classTargetBinding = context.getNodeTypeBinding(classTarget);
                String className = classTargetBinding.getName();
                refClassFields.add(Pair.of(className, fieldName));
            }
        }
    });
    // generate private field accessors
    unit.accept(new RecursiveASTVisitor<Void>() {
        @Override
        public Void visitClassDeclaration(ClassDeclaration node) {
            String className = node.getName().getName();
            for (Pair<String, String> pair : refClassFields) {
                if (pair.getLeft().equals(className)) {
                    String fieldName = pair.getRight();
                    String accessorName = fieldName + accessorSuffix;
                    String privateFieldName = "_" + fieldName;
                    node.getMembers()
                            .add(methodDeclaration(null, null, Keyword.GET, null, identifier(accessorName),
                                    null, expressionFunctionBody(identifier(privateFieldName))));
                    node.getMembers()
                            .add(methodDeclaration(null, null, Keyword.SET, null, identifier(accessorName),
                                    formalParameterList(simpleFormalParameter("__v")),
                                    expressionFunctionBody(assignmentExpression(identifier(privateFieldName),
                                            TokenType.EQ, identifier("__v")))));
                }
            }
            return super.visitClassDeclaration(node);
        }
    });
}

From source file:android.databinding.tool.util.XmlEditor.java

public static String strip(File f, String newTag) throws IOException {
    ANTLRInputStream inputStream = new ANTLRInputStream(new FileReader(f));
    XMLLexer lexer = new XMLLexer(inputStream);
    CommonTokenStream tokenStream = new CommonTokenStream(lexer);
    XMLParser parser = new XMLParser(tokenStream);
    XMLParser.DocumentContext expr = parser.document();
    XMLParser.ElementContext root = expr.element();

    if (root == null || !"layout".equals(nodeName(root))) {
        return null; // not a binding layout
    }/* w  w w.j a  va 2  s. c o  m*/

    List<? extends ElementContext> childrenOfRoot = elements(root);
    List<? extends XMLParser.ElementContext> dataNodes = filterNodesByName("data", childrenOfRoot);
    if (dataNodes.size() > 1) {
        L.e("Multiple binding data tags in %s. Expecting a maximum of one.", f.getAbsolutePath());
    }

    ArrayList<String> lines = new ArrayList<>();
    lines.addAll(FileUtils.readLines(f, "utf-8"));

    for (android.databinding.parser.XMLParser.ElementContext it : dataNodes) {
        replace(lines, toPosition(it.getStart()), toEndPosition(it.getStop()), "");
    }
    List<? extends XMLParser.ElementContext> layoutNodes = excludeNodesByName("data", childrenOfRoot);
    if (layoutNodes.size() != 1) {
        L.e("Only one layout element and one data element are allowed. %s has %d", f.getAbsolutePath(),
                layoutNodes.size());
    }

    final XMLParser.ElementContext layoutNode = layoutNodes.get(0);

    ArrayList<Pair<String, android.databinding.parser.XMLParser.ElementContext>> noTag = new ArrayList<>();

    recurseReplace(layoutNode, lines, noTag, newTag, 0);

    // Remove the <layout>
    Position rootStartTag = toPosition(root.getStart());
    Position rootEndTag = toPosition(root.content().getStart());
    replace(lines, rootStartTag, rootEndTag, "");

    // Remove the </layout>
    ImmutablePair<Position, Position> endLayoutPositions = findTerminalPositions(root, lines);
    replace(lines, endLayoutPositions.left, endLayoutPositions.right, "");

    StringBuilder rootAttributes = new StringBuilder();
    for (AttributeContext attr : attributes(root)) {
        rootAttributes.append(' ').append(attr.getText());
    }
    Pair<String, XMLParser.ElementContext> noTagRoot = null;
    for (Pair<String, XMLParser.ElementContext> pair : noTag) {
        if (pair.getRight() == layoutNode) {
            noTagRoot = pair;
            break;
        }
    }
    if (noTagRoot != null) {
        ImmutablePair<String, XMLParser.ElementContext> newRootTag = new ImmutablePair<>(
                noTagRoot.getLeft() + rootAttributes.toString(), layoutNode);
        int index = noTag.indexOf(noTagRoot);
        noTag.set(index, newRootTag);
    } else {
        ImmutablePair<String, XMLParser.ElementContext> newRootTag = new ImmutablePair<>(
                rootAttributes.toString(), layoutNode);
        noTag.add(newRootTag);
    }
    //noinspection NullableProblems
    Collections.sort(noTag, new Comparator<Pair<String, XMLParser.ElementContext>>() {
        @Override
        public int compare(Pair<String, XMLParser.ElementContext> o1,
                Pair<String, XMLParser.ElementContext> o2) {
            Position start1 = toPosition(o1.getRight().getStart());
            Position start2 = toPosition(o2.getRight().getStart());
            int lineCmp = Integer.compare(start2.line, start1.line);
            if (lineCmp != 0) {
                return lineCmp;
            }
            return Integer.compare(start2.charIndex, start1.charIndex);
        }
    });
    for (Pair<String, android.databinding.parser.XMLParser.ElementContext> it : noTag) {
        XMLParser.ElementContext element = it.getRight();
        String tag = it.getLeft();
        Position endTagPosition = endTagPosition(element);
        fixPosition(lines, endTagPosition);
        String line = lines.get(endTagPosition.line);
        String newLine = line.substring(0, endTagPosition.charIndex) + " " + tag
                + line.substring(endTagPosition.charIndex);
        lines.set(endTagPosition.line, newLine);
    }
    return StringUtils.join(lines, System.getProperty("line.separator"));
}

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

private static Map<Pair<String, Double>, MS1ScanForWellAndMassCharge> getMultipleMS1s(MS1 ms1,
        Set<Pair<String, Double>> metlinMasses, String ms1File)
        throws ParserConfigurationException, IOException, XMLStreamException {

    // In order for this to sit well with the data model we'll need to ensure the keys are all unique.
    Set<String> uniqueKeys = new HashSet<>();
    metlinMasses.stream().map(Pair::getLeft).forEach(x -> {
        if (uniqueKeys.contains(x)) {
            throw new RuntimeException(
                    String.format("Assumption violation: found duplicate metlin mass keys: %s", x));
        }//  w  ww . j  ava2 s .  c o  m
        uniqueKeys.add(x);
    });

    Iterator<LCMSSpectrum> ms1Iterator = new LCMSNetCDFParser().getIterator(ms1File);

    Map<Double, List<XZ>> scanLists = new HashMap<>(metlinMasses.size());
    // Initialize reading buffers for all of the target masses.
    metlinMasses.forEach(x -> {
        if (!scanLists.containsKey(x.getRight())) {
            scanLists.put(x.getRight(), new ArrayList<>());
        }
    });
    // De-dupe by mass in case we have exact duplicates, sort for well-ordered extractions.
    List<Double> sortedMasses = new ArrayList<>(scanLists.keySet());

    /* Note: this operation is O(n * m) where n is the number of (mass, intensity) readings from the scan
     * and m is the number of mass targets specified.  We might be able to get this down to O(m log n), but
     * we'll save that for once we get this working at all. */

    while (ms1Iterator.hasNext()) {
        LCMSSpectrum timepoint = ms1Iterator.next();

        // get all (mz, intensity) at this timepoint
        List<Pair<Double, Double>> intensities = timepoint.getIntensities();

        // for this timepoint, extract each of the ion masses from the METLIN set
        for (Double ionMz : sortedMasses) {
            // this time point is valid to look at if its max intensity is around
            // the mass we care about. So lets first get the max peak location
            double intensityForMz = ms1.extractMZ(ionMz, intensities);

            // the above is Pair(mz_extracted, intensity), where mz_extracted = mz
            // we now add the timepoint val and the intensity to the output
            XZ intensityAtThisTime = new XZ(timepoint.getTimeVal(), intensityForMz);
            scanLists.get(ionMz).add(intensityAtThisTime);
        }
    }

    Map<Pair<String, Double>, MS1ScanForWellAndMassCharge> finalResults = new HashMap<>(metlinMasses.size());

    /* Note: we might be able to squeeze more performance out of this by computing the
     * stats once per trace and then storing them.  But the time to compute will probably
     * be dwarfed by the time to extract the data (assuming deduplication was done ahead
     * of time), so we'll leave it as is for now. */
    for (Pair<String, Double> pair : metlinMasses) {
        String label = pair.getLeft();
        Double mz = pair.getRight();
        MS1ScanForWellAndMassCharge result = new MS1ScanForWellAndMassCharge();

        result.setMetlinIons(Collections.singletonList(label));
        result.getIonsToSpectra().put(label, scanLists.get(mz));
        ms1.computeAndStorePeakProfile(result, label);

        // DO NOT use isGoodPeak here.  We want positive and negative results alike.

        // There's only one ion in this scan, so just use its max.
        Double maxIntensity = result.getMaxIntensityForIon(label);
        result.setMaxYAxis(maxIntensity);
        // How/why is this not IonsToMax?  Just set it as such for this.
        result.setIndividualMaxIntensities(Collections.singletonMap(label, maxIntensity));

        finalResults.put(pair, result);
    }

    return finalResults;
}

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

private static Map<Integer, StandardWell> extractStandardWellsFromOptionsList(DB db,
        List<ChemicalAssociatedWithPathway> pathwayChems, String[] optionValues, Plate standardPlate)
        throws SQLException, IOException, ClassNotFoundException {
    Map<String, String> chemToWellByName = new HashMap<>();
    Map<Integer, String> chemToWellByIndex = new HashMap<>();
    if (optionValues != null && optionValues.length > 0) {
        for (int i = 0; i < optionValues.length; i++) {
            String[] fields = StringUtils.split(optionValues[i], "=");
            if (fields != null && fields.length == 2) {
                chemToWellByName.put(fields[0], fields[1]);
            } else {
                chemToWellByIndex.put(i, optionValues[i]);
            }/*ww  w  .ja  v  a  2s  . co m*/
        }
    }

    Map<Integer, StandardWell> results = new HashMap<>();
    for (int i = 0; i < pathwayChems.size(); i++) {
        ChemicalAssociatedWithPathway chem = pathwayChems.get(i);
        String coords = null;
        if (chemToWellByName.containsKey(chem.getChemical())) {
            coords = chemToWellByName.remove(chem.getChemical());
        } else if (chemToWellByIndex.containsKey(i)) {
            coords = chemToWellByIndex.remove(i);
        }

        if (coords == null) {
            System.err.format("No coordinates specified for %s, skipping\n", chem.getChemical());
            continue;
        }
        Pair<Integer, Integer> intCoords = Utils.parsePlateCoordinates(coords);
        StandardWell well = StandardWell.getInstance().getStandardWellsByPlateIdAndCoordinates(db,
                standardPlate.getId(), intCoords.getLeft(), intCoords.getRight());
        if (well == null) {
            System.err.format("ERROR: Could not find well %s in plate %s\n", coords,
                    standardPlate.getBarcode());
            System.exit(-1);
        } else if (!well.getChemical().equals(chem.getChemical())) {
            System.err.format(
                    "WARNING: pathway chemical %s and chemical in specified standard well %s don't match!\n",
                    chem.getChemical(), well.getChemical());
        }

        System.out.format("Using standard well %s : %s for pathway chemical %s (step %d)\n",
                standardPlate.getBarcode(), coords, chem.getChemical(), chem.getIndex());

        results.put(chem.getId(), well);
    }

    return results;
}

From source file:Solver.java

private static void Solve(Pair<Integer, Integer[]> data, boolean searchAll) {
    int N = data.getLeft();
    Integer[] S = data.getRight();
    int nsquares = S.length;
    Store store = new Store();

    IntVar[] X = new IntVar[nsquares];
    IntVar[] Y = new IntVar[nsquares];

    IntVar[] W = new IntVar[nsquares];
    IntVar[] H = new IntVar[nsquares];

    IntVar L = new IntVar(store, N, N);

    ArrayUtils.reverse(S);//from   ww  w .ja v  a 2 s  .c  o m

    for (int i = 0; i < nsquares; i++) {
        X[i] = new IntVar(store, "X" + i, 0, N - S[i]);
        Y[i] = new IntVar(store, "Y" + i, 0, N - S[i]);

        W[i] = new IntVar(store, S[i], S[i]);
        H[i] = new IntVar(store, S[i], S[i]);
    }

    Constraint ctr1 = new Diff2(X, Y, W, H);
    Constraint ctr2 = new Cumulative(X, W, H, L);
    Constraint ctr3 = new Cumulative(Y, W, H, L);

    ctr1.impose(store);
    ctr2.impose(store);
    ctr3.impose(store);

    Search<IntVar> searchX = new DepthFirstSearch<IntVar>();
    Search<IntVar> searchY = new DepthFirstSearch<IntVar>();
    SelectChoicePoint<IntVar> labelX = new SimpleSelect<>(X, new SmallestMin<>(), new SmallestDomain<>(),
            new IndomainMin<>());
    SelectChoicePoint<IntVar> labelY = new SimpleSelect<>(Y, new SmallestMin<>(), new SmallestDomain<>(),
            new IndomainMin<>());
    searchY.setSelectChoicePoint(labelY);
    searchX.addChildSearch(searchY);

    if (searchAll)
        searchX.getSolutionListener().searchAll(true);

    searchX.getSolutionListener().recordSolutions(true);
    searchY.getSolutionListener().recordSolutions(true);
    searchX.setPrintInfo(false);
    searchY.setPrintInfo(false);
    searchX.labeling(store, labelX);
    for (int sid = 1; sid <= searchX.getSolutionListener().solutionsNo(); sid++) {
        SwingUtilities.invokeLater((new Solver()).new Window(sid - 1, window_size, N, searchX.getSolution(sid),
                searchY.getSolution(sid), S));
    }
}

From source file:com.netflix.imfutility.itunes.audio.ChannelsMapperTest.java

private static void assertChannelEquals(Pair<SequenceUUID, Integer> channel, Integer audioSeqNum,
        Integer channelsNum) {//  ww  w.j  av  a  2s. c  o m
    SequenceUUID seqUuid = getSequenceUuid(audioSeqNum, SequenceType.AUDIO);

    assertEquals(seqUuid, channel.getLeft());
    assertEquals(channelsNum, channel.getRight());
}

From source file:edu.uci.ics.asterix.metadata.feeds.FeedUtil.java

public static JobSpecification alterJobSpecificationForFeed(JobSpecification spec,
        FeedConnectionId feedConnectionId, Map<String, String> feedPolicyProperties) {

    if (LOGGER.isLoggable(Level.INFO)) {
        LOGGER.info("Original Job Spec:" + spec);
    }//from w ww. j  av  a  2s . c  o  m

    JobSpecification altered = new JobSpecification(spec.getFrameSize());
    Map<OperatorDescriptorId, IOperatorDescriptor> operatorMap = spec.getOperatorMap();
    boolean preProcessingRequired = preProcessingRequired(feedConnectionId);
    // copy operators
    String operandId = null;
    Map<OperatorDescriptorId, OperatorDescriptorId> oldNewOID = new HashMap<OperatorDescriptorId, OperatorDescriptorId>();
    FeedMetaOperatorDescriptor metaOp = null;
    for (Entry<OperatorDescriptorId, IOperatorDescriptor> entry : operatorMap.entrySet()) {
        operandId = FeedRuntimeId.DEFAULT_OPERAND_ID;
        IOperatorDescriptor opDesc = entry.getValue();
        if (opDesc instanceof FeedCollectOperatorDescriptor) {
            FeedCollectOperatorDescriptor orig = (FeedCollectOperatorDescriptor) opDesc;
            FeedCollectOperatorDescriptor fiop = new FeedCollectOperatorDescriptor(altered,
                    orig.getFeedConnectionId(), orig.getSourceFeedId(), (ARecordType) orig.getOutputType(),
                    orig.getRecordDescriptor(), orig.getFeedPolicyProperties(), orig.getSubscriptionLocation());
            oldNewOID.put(opDesc.getOperatorId(), fiop.getOperatorId());
        } else if (opDesc instanceof AsterixLSMTreeInsertDeleteOperatorDescriptor) {
            operandId = ((AsterixLSMTreeInsertDeleteOperatorDescriptor) opDesc).getIndexName();
            metaOp = new FeedMetaOperatorDescriptor(altered, feedConnectionId, opDesc, feedPolicyProperties,
                    FeedRuntimeType.STORE, false, operandId);
            oldNewOID.put(opDesc.getOperatorId(), metaOp.getOperatorId());
        } else if (opDesc instanceof AsterixLSMInvertedIndexInsertDeleteOperatorDescriptor) {
            operandId = ((AsterixLSMInvertedIndexInsertDeleteOperatorDescriptor) opDesc).getIndexName();
            metaOp = new FeedMetaOperatorDescriptor(altered, feedConnectionId, opDesc, feedPolicyProperties,
                    FeedRuntimeType.STORE, false, operandId);
            oldNewOID.put(opDesc.getOperatorId(), metaOp.getOperatorId());

        } else {
            FeedRuntimeType runtimeType = null;
            boolean enableSubscriptionMode = false;
            boolean createMetaOp = true;
            OperatorDescriptorId opId = null;
            if (opDesc instanceof AlgebricksMetaOperatorDescriptor) {
                IPushRuntimeFactory runtimeFactory = ((AlgebricksMetaOperatorDescriptor) opDesc).getPipeline()
                        .getRuntimeFactories()[0];
                if (runtimeFactory instanceof AssignRuntimeFactory) {
                    IConnectorDescriptor connectorDesc = spec.getOperatorInputMap().get(opDesc.getOperatorId())
                            .get(0);
                    IOperatorDescriptor sourceOp = spec.getProducer(connectorDesc);
                    if (sourceOp instanceof FeedCollectOperatorDescriptor) {
                        runtimeType = preProcessingRequired ? FeedRuntimeType.COMPUTE : FeedRuntimeType.OTHER;
                        enableSubscriptionMode = preProcessingRequired;
                    } else {
                        runtimeType = FeedRuntimeType.OTHER;
                    }
                } else if (runtimeFactory instanceof EmptyTupleSourceRuntimeFactory) {
                    runtimeType = FeedRuntimeType.ETS;
                } else {
                    runtimeType = FeedRuntimeType.OTHER;
                }
            } else {
                if (opDesc instanceof AbstractSingleActivityOperatorDescriptor) {
                    runtimeType = FeedRuntimeType.OTHER;
                } else {
                    opId = altered.createOperatorDescriptorId(opDesc);
                    createMetaOp = false;
                }
            }
            if (createMetaOp) {
                metaOp = new FeedMetaOperatorDescriptor(altered, feedConnectionId, opDesc, feedPolicyProperties,
                        runtimeType, enableSubscriptionMode, operandId);
                opId = metaOp.getOperatorId();
            }
            oldNewOID.put(opDesc.getOperatorId(), opId);
        }
    }

    // copy connectors
    Map<ConnectorDescriptorId, ConnectorDescriptorId> connectorMapping = new HashMap<ConnectorDescriptorId, ConnectorDescriptorId>();
    for (Entry<ConnectorDescriptorId, IConnectorDescriptor> entry : spec.getConnectorMap().entrySet()) {
        IConnectorDescriptor connDesc = entry.getValue();
        ConnectorDescriptorId newConnId = altered.createConnectorDescriptor(connDesc);
        connectorMapping.put(entry.getKey(), newConnId);
    }

    // make connections between operators
    for (Entry<ConnectorDescriptorId, Pair<Pair<IOperatorDescriptor, Integer>, Pair<IOperatorDescriptor, Integer>>> entry : spec
            .getConnectorOperatorMap().entrySet()) {
        IConnectorDescriptor connDesc = altered.getConnectorMap().get(connectorMapping.get(entry.getKey()));
        Pair<IOperatorDescriptor, Integer> leftOp = entry.getValue().getLeft();
        Pair<IOperatorDescriptor, Integer> rightOp = entry.getValue().getRight();

        IOperatorDescriptor leftOpDesc = altered.getOperatorMap()
                .get(oldNewOID.get(leftOp.getLeft().getOperatorId()));
        IOperatorDescriptor rightOpDesc = altered.getOperatorMap()
                .get(oldNewOID.get(rightOp.getLeft().getOperatorId()));

        altered.connect(connDesc, leftOpDesc, leftOp.getRight(), rightOpDesc, rightOp.getRight());
    }

    // prepare for setting partition constraints
    Map<OperatorDescriptorId, List<LocationConstraint>> operatorLocations = new HashMap<OperatorDescriptorId, List<LocationConstraint>>();
    Map<OperatorDescriptorId, Integer> operatorCounts = new HashMap<OperatorDescriptorId, Integer>();

    for (Constraint constraint : spec.getUserConstraints()) {
        LValueConstraintExpression lexpr = constraint.getLValue();
        ConstraintExpression cexpr = constraint.getRValue();
        OperatorDescriptorId opId;
        switch (lexpr.getTag()) {
        case PARTITION_COUNT:
            opId = ((PartitionCountExpression) lexpr).getOperatorDescriptorId();
            operatorCounts.put(opId, (int) ((ConstantExpression) cexpr).getValue());
            break;
        case PARTITION_LOCATION:
            opId = ((PartitionLocationExpression) lexpr).getOperatorDescriptorId();

            IOperatorDescriptor opDesc = altered.getOperatorMap().get(oldNewOID.get(opId));
            List<LocationConstraint> locations = operatorLocations.get(opDesc.getOperatorId());
            if (locations == null) {
                locations = new ArrayList<>();
                operatorLocations.put(opDesc.getOperatorId(), locations);
            }
            String location = (String) ((ConstantExpression) cexpr).getValue();
            LocationConstraint lc = new LocationConstraint();
            lc.location = location;
            lc.partition = ((PartitionLocationExpression) lexpr).getPartition();
            locations.add(lc);
            break;
        }
    }

    // set absolute location constraints
    for (Entry<OperatorDescriptorId, List<LocationConstraint>> entry : operatorLocations.entrySet()) {
        IOperatorDescriptor opDesc = altered.getOperatorMap().get(oldNewOID.get(entry.getKey()));
        Collections.sort(entry.getValue(), new Comparator<LocationConstraint>() {

            @Override
            public int compare(LocationConstraint o1, LocationConstraint o2) {
                return o1.partition - o2.partition;
            }
        });
        String[] locations = new String[entry.getValue().size()];
        for (int i = 0; i < locations.length; ++i) {
            locations[i] = entry.getValue().get(i).location;
        }
        PartitionConstraintHelper.addAbsoluteLocationConstraint(altered, opDesc, locations);
    }

    // set count constraints
    for (Entry<OperatorDescriptorId, Integer> entry : operatorCounts.entrySet()) {
        IOperatorDescriptor opDesc = altered.getOperatorMap().get(oldNewOID.get(entry.getKey()));
        if (!operatorLocations.keySet().contains(entry.getKey())) {
            PartitionConstraintHelper.addPartitionCountConstraint(altered, opDesc, entry.getValue());
        }
    }

    // useConnectorSchedulingPolicy
    altered.setUseConnectorPolicyForScheduling(spec.isUseConnectorPolicyForScheduling());

    // connectorAssignmentPolicy
    altered.setConnectorPolicyAssignmentPolicy(spec.getConnectorPolicyAssignmentPolicy());

    // roots
    for (OperatorDescriptorId root : spec.getRoots()) {
        altered.addRoot(altered.getOperatorMap().get(oldNewOID.get(root)));
    }

    // jobEventListenerFactory
    altered.setJobletEventListenerFactory(spec.getJobletEventListenerFactory());

    if (LOGGER.isLoggable(Level.INFO)) {
        LOGGER.info("New Job Spec:" + altered);
    }

    return altered;

}

From source file:com.spotify.heroic.HeroicCore.java

static boolean awaitLifeCycles(final String op, final CoreComponent primary, final Duration await,
        final List<LifeCycleNamedHook<AsyncFuture<Void>>> hooks)
        throws InterruptedException, ExecutionException {
    log.info("[{}] {} lifecycle(s)...", op, hooks.size());

    final AsyncFramework async = primary.async();

    final List<AsyncFuture<Void>> futures = new ArrayList<>();
    final List<Pair<AsyncFuture<Void>, LifeCycleHook<AsyncFuture<Void>>>> pairs = new ArrayList<>();

    for (final LifeCycleNamedHook<AsyncFuture<Void>> hook : hooks) {
        log.trace("[{}] {}", op, hook.id());

        final AsyncFuture<Void> future;

        try {//  w  w w . java2s  . c o  m
            future = hook.get();
        } catch (Exception e) {
            futures.add(async.failed(e));
            break;
        }

        if (log.isTraceEnabled()) {
            final Stopwatch w = Stopwatch.createStarted();

            future.onFinished(() -> {
                log.trace("[{}] {}, took {}us", op, hook.id(), w.elapsed(TimeUnit.MICROSECONDS));
            });
        }

        futures.add(future);
        pairs.add(Pair.of(future, hook));
    }

    try {
        async.collect(futures).get(await.getDuration(), await.getUnit());
    } catch (final TimeoutException e) {
        log.error("Operation timed out");

        for (final Pair<AsyncFuture<Void>, LifeCycleHook<AsyncFuture<Void>>> pair : pairs) {
            if (!pair.getLeft().isDone()) {
                log.error("{}: did not finish in time: {}", op, pair.getRight());
            }
        }

        return false;
    }

    log.info("[{}] {} lifecycle(s) done", op, hooks.size());
    return true;
}

From source file:com.yahoo.elide.core.exceptions.JsonPatchExtensionException.java

public JsonPatchExtensionException(final Pair<Integer, JsonNode> response) {
    super(response.getLeft());
    this.response = response;
}