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.github.drbookings.model.settings.SettingsManager.java

public void putRoomNameMapping(final String vendorName, final String ourName)
        throws ClassNotFoundException, IOException {
    putRoomNameMapping(new ImmutablePair<>(vendorName, ourName));

}

From source file:io.cloudslang.lang.compiler.modeller.MetadataModellerImpl.java

private Pair<StepMetadata, List<RuntimeException>> transformToStepMetadata(String stepName,
        Map<String, String> parsedData) {
    Map<String, String> inputs = new LinkedHashMap<>();
    Map<String, String> outputs = new LinkedHashMap<>();
    List<RuntimeException> errors = new ArrayList<>();

    for (Map.Entry<String, String> entry : parsedData.entrySet()) {
        String declaration = entry.getKey();
        String[] declarationElements = descriptionPatternMatcher.splitDeclaration(declaration);
        String tag = declarationElements[0];
        if (StepDescriptionTag.isStepDescriptionTag(tag)) {
            String content = entry.getValue();
            StepDescriptionTag descriptionTag = StepDescriptionTag.fromString(tag);
            if (descriptionTag != null) {
                switch (descriptionTag) {
                case INPUT:
                    processStepDeclaration(declarationElements, errors, tag, inputs, content, stepName);
                    break;
                case OUTPUT:
                    processStepDeclaration(declarationElements, errors, tag, outputs, content, stepName);
                    break;
                default:
                    // shouldn't get here
                    errors.add(new NotImplementedException("Unrecognized tag: " + descriptionTag));
                }//from w  ww.  j  av  a  2s.  c o m
            } else {
                // shouldn't get here
                errors.add(new RuntimeException("Unrecognized tag: " + tag));
            }
        } else {
            errors.add(new RuntimeException("Unrecognized tag for step description section: " + tag));
        }
    }

    StepMetadata stepMetadata = new StepMetadata(stepName, inputs, outputs);
    return new ImmutablePair<>(stepMetadata, errors);
}

From source file:com.epam.catgenome.manager.gene.GeneRegisterer.java

private void processLastFeature(GeneFeature feature, int featuresCount, GeneFile geneFile,
        List<FeatureIndexEntry> allEntries, boolean doFeatureIndex) throws IOException {
    // Put the last one in metaMap
    if (feature != null) {
        endPosition = feature.getStart();
        if (currentKey != null) {
            metaMap.put(currentKey, new ImmutablePair<>(startPosition, endPosition));
            // Put the last one
            if (Utils.chromosomeMapContains(chromosomeMap, currentKey) && doFeatureIndex) {
                featureIndexManager.writeLuceneIndexForFile(geneFile, allEntries);
                allEntries.clear();/*from  w  w  w  .j  a  va 2s  .c  o  m*/
            }
        }
    }

    if (featuresCount > 0 && currentWig != null && currentChromosome != null) {
        currentWig.setValue((float) featuresCount);
        histogram.add(currentWig);
        fileManager.writeHistogram(geneFile, currentChromosome.getName(), histogram);
    }
}

From source file:com.addthis.hydra.kafka.consumer.ConsumerUtils.java

public static Pair<ConsumerConnector, KafkaStream<Bundle, Bundle>> newBundleConsumer(String zookeeper,
        String topic, HashMap<String, String> overrides) {
    Map<String, Integer> topicStreams = new HashMap<>();
    topicStreams.put(topic, 1);/*from w w  w  .j  ava 2 s .  co  m*/
    Pair<ConsumerConnector, Map<String, List<KafkaStream<Bundle, Bundle>>>> connectorAndStreams = newBundleStreams(
            zookeeper, topicStreams, overrides);
    return new ImmutablePair<>(connectorAndStreams.getLeft(), connectorAndStreams.getRight().get(topic).get(0));
}

From source file:hu.ppke.itk.nlpg.purepos.decoder.AbstractDecoder.java

private Map<NGram<Integer>, Map<Integer, Pair<Double, Double>>> getNextForGuessedOOVToken(
        final Set<NGram<Integer>> prevTagsSet, String lWord, ISuffixGuesser<String, Integer> guesser) {

    Map<NGram<Integer>, Map<Integer, Pair<Double, Double>>> ret = new HashMap<NGram<Integer>, Map<Integer, Pair<Double, Double>>>();
    Map<Integer, Pair<Double, Double>> tagProbs;
    Map<Integer, Double> guessedTags = guesser.getTagLogProbabilities(lWord);

    Set<Entry<Integer, Double>> prunedGuessedTags = pruneGuessedTags(guessedTags);

    tagProbs = new HashMap<Integer, Pair<Double, Double>>();
    for (NGram<Integer> prevTags : prevTagsSet) {
        for (Entry<Integer, Double> guess : prunedGuessedTags) {
            Double emissionProb = guess.getValue();
            Integer tag = guess.getKey();

            Double tagTransProb = model.getTagTransitionModel().getLogProb(prevTags.toList(), tag);
            double aprioriProb = Math.log(model.getAprioriTagProbs().get(tag));
            tagProbs.put(tag, new ImmutablePair<Double, Double>(tagTransProb, emissionProb - aprioriProb));

        }//from w w w  . ja  v  a  2  s.  co m
        ret.put(prevTags, tagProbs);
    }
    return ret;
}

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

@Override
protected Pair<List<File>, List<File>> createWorkingFiles(@NotNull SolutionPerJob solutionPerJob)
        throws IOException {
    Pair<List<File>, List<File>> returnValue;

    List<File> netFileList = dataProcessor.retrieveInputFiles(".net", solutionPerJob.getParentID(),
            solutionPerJob.getId(), dataProcessor.getProviderName(),
            solutionPerJob.getTypeVMselected().getId());
    List<File> defFileList = dataProcessor.retrieveInputFiles(".def", solutionPerJob.getParentID(),
            solutionPerJob.getId(), dataProcessor.getProviderName(),
            solutionPerJob.getTypeVMselected().getId());
    List<File> statFileList = dataProcessor.retrieveInputFiles(".stat", solutionPerJob.getParentID(),
            solutionPerJob.getId(), dataProcessor.getProviderName(),
            solutionPerJob.getTypeVMselected().getId());

    final String experiment = String.format("%s, class %s, provider %s, VM %s, # %d",
            solutionPerJob.getParentID(), solutionPerJob.getId(), dataProcessor.getProviderName(),
            solutionPerJob.getTypeVMselected().getId(), solutionPerJob.getNumberVM());

    if (netFileList.isEmpty() || defFileList.isEmpty() || statFileList.isEmpty()) {
        logger.debug(String.format("Generating SPN model for %s", experiment));
        usingInputModel = false;//from ww  w .  jav a  2  s . c  o m
        returnValue = generateSPNModel(solutionPerJob);
    } else {
        logger.debug(String.format("Using input SPN model for %s", experiment));
        usingInputModel = true;

        // TODO now it just takes the first file, I would expect a single file per list
        File inputNetFile = netFileList.get(0);
        File inputDefFile = defFileList.get(0);
        File inputStatFile = statFileList.get(0);

        String prefix = filePrefix(solutionPerJob);
        final String originalLabel = String.join("", Files.readAllLines(inputStatFile.toPath()));
        label = statSafeLabel;

        Map<String, String> placeHolders = new TreeMap<>();
        placeHolders.put("@@CONCURRENCY@@", Long.toUnsignedString(solutionPerJob.getNumberUsers().longValue()));
        placeHolders.put("@@CORES@@", Long.toUnsignedString(solutionPerJob.getNumberContainers().longValue()));
        logger.trace("@@CORES@@ replaced with " + solutionPerJob.getNumberContainers().toString());
        placeHolders.put(originalLabel, label);
        List<String> outcomes = processPlaceholders(inputDefFile, placeHolders);

        File defFile = fileUtility.provideTemporaryFile(prefix, ".def");
        writeLinesToFile(outcomes, defFile);
        outcomes = processPlaceholders(inputNetFile, placeHolders);

        File netFile = fileUtility.provideTemporaryFile(prefix, ".net");
        writeLinesToFile(outcomes, netFile);

        File statFile = fileUtility.provideTemporaryFile(prefix, ".stat");
        List<String> statContent = new ArrayList<>(1);
        statContent.add(label);
        writeLinesToFile(statContent, statFile);

        List<File> model = new ArrayList<>(3);
        model.add(netFile);
        model.add(defFile);
        model.add(statFile);
        returnValue = new ImmutablePair<>(model, new ArrayList<>());
    }

    return returnValue;
}

From source file:com.nextdoor.bender.operation.conditional.ConditionalOperationTest.java

@Test
public void testFilterCondition() {
    List<Pair<FilterOperation, List<OperationProcessor>>> conditions = new ArrayList<Pair<FilterOperation, List<OperationProcessor>>>();
    /*/*  www. j a  va  2 s. c om*/
     * Case 1
     */
    List<OperationProcessor> case1Ops = new ArrayList<OperationProcessor>();
    BasicFilterOperationFactory fOp = new BasicFilterOperationFactory();
    BasicFilterOperationConfig fOpConf = new BasicFilterOperationConfig();
    fOpConf.setPass(false);
    fOp.setConf(fOpConf);

    case1Ops.add(new OperationProcessor(fOp));

    FilterOperation case1Filter = new BasicFilterOperation(true);
    conditions.add(new ImmutablePair<FilterOperation, List<OperationProcessor>>(case1Filter, case1Ops));

    ConditionalOperation op = new ConditionalOperation(conditions, false);

    /*
     * Create thread that supplies input events
     */
    Queue<InternalEvent> inputQueue = new Queue<InternalEvent>();
    supply(2, inputQueue);

    /*
     * Process
     */
    Stream<InternalEvent> input = inputQueue.stream();
    Stream<InternalEvent> output = op.getOutputStream(input);

    List<String> actual = output.map(m -> {
        return m.getEventObj().getPayload().toString();
    }).collect(Collectors.toList());

    assertEquals(0, actual.size());
}

From source file:fr.lirmm.graphik.graal.bench.homomorphism.InfHomomorphismBench.java

@Override
public CloseableIterator<Map.Entry<String, Query>> getQueries() {
    return new ConverterCloseableIterator<Query, Map.Entry<String, Query>>(
            new CloseableIteratorAdapter<Query>(queries.iterator()),
            new Converter<Query, Map.Entry<String, Query>>() {

                @Override/* w  ww  .  j ava2 s. c  o  m*/
                public Entry<String, Query> convert(Query object) {
                    if (object instanceof DefaultUnionOfConjunctiveQueries) {
                        return new ImmutablePair<String, Query>(
                                ((DefaultUnionOfConjunctiveQueries) object).getLabel(), object);
                    } else if (object instanceof ConjunctiveQuery) {
                        return new ImmutablePair<String, Query>(((ConjunctiveQuery) object).getLabel(), object);
                    } else {
                        return new ImmutablePair<String, Query>("", object);
                    }
                }

            });
}

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

@Test
public void testRemovedColumn() throws Exception {
    HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder().build();
    HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build();

    List<Record> records = new LinkedList<>();

    Map<String, Field> map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 1));
    map.put("removed", Field.create(Field.Type.STRING, "value"));
    Record record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);/*from  w w  w .  ja v  a 2  s  .c o  m*/

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 2));
    record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);

    processRecords(processor, hiveTarget, records);

    assertQueryResult("select * from tbl order by id", new QueryValidator() {
        @Override
        public void validateResultSet(ResultSet rs) throws Exception {
            assertResultSetStructure(rs, new ImmutablePair("tbl.id", Types.INTEGER),
                    new ImmutablePair("tbl.removed", Types.VARCHAR),
                    new ImmutablePair("tbl.dt", Types.VARCHAR));

            Assert.assertTrue("Table tbl doesn't contain any rows", rs.next());
            Assert.assertEquals(1, rs.getLong(1));
            Assert.assertEquals("value", rs.getString(2));

            Assert.assertTrue("Unexpected number of rows", rs.next());
            Assert.assertEquals(2, rs.getLong(1));
            Assert.assertEquals(null, rs.getString(2));

            Assert.assertFalse("Unexpected number of rows", rs.next());
        }
    });
}

From source file:fr.esrf.icat.manager.core.part.EntityEditDialog.java

@Override
protected Control createDialogArea(final Composite parent) {
    final Composite container = (Composite) super.createDialogArea(parent);
    GridLayout layout = new GridLayout(3, false);
    layout.marginRight = 5;/*from ww w.ja  va 2s  .  co  m*/
    layout.marginLeft = 10;
    container.setLayout(layout);
    comboMapping = new HashMap<>();
    fieldValues = new HashMap<>();
    // we are sure we have at least one entity, use the 1st one for anything general (field types, etc.)
    final WrappedEntityBean firstEntity = entities.get(0);
    for (final String field : firstEntity.getMutableFields()) {
        Label lblAuthn = new Label(container, SWT.NONE);
        lblAuthn.setText(StringUtils.capitalize(field) + ":");
        final Button checkEdit = new Button(container, SWT.CHECK);
        checkEdit.setEnabled(false);
        checkEdit.setVisible(false);
        final Class<?> clazz = firstEntity.getReturnType(field);
        Object initialValue = null;
        boolean notSet = true;
        for (WrappedEntityBean entity : entities) {
            try {
                Object value = entity.get(field);
                if (notSet) {
                    initialValue = value;
                    notSet = false;
                } else if ((null == value && null != initialValue)
                        || (null != value && !value.equals(initialValue))) {
                    initialValue = null;
                    checkEdit.setImage(MULTI_IMAGE);
                    checkEdit.setSelection(false);
                    checkEdit.setEnabled(true);
                    checkEdit.setVisible(true);
                    break;
                }
            } catch (Exception e) {
                LOG.error("Error getting initial value for " + field, e);
            }
        }
        final boolean hasInitialValue = initialValue != null;
        if (firstEntity.isEntity(field)) {
            final Combo combo = new Combo(container, SWT.DROP_DOWN | SWT.BORDER);
            new Label(container, SWT.NONE); //empty left label
            final Label label = new Label(container, SWT.RIGHT);
            label.setLayoutData(new GridData(SWT.END, SWT.CENTER, true, false));
            label.setImage(WARNING_IMAGE);
            final Label warningLabel = new Label(container, SWT.LEFT);
            warningLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, true, false));
            combo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
            final EntityListProposalContentProvider proposalProvider = new EntityListProposalContentProvider(
                    client, firstEntity.getReturnType(field).getSimpleName(), initialValue, label, warningLabel,
                    container);
            warningLabel.setText(proposalProvider.getCurrentFilter());
            final ContentProposalAdapter contentProposalAdapter = new ContentProposalAdapter(combo,
                    new ComboContentAdapter(), proposalProvider, DEFAULT_KEYSTROKE, DEFAULT_ACTIVATION_CHARS);
            contentProposalAdapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
            contentProposalAdapter.setPropagateKeys(true);
            contentProposalAdapter.setAutoActivationDelay(1000);
            contentProposalAdapter.addContentProposalListener(new IContentProposalListener2() {
                @Override
                public void proposalPopupOpened(ContentProposalAdapter adapter) {
                }

                @Override
                public void proposalPopupClosed(ContentProposalAdapter adapter) {
                    // when the proposal popup closes we set the content of the combo to the proposals
                    final String[] currentItems = proposalProvider.getCurrentItems();
                    if (currentItems != null && currentItems.length > 0) {
                        combo.setItems(currentItems);
                    }
                    final String currentText = proposalProvider.getCurrentText();
                    final int caretPosition = proposalProvider.getCaretPosition();
                    combo.setText(currentText);
                    combo.setSelection(new Point(caretPosition, caretPosition));
                }
            });
            combo.setItems(proposalProvider.getInitialItems());
            if (hasInitialValue) {
                combo.select(0);
            }
            comboMapping.put(field,
                    new ImmutablePair<Object[], Combo>(new Object[] { proposalProvider }, combo));
            if (checkEdit.isEnabled()) {
                combo.setEnabled(false);
                checkEdit.addSelectionListener(new SelectionAdapter() {
                    @Override
                    public void widgetSelected(SelectionEvent e) {
                        combo.setEnabled(checkEdit.getSelection());
                    }
                });
            }

        } else if (Enum.class.isAssignableFrom(clazz)) {
            final Combo combo = new Combo(container, SWT.DROP_DOWN | SWT.BORDER);
            final Object[] c = clazz.getEnumConstants();
            final String[] s = new String[c.length];
            int selected = -1;
            for (int i = 0; i < c.length; i++) {
                s[i] = c[i].toString();
                if (initialValue != null && c[i].equals(initialValue)) {
                    selected = i;
                }
            }
            // replacement for AutocompleteComboSelector to avoid selecting the 1st value in the combo when
            // no proposal is accepted (or field is emptied)
            new AutocompleteCombo(combo) {
                @Override
                protected AutocompleteContentProposalProvider getContentProposalProvider(String[] proposals) {
                    return new AutocompleteSelectorContentProposalProvider(proposals, this.combo);
                }

            };
            combo.setItems(s);
            if (selected >= 0) {
                combo.select(selected);
            }
            combo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
            comboMapping.put(field, new ImmutablePair<Object[], Combo>(c, combo));
            if (checkEdit.isEnabled()) {
                combo.setEnabled(false);
                checkEdit.addSelectionListener(new SelectionAdapter() {
                    @Override
                    public void widgetSelected(SelectionEvent e) {
                        combo.setEnabled(checkEdit.getSelection());
                    }
                });
            }

        } else if (clazz.equals(Boolean.class) || clazz.equals(boolean.class)) {
            final Button btn = new Button(container, SWT.CHECK);
            btn.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1));
            if (null == initialValue) {
                if (isSingle) {
                    try {
                        firstEntity.set(field, Boolean.FALSE);
                    } catch (Exception e) {
                        LOG.error("Error setting " + field + " to " + Boolean.FALSE);
                    }
                }
            } else {
                btn.setSelection((Boolean) initialValue);
            }
            btn.addSelectionListener(new SelectionAdapter() {
                @Override
                public void widgetSelected(SelectionEvent e) {
                    boolean value = btn.getSelection();
                    fieldValues.put(field, value);
                }
            });
            if (checkEdit.isEnabled()) {
                btn.setEnabled(false);
                checkEdit.addSelectionListener(new SelectionAdapter() {
                    @Override
                    public void widgetSelected(SelectionEvent e) {
                        final boolean selected = checkEdit.getSelection();
                        btn.setEnabled(selected);
                        if (selected) {
                            fieldValues.put(field, btn.getSelection());
                        } else {
                            fieldValues.remove(field);
                        }
                    }
                });
            }

        } else if (Calendar.class.isAssignableFrom(clazz) || Date.class.isAssignableFrom(clazz)
                || XMLGregorianCalendar.class.isAssignableFrom(clazz)) {

            final CDateTime cdt = new CDateTime(container,
                    CDT.BORDER | CDT.SPINNER | CDT.TAB_FIELDS | CDT.DATE_MEDIUM | CDT.TIME_MEDIUM);
            cdt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
            if (null != initialValue) {
                Date initialDate = null;
                if (initialValue instanceof Calendar) {
                    initialDate = ((Calendar) initialValue).getTime();
                } else if (initialValue instanceof XMLGregorianCalendar) {
                    initialDate = ((XMLGregorianCalendar) initialValue).toGregorianCalendar().getTime();
                } else if (initialValue instanceof Date) {
                    initialDate = (Date) initialValue;
                }
                cdt.setSelection(initialDate);
            }

            cdt.addSelectionListener(new SelectionAdapter() {
                @Override
                public void widgetSelected(SelectionEvent e) {
                    fieldValues.put(field, makeCorrectDateValue(clazz, cdt.getSelection()));
                }
            });
            if (checkEdit.isEnabled()) {
                cdt.setEnabled(false);
                checkEdit.addSelectionListener(new SelectionAdapter() {
                    @Override
                    public void widgetSelected(SelectionEvent e) {
                        final boolean selected = checkEdit.getSelection();
                        cdt.setEnabled(selected);
                        if (selected) {
                            fieldValues.put(field, makeCorrectDateValue(clazz, cdt.getSelection()));
                        } else {
                            fieldValues.remove(field);
                        }
                    }
                });
            }

        } else if (Number.class.isAssignableFrom(clazz)) {
            final Text text = new Text(container, SWT.BORDER);
            text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
            if (null != initialValue) {
                text.setText(initialValue.toString());
            }
            final Color original = text.getForeground();
            text.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    text.setForeground(original);
                    String value = text.getText();
                    if (null == value) {
                        value = ICATEntity.EMPTY_STRING;
                    }
                    final Object numVal = makeCorrectNumericValue(clazz, value);
                    if (null == numVal) {
                        text.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_RED));
                    } else {
                        fieldValues.put(field, numVal);
                    }
                }
            });
            if (checkEdit.isEnabled()) {
                text.setEnabled(false);
                checkEdit.addSelectionListener(new SelectionAdapter() {
                    @Override
                    public void widgetSelected(SelectionEvent e) {
                        final boolean selected = checkEdit.getSelection();
                        text.setEnabled(selected);
                        if (selected) {
                            fieldValues.put(field, makeCorrectNumericValue(clazz, text.getText()));
                        } else {
                            fieldValues.remove(field);
                        }
                    }
                });
            }

        } else { // Assumes String
            final Text text = new Text(container, SWT.BORDER);
            text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
            if (null == initialValue) {
                if (isSingle) {
                    try {
                        firstEntity.set(field, ICATEntity.EMPTY_STRING);
                    } catch (Exception e) {
                        LOG.error("Error setting " + field + " to EMPTY_STRING");
                    }
                }
            } else {
                text.setText(initialValue.toString());
            }
            text.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    String value = text.getText();
                    if (null == value) {
                        value = ICATEntity.EMPTY_STRING;
                    }
                    fieldValues.put(field, value);
                }
            });
            if (checkEdit.isEnabled()) {
                text.setEnabled(false);
                checkEdit.addSelectionListener(new SelectionAdapter() {
                    @Override
                    public void widgetSelected(SelectionEvent e) {
                        final boolean selected = checkEdit.getSelection();
                        text.setEnabled(selected);
                        if (selected) {
                            fieldValues.put(field, text.getText());
                        } else {
                            fieldValues.remove(field);
                        }
                    }
                });
            }
        }
    }
    return container;
}