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:malte0811.industrialWires.blocks.wire.TileEntityIC2ConnectorTin.java

public void transferPower() {
    Set<AbstractConnection> conns = new HashSet<>(
            ImmersiveNetHandler.INSTANCE.getIndirectEnergyConnections(pos, worldObj));
    Map<AbstractConnection, Pair<IIC2Connector, Double>> maxOutputs = new HashMap<>();
    double outputMax = Math.min(inBuffer, maxToNet);
    double sum = 0;
    for (AbstractConnection c : conns) {
        IImmersiveConnectable iic = ApiUtils.toIIC(c.end, worldObj);
        if (iic instanceof IIC2Connector) {
            double tmp = inBuffer - ((IIC2Connector) iic).insertEnergy(outputMax, true);
            if (tmp > .00000001) {
                maxOutputs.put(c, new ImmutablePair<>((IIC2Connector) iic, tmp));
                sum += tmp;//from  w ww  . j a  v a 2 s.co  m
            }
        }
    }
    if (sum < .0001) {
        return;
    }
    final double oldInBuf = outputMax;
    HashMap<Connection, Integer> transferedPerConn = ImmersiveNetHandler.INSTANCE
            .getTransferedRates(worldObj.provider.getDimension());
    for (AbstractConnection c : maxOutputs.keySet()) {
        Pair<IIC2Connector, Double> p = maxOutputs.get(c);
        double out = oldInBuf * p.getRight() / sum;
        double loss = getAverageLossRate(c);
        double inserted = out - p.getLeft().insertEnergy(out - loss, false);
        inBuffer -= inserted;
        float intermediaryLoss = 0;
        HashSet<IImmersiveConnectable> passedConnectors = new HashSet<>();
        double energyAtConn = inserted + loss;
        for (Connection sub : c.subConnections) {
            int transferredPerCon = transferedPerConn.containsKey(sub) ? transferedPerConn.get(sub) : 0;
            energyAtConn -= sub.cableType.getLossRatio() * sub.length;
            ImmersiveNetHandler.INSTANCE.getTransferedRates(worldObj.provider.getDimension()).put(sub,
                    (int) (transferredPerCon + energyAtConn));
            IImmersiveConnectable subStart = ApiUtils.toIIC(sub.start, worldObj);
            IImmersiveConnectable subEnd = ApiUtils.toIIC(sub.end, worldObj);
            if (subStart != null && passedConnectors.add(subStart))
                subStart.onEnergyPassthrough((int) (inserted - inserted * intermediaryLoss));
            if (subEnd != null && passedConnectors.add(subEnd))
                subEnd.onEnergyPassthrough((int) (inserted - inserted * intermediaryLoss));
        }
    }
}

From source file:com.robertsmieja.test.utils.junit.GettersAndSettersUtils.java

static ImmutablePair<Method, Method> getGetterAndSetterForField(Field field) {
    Method getter = MethodUtils.getAccessibleMethod(field.getDeclaringClass(),
            accessorMethodNameForField(GettersAndSettersTests.IS_METHOD_PREFIX, field));
    if (getter == null) {
        getter = MethodUtils.getAccessibleMethod(field.getDeclaringClass(),
                accessorMethodNameForField(GettersAndSettersTests.GET_METHOD_PREFIX, field));
    }/*  w ww. j  av  a 2 s  .  c o m*/
    if (getter == null) {
        failToFindMethodForField(field,
                accessorMethodNameForField(GettersAndSettersTests.GET_METHOD_PREFIX, field));
    }
    Method setter = getSetterForField(field);
    if (setter == null) {
        failToFindMethodForField(field,
                accessorMethodNameForField(GettersAndSettersTests.SET_METHOD_PREFIX, field));
    }
    return new ImmutablePair<>(getter, setter);
}

From source file:com.netflix.bdp.inviso.history.TraceService.java

/**
 * Returns a json object representing the job history.
 *
 * @param jobId/*ww w  .j  a va2  s.  c  om*/
 * @param path Use the given path as opposed to the history locator
 * @param summary Return just the top level details of the job
 * @param counters Include counters
 * @return Json string
 * @throws Exception
 */
@Path("load/{jobId}")
@GET
@Produces("application/json")
public String trace(@PathParam("jobId") final String jobId, @QueryParam("path") final String path,
        @QueryParam("summary") boolean summary, @QueryParam("counters") @DefaultValue("true") boolean counters)
        throws Exception {

    Pair<org.apache.hadoop.fs.Path, org.apache.hadoop.fs.Path> historyPath;

    if (path != null) {
        historyPath = new ImmutablePair<>(null, new org.apache.hadoop.fs.Path(path));
    } else {
        historyPath = historyLocator.locate(jobId);
    }

    if (historyPath == null) {
        throw new WebApplicationException(404);
    }

    TraceJobHistoryLoader loader = new TraceJobHistoryLoader(properties);

    FileSystem fs = FileSystem.get(historyPath.getRight().toUri(), config);
    CompressionCodec codec = new CompressionCodecFactory(config).getCodec(historyPath.getRight());

    FSDataInputStream fin = fs.open(historyPath.getRight());

    if (codec != null) {
        fin = new FSDataInputStream(new WrappedCompressionInputStream(codec.createInputStream(fin)));
    }

    JobHistoryParser parser = new JobHistoryParser(fin);
    parser.parse(loader);

    String[] ignore = { "counters" };

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule("MyModule", new Version(1, 0, 0, null));

    //Job
    JavaType jobMapType = MapLikeType.construct(Job.class, SimpleType.construct(String.class),
            SimpleType.construct(Object.class));
    module.addSerializer(Job.class, MapSerializer.construct(ignore, jobMapType, false, null, null, null, null));

    //Task
    JavaType taskMapType = MapLikeType.construct(Task.class, SimpleType.construct(String.class),
            SimpleType.construct(Object.class));
    module.addSerializer(Task.class,
            MapSerializer.construct(ignore, taskMapType, false, null, null, null, null));

    //Attempt
    JavaType attemptMapType = MapLikeType.construct(TaskAttempt.class, SimpleType.construct(String.class),
            SimpleType.construct(Object.class));
    module.addSerializer(TaskAttempt.class,
            MapSerializer.construct(ignore, attemptMapType, false, null, null, null, null));

    if (!counters) {
        mapper.registerModule(module);
    }

    if (summary) {
        loader.getJob().clearTasks();
    }

    return mapper.writeValueAsString(loader.getJob());
}

From source file:com.uber.hoodie.utilities.sources.HiveIncrPullSource.java

@Override
public Pair<Optional<JavaRDD<GenericRecord>>, String> fetchNewData(Optional<String> lastCheckpointStr,
        long maxInputBytes) {
    try {//from  w w w . j a  v  a2s  .  c o m
        // find the source commit to pull
        Optional<String> commitToPull = findCommitToPull(lastCheckpointStr);

        if (!commitToPull.isPresent()) {
            return new ImmutablePair<>(Optional.empty(),
                    lastCheckpointStr.isPresent() ? lastCheckpointStr.get() : "");
        }

        // read the files out.
        List<FileStatus> commitDeltaFiles = Arrays
                .asList(fs.listStatus(new Path(incrPullRootPath, commitToPull.get())));
        String pathStr = commitDeltaFiles.stream().map(f -> f.getPath().toString())
                .collect(Collectors.joining(","));
        String schemaStr = schemaProvider.getSourceSchema().toString();
        final AvroConvertor avroConvertor = new AvroConvertor(schemaStr);
        return new ImmutablePair<>(
                Optional.of(DFSSource.fromFiles(dataFormat, avroConvertor, pathStr, sparkContext)),
                String.valueOf(commitToPull.get()));
    } catch (IOException ioe) {
        throw new HoodieIOException("Unable to read from source from checkpoint: " + lastCheckpointStr, ioe);
    }
}

From source file:com.conversantmedia.mapreduce.tool.annotation.handler.NamedOutputAnnotationHandler.java

/**
 * If this is a multiple output we're annotating, see if there are type parameters to
 * use for the key/value classes./*from  w w w .  j  a va 2s  . c  om*/
 * 
 * @param target   object to reflect for type params
 * @return         the key/value type parameters
 */
protected Pair<Type, Type> getGenericTypeParams(Object target) {
    Pair<Type, Type> kvTypePair = null;
    if (target instanceof Field) {
        Field field = (Field) target;
        if (field.getType() == MultipleOutputs.class) {
            Type genericType = field.getGenericType();
            if (genericType instanceof ParameterizedType) {
                Type[] keyValueTypes = ((ParameterizedType) genericType).getActualTypeArguments();
                if (keyValueTypes != null && keyValueTypes.length == 2) {
                    kvTypePair = new ImmutablePair<>(keyValueTypes[0], keyValueTypes[1]);
                }
            }
        }
    }
    return kvTypePair;
}

From source file:gov.gtas.repository.CaseDispositionRepositoryImpl.java

@Override
public Pair<Long, List<Case>> findByCriteria(CaseRequestDto dto) {

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Case> q = cb.createQuery(Case.class);
    Root<Case> root = q.from(Case.class);
    List<Predicate> predicates = new ArrayList<>();

    TypedQuery<Case> typedQuery = em.createQuery(q);

    // sorting// w w w. j  a va2 s.  c  o m
    if (dto.getSort() != null) {
        List<Order> orders = new ArrayList<>();
        for (SortOptionsDto sort : dto.getSort()) {
            Expression<?> e = root.get(sort.getColumn());
            Order order;
            if ("desc".equalsIgnoreCase(sort.getDir())) {
                order = cb.desc(e);
            } else {
                order = cb.asc(e);
            }
            orders.add(order);
        }
        q.orderBy(orders);
    }

    if (dto.getFlightId() != null) {
        predicates.add(cb.equal(root.<Long>get("flightId"), dto.getFlightId()));
    }

    if (dto.getPaxId() != null) {
        predicates.add(cb.equal(root.<Long>get("paxId"), dto.getPaxId()));
    }

    if (dto.getPaxName() != null) {
        String likeString = String.format("%%%s%%", dto.getPaxName().toUpperCase());
        predicates.add(cb.like(root.<String>get("paxName"), likeString));
    }

    if (dto.getLastName() != null) { // map this to full pax name
        String likeString = String.format("%%%s%%", dto.getLastName().toUpperCase());
        predicates.add(cb.like(root.<String>get("paxName"), likeString));
    }

    if (dto.getStatus() != null) {
        String likeString = String.format("%%%s%%", dto.getStatus().toUpperCase());
        predicates.add(cb.like(root.<String>get("status"), likeString));
    }

    if (dto.getFlightNumber() != null) {
        predicates.add(cb.equal(root.<Long>get("flightNumber"), dto.getFlightNumber()));
    }

    if (dto.getRuleCatId() != null) {
        predicates.add(cb.equal(root.<Long>get("highPriorityRuleCatId"), dto.getRuleCatId()));
    }

    Predicate etaCondition;
    if (dto.getEtaStart() != null && dto.getEtaEnd() != null) {

        Path<Date> eta = root.<Date>get("flightETADate");
        Predicate startPredicate = cb.or(cb.isNull(eta), cb.greaterThanOrEqualTo(eta, dto.getEtaStart()));
        Predicate endPredicate = cb.or(cb.isNull(eta), cb.lessThanOrEqualTo(eta, dto.getEtaEnd()));
        etaCondition = cb.and(startPredicate, endPredicate);
        predicates.add(etaCondition);
    }

    q.select(root).where(predicates.toArray(new Predicate[] {}));
    typedQuery = em.createQuery(q);

    // total count
    CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
    countQuery.select(cb.count(countQuery.from(Case.class))).where(predicates.toArray(new Predicate[] {}));
    Long count = em.createQuery(countQuery).getSingleResult();

    // pagination
    int pageNumber = dto.getPageNumber();
    int pageSize = dto.getPageSize();
    int firstResultIndex = (pageNumber - 1) * pageSize;
    typedQuery.setFirstResult(firstResultIndex);
    typedQuery.setMaxResults(dto.getPageSize());

    logger.debug(typedQuery.unwrap(org.hibernate.Query.class).getQueryString());
    List<Case> results = typedQuery.getResultList();

    return new ImmutablePair<>(count, results);

}

From source file:com.romeikat.datamessie.core.processing.service.stemming.text.TextStemmer.java

private Pair<String, String> getReplacingAndReplacement(final SharedSessionContract ssc,
        final String namedEntityName) {
    final String replacing = namedEntityName;
    final String replacement = NamedEntity.getAsSingleWord(namedEntityName);
    // Return the replacement, if different
    if (replacement.equals(replacing)) {
        return null;
    }//w w  w .ja  va  2s . c  om
    return new ImmutablePair<String, String>(replacing, replacement);
}

From source file:models.Index.java

/**
 * @return The locations of the local and public JSON-LD contexts.
 * @throws MalformedURLException If the constructed URL is malformed.
 *//*from   w ww.java 2  s  .c o  m*/
public Pair<URL, String> context() throws MalformedURLException {
    final String path = "conf/contexts";
    final String file = id + ".json";
    URL localContextResourceUrl = Play.application().resource("/" + path + "/" + file);
    if (localContextResourceUrl == null) // no app running, use plain local file
        localContextResourceUrl = new File(path, file).toURI().toURL();
    final String publicContextUrl = CONFIG.getString("application.url")
            + controllers.routes.Api.context(file).url();
    return new ImmutablePair<>(localContextResourceUrl, publicContextUrl);
}

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

@Test
public void testNewColumn() 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));
    Record record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);/*  w  ww .ja  va  2s. c  o  m*/

    map = new LinkedHashMap<>();
    map.put("id", Field.create(Field.Type.INTEGER, 2));
    map.put("new_column", Field.create(Field.Type.STRING, "new value"));
    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.new_column", 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(null, rs.getString(2));

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

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

From source file:com.ottogroup.bi.streaming.operator.json.insert.JsonStaticContentInsertionTest.java

/**
 * Test case for {@link JsonStaticContentInsertion#JsonStaticContentInsertion(java.util.List)} being provided a
 * configuration which holds an element that is missing the insertion value
 *///from   w  w w  . j  a  v a 2s.  co  m
@Test(expected = IllegalArgumentException.class)
public void testConstructor_withNullInsertionValue() throws Exception {
    List<Pair<JsonContentReference, Serializable>> values = new ArrayList<>();
    values.add(new ImmutablePair<JsonContentReference, Serializable>(
            new JsonContentReference(new String[] { "valid" }, JsonContentType.STRING), null));
    new JsonStaticContentInsertion(values);
}