Example usage for org.apache.commons.lang3.tuple Pair getValue

List of usage examples for org.apache.commons.lang3.tuple Pair getValue

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple Pair getValue.

Prototype

@Override
public R getValue() 

Source Link

Document

Gets the value from this pair.

This method implements the Map.Entry interface returning the right element as the value.

Usage

From source file:com.linkedin.pinot.routing.builder.GeneratorBasedRoutingTableBuilder.java

@Override
public List<ServerToSegmentSetMap> computeRoutingTableFromExternalView(String tableName,
        ExternalView externalView, List<InstanceConfig> instanceConfigList) {
    // The default routing table algorithm tries to balance all available segments across all servers, so that each
    // server is hit on every query. This works fine with small clusters (say less than 20 servers) but for larger
    // clusters, this adds up to significant overhead (one request must be enqueued for each server, processed,
    // returned, deserialized, aggregated, etc.).
    ////from w w  w.  ja va 2  s  . c o m
    // For large clusters, we want to avoid hitting every server, as this also has an adverse effect on client tail
    // latency. This is due to the fact that a query cannot return until it has received a response from each server,
    // and the greater the number of servers that are hit, the more likely it is that one of the servers will be a
    // straggler (eg. due to contention for query processing threads, GC, etc.). We also want to balance the segments
    // within any given routing table so that each server in the routing table has approximately the same number of
    // segments to process.
    //
    // To do so, we have a routing table generator that generates routing tables by picking a random subset of servers.
    // With this set of servers, we check if the set of segments served by these servers is complete. If the set of
    // segments served does not cover all of the segments, we compute the list of missing segments and pick a random
    // server that serves these missing segments until we have complete coverage of all the segments.
    //
    // We then order the segments in ascending number of replicas within our server set, in order to allocate the
    // segments with fewer replicas first. This ensures that segments that are 'easier' to allocate are more likely to
    // end up on a replica with fewer segments.
    //
    // Then, we pick a random replica for each segment, iterating from fewest replicas to most replicas, inversely
    // weighted by the number of segments already assigned to that replica. This ensures that we build a routing table
    // that's as even as possible.
    //
    // The algorithm to generate a routing table is thus:
    // 1. Compute the inverse external view, a mapping of servers to segments
    // 2. For each routing table to generate:
    //   a) Pick TARGET_SERVER_COUNT_PER_QUERY distinct servers
    //   b) Check if the server set covers all the segments; if not, add additional servers until it does.
    //   c) Order the segments in our server set in ascending order of number of replicas present in our server set
    //   d) For each segment, pick a random replica with proper weighting
    //   e) Return that routing table
    //
    // Given that we can generate routing tables at will, we then generate many routing tables and use them to optimize
    // according to two criteria: the variance in workload per server for any individual table as well as the variance
    // in workload per server across all the routing tables. To do so, we generate an initial set of routing tables
    // according to a per-routing table metric and discard the worst routing tables.

    RoutingTableGenerator routingTableGenerator = buildRoutingTableGenerator();
    routingTableGenerator.init(externalView, instanceConfigList);

    PriorityQueue<Pair<Map<String, Set<String>>, Float>> topRoutingTables = new PriorityQueue<>(
            ROUTING_TABLE_COUNT, new Comparator<Pair<Map<String, Set<String>>, Float>>() {
                @Override
                public int compare(Pair<Map<String, Set<String>>, Float> left,
                        Pair<Map<String, Set<String>>, Float> right) {
                    // Float.compare sorts in ascending order and we want a max heap, so we need to return the negative of the comparison
                    return -Float.compare(left.getValue(), right.getValue());
                }
            });

    for (int i = 0; i < ROUTING_TABLE_COUNT; i++) {
        topRoutingTables.add(generateRoutingTableWithMetric(routingTableGenerator));
    }

    // Generate routing more tables and keep the ROUTING_TABLE_COUNT top ones
    for (int i = 0; i < (ROUTING_TABLE_GENERATION_COUNT - ROUTING_TABLE_COUNT); ++i) {
        Pair<Map<String, Set<String>>, Float> newRoutingTable = generateRoutingTableWithMetric(
                routingTableGenerator);
        Pair<Map<String, Set<String>>, Float> worstRoutingTable = topRoutingTables.peek();

        // If the new routing table is better than the worst one, keep it
        if (newRoutingTable.getRight() < worstRoutingTable.getRight()) {
            topRoutingTables.poll();
            topRoutingTables.add(newRoutingTable);
        }
    }

    // Return the best routing tables
    List<ServerToSegmentSetMap> routingTables = new ArrayList<>(topRoutingTables.size());
    while (!topRoutingTables.isEmpty()) {
        Pair<Map<String, Set<String>>, Float> routingTableWithMetric = topRoutingTables.poll();
        routingTables.add(new ServerToSegmentSetMap(routingTableWithMetric.getKey()));
    }

    return routingTables;
}

From source file:it.anyplace.sync.client.SyncthingClient.java

public FileDownloadObserver pullFile(String folder, String path) throws InterruptedException {
    BlockExchangeConnectionHandler connectionHandler = getConnectionForFolder(folder);
    Pair<FileInfo, FileBlocks> fileInfoAndBlocks = indexHandler.waitForRemoteIndexAquired(connectionHandler)
            .getFileInfoAndBlocksByPath(folder, path);
    checkNotNull(fileInfoAndBlocks, "file not found in local index for folder = %s path = %s", folder, path);
    return new BlockPuller(configuration, connectionHandler, true).pullBlocks(fileInfoAndBlocks.getValue());
}

From source file:com.cisco.oss.foundation.http.AbstractHttpClient.java

private List<InternalServerProxy> updateServerListBasedOnConfig(final List<InternalServerProxy> serversList,
        final InternalServerProxyMetadata metadata) {

    // iterate host and port pairs and create ad new servers to the server
    // list./* www.j  av a2  s  .c om*/
    for (Pair<String, Integer> hostPort : metadata.getHostAndPortPairs()) {

        final String hostEntry = hostPort.getKey();
        final int portEntry = hostPort.getValue();

        final InternalServerProxy internalServerProxy = createInternalServerProxy(metadata, hostEntry,
                portEntry);
        serversList.add(internalServerProxy);
    }

    return serversList;
}

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

@Override
public void process(Annotation annotation, Job job, Object target) throws ToolException {
    NamedOutput namedOut = (NamedOutput) annotation;
    KeyValue kv = namedOut.type();

    // If this is a MultipleOutputs member we're annotating, see if we can't
    // get the key/value from the parameters if there are any.
    Pair<Type, Type> kvTypePair = getGenericTypeParams(target);

    Class<?> keyClass = kv.key();
    if (keyClass == void.class) {
        if (kvTypePair != null) {
            keyClass = (Class<?>) kvTypePair.getKey();
        } else {//from  w  w  w.j av  a 2 s. c  o m
            // fall back on job output key class
            keyClass = job.getOutputKeyClass();
        }
    }

    Class<?> valueClass = kv.value();
    if (valueClass == void.class) {
        if (kvTypePair != null) {
            valueClass = (Class<?>) kvTypePair.getValue();
        } else {
            valueClass = job.getOutputValueClass();
        }
    }

    String[] names = getNames(namedOut);
    for (String name : names) {
        name = (String) evaluateExpression(name);
        if (!configured.contains(name)) {
            MultipleOutputs.addNamedOutput(job, name, namedOut.format(), keyClass, valueClass);
            MultipleOutputs.setCountersEnabled(job, namedOut.countersEnabled());
            configured.add(name);
        }
    }
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdController.java

private byte[] createRequestXml(String action, ImmutablePair<String, String>... params) {
    try {/*from  ww  w .  j a va 2s .c o  m*/
        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage soapMessage = factory.createMessage();

        SOAPBodyElement actionElement = soapMessage.getSOAPBody().addBodyElement(new QName(null, action, "m"));
        actionElement.addNamespaceDeclaration("m", serviceType);

        for (Pair<String, String> param : params) {
            SOAPElement paramElement = actionElement.addChildElement(QName.valueOf(param.getKey()));
            paramElement.setValue(param.getValue());
        }

        soapMessage.getSOAPPart().setXmlStandalone(true);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(new DOMSource(soapMessage.getSOAPPart()), new StreamResult(baos));

        return baos.toByteArray();
    } catch (IllegalArgumentException | SOAPException | TransformerException | DOMException e) {
        throw new IllegalStateException(e); // should never happen
    }
}

From source file:com.linkedin.pinot.broker.routing.builder.GeneratorBasedRoutingTableBuilder.java

@Override
public void computeRoutingTableFromExternalView(String tableName, ExternalView externalView,
        List<InstanceConfig> instanceConfigs) {
    // The default routing table algorithm tries to balance all available segments across all servers, so that each
    // server is hit on every query. This works fine with small clusters (say less than 20 servers) but for larger
    // clusters, this adds up to significant overhead (one request must be enqueued for each server, processed,
    // returned, deserialized, aggregated, etc.).
    ////from   w w  w  .j  a  v a  2s  .com
    // For large clusters, we want to avoid hitting every server, as this also has an adverse effect on client tail
    // latency. This is due to the fact that a query cannot return until it has received a response from each server,
    // and the greater the number of servers that are hit, the more likely it is that one of the servers will be a
    // straggler (eg. due to contention for query processing threads, GC, etc.). We also want to balance the segments
    // within any given routing table so that each server in the routing table has approximately the same number of
    // segments to process.
    //
    // To do so, we have a routing table generator that generates routing tables by picking a random subset of servers.
    // With this set of servers, we check if the set of segments served by these servers is complete. If the set of
    // segments served does not cover all of the segments, we compute the list of missing segments and pick a random
    // server that serves these missing segments until we have complete coverage of all the segments.
    //
    // We then order the segments in ascending number of replicas within our server set, in order to allocate the
    // segments with fewer replicas first. This ensures that segments that are 'easier' to allocate are more likely to
    // end up on a server with fewer segments.
    //
    // Then, we pick a server with least segments already assigned for each segment. This ensures that we build a
    // routing table that's as even as possible.
    //
    // The algorithm to generate a routing table is thus:
    // 1. Compute the inverse external view, a mapping of servers to segments
    // 2. For each routing table to generate:
    //   a) Pick _targetNumServersPerQuery distinct servers
    //   b) Check if the server set covers all the segments; if not, add additional servers until it does
    //   c) Order the segments in our server set in ascending order of number of replicas present in our server set
    //   d) For each segment, pick a server with least segments already assigned
    //   e) Return that routing table
    //
    // Given that we can generate routing tables at will, we then generate many routing tables and use them to optimize
    // according to two criteria: the variance in workload per server for any individual table as well as the variance
    // in workload per server across all the routing tables. To do so, we generate an initial set of routing tables
    // according to a per-routing table metric and discard the worst routing tables.

    RoutingTableGenerator routingTableGenerator = buildRoutingTableGenerator();
    routingTableGenerator.init(externalView, instanceConfigs);

    PriorityQueue<Pair<Map<String, List<String>>, Float>> topRoutingTables = new PriorityQueue<>(
            ROUTING_TABLE_COUNT, new Comparator<Pair<Map<String, List<String>>, Float>>() {
                @Override
                public int compare(Pair<Map<String, List<String>>, Float> left,
                        Pair<Map<String, List<String>>, Float> right) {
                    // Float.compare sorts in ascending order and we want a max heap, so we need to return the negative of the comparison
                    return -Float.compare(left.getValue(), right.getValue());
                }
            });

    for (int i = 0; i < ROUTING_TABLE_COUNT; i++) {
        topRoutingTables.add(generateRoutingTableWithMetric(routingTableGenerator));
    }

    // Generate routing more tables and keep the ROUTING_TABLE_COUNT top ones
    for (int i = 0; i < (ROUTING_TABLE_GENERATION_COUNT - ROUTING_TABLE_COUNT); ++i) {
        Pair<Map<String, List<String>>, Float> newRoutingTable = generateRoutingTableWithMetric(
                routingTableGenerator);
        Pair<Map<String, List<String>>, Float> worstRoutingTable = topRoutingTables.peek();

        // If the new routing table is better than the worst one, keep it
        if (newRoutingTable.getRight() < worstRoutingTable.getRight()) {
            topRoutingTables.poll();
            topRoutingTables.add(newRoutingTable);
        }
    }

    // Return the best routing tables
    List<Map<String, List<String>>> routingTables = new ArrayList<>(topRoutingTables.size());
    while (!topRoutingTables.isEmpty()) {
        routingTables.add(topRoutingTables.poll().getKey());
    }

    setRoutingTables(routingTables);
}

From source file:massbank.Record.java

public String toString() {
    StringBuilder sb = new StringBuilder();

    sb.append("ACCESSION: " + ACCESSION() + "\n");
    sb.append("RECORD_TITLE: " + RECORD_TITLE() + "\n");
    sb.append("DATE: " + DATE() + "\n");
    sb.append("AUTHORS: " + AUTHORS() + "\n");
    sb.append("LICENSE: " + LICENSE() + "\n");
    if (COPYRIGHT() != null)
        sb.append("COPYRIGHT: " + COPYRIGHT() + "\n");
    if (PUBLICATION() != null)
        sb.append("PUBLICATION: " + PUBLICATION() + "\n");
    if (COMMENT() != null) {
        for (String comment : COMMENT())
            sb.append("COMMENT: " + comment + "\n");
    }/*w  w  w . ja  va  2  s.  c om*/
    if (CH_NAME() != null) {
        for (String ch_name : CH_NAME())
            sb.append("CH$NAME: " + ch_name + "\n");
    }
    sb.append("CH$COMPOUND_CLASS: " + CH_COMPOUND_CLASS() + "\n");
    sb.append("CH$FORMULA: " + CH_FORMULA() + "\n");
    sb.append("CH$EXACT_MASS: " + CH_EXACT_MASS() + "\n");
    try {
        sb.append("CH$SMILES: " + CH_SMILES() + "\n");
    } catch (CDKException e) {
        System.err.println(e.getMessage());
        sb.append("CH$SMILES: null\n");
    }
    try {
        sb.append("CH$IUPAC: " + CH_IUPAC() + "\n");
    } catch (CDKException e) {
        System.err.println(e.getMessage());
        sb.append("CH$IUPAC: null\n");
    }
    if (CH_LINK() != null) {
        for (Pair<String, String> link : CH_LINK())
            sb.append("CH$LINK: " + link.getKey() + " " + link.getValue() + "\n");
    }
    if (SP_SCIENTIFIC_NAME() != null)
        sb.append("SP$SCIENTIFIC_NAME: " + SP_SCIENTIFIC_NAME() + "\n");
    if (SP_LINEAGE() != null)
        sb.append("SP$LINEAGE: " + SP_LINEAGE() + "\n");
    if (SP_LINK() != null) {
        for (Pair<String, String> link : SP_LINK())
            sb.append("SP$LINK: " + link.getKey() + " " + link.getValue() + "\n");
    }
    if (SP_SAMPLE() != null) {
        for (String sample : SP_SAMPLE())
            sb.append("SP$SAMPLE: " + sample + "\n");
    }
    sb.append("AC$INSTRUMENT: " + AC_INSTRUMENT() + "\n");
    sb.append("AC$INSTRUMENT_TYPE: " + AC_INSTRUMENT_TYPE().toString() + "\n");
    sb.append("AC$MASS_SPECTROMETRY: MS_TYPE: " + AC_MASS_SPECTROMETRY_MS_TYPE() + "\n");
    sb.append("AC$MASS_SPECTROMETRY: ION_MODE: " + AC_MASS_SPECTROMETRY_ION_MODE() + "\n");
    if (AC_MASS_SPECTROMETRY() != null) {
        for (Pair<String, String> ac_mass_spectrometry : AC_MASS_SPECTROMETRY())
            sb.append("AC$MASS_SPECTROMETRY: " + ac_mass_spectrometry.getKey() + " "
                    + ac_mass_spectrometry.getValue() + "\n");
    }
    if (AC_CHROMATOGRAPHY() != null) {
        for (Pair<String, String> ac_chromatography : AC_CHROMATOGRAPHY())
            sb.append("AC$CHROMATOGRAPHY: " + ac_chromatography.getKey() + " " + ac_chromatography.getValue()
                    + "\n");
    }
    if (MS_FOCUSED_ION() != null) {
        for (Pair<String, String> ms_focued_ion : MS_FOCUSED_ION())
            sb.append("MS$FOCUSED_ION: " + ms_focued_ion.getKey() + " " + ms_focued_ion.getValue() + "\n");
    }
    if (MS_DATA_PROCESSING() != null) {
        for (Pair<String, String> ms_data_processing : MS_DATA_PROCESSING())
            sb.append("MS$DATA_PROCESSING: " + ms_data_processing.getKey() + " " + ms_data_processing.getValue()
                    + "\n");
    }
    sb.append("PK$SPLASH: " + PK_SPLASH() + "\n");

    if (PK_ANNOTATION_HEADER() != null) {
        sb.append("PK$ANNOTATION:");
        for (String annotation_header_item : PK_ANNOTATION_HEADER())
            sb.append(" " + annotation_header_item);
        sb.append("\n");
        for (List<String> annotation_line : PK_ANNOTATION()) {
            sb.append(" ");
            for (String annotation_item : annotation_line)
                sb.append(" " + annotation_item);
            sb.append("\n");
        }
    }

    sb.append("PK$NUM_PEAK: " + PK_NUM_PEAK() + "\n");
    sb.append("PK$PEAK: m/z int. rel.int.\n");
    for (List<Double> peak_line : PK_PEAK()) {
        sb.append(" ");
        for (Double peak_line_item : peak_line)
            sb.append(" " + peak_line_item.toString());
        sb.append("\n");
    }

    /*
     * // PK$ANNOTATION: m/z tentative_formula formula_count mass error(ppm) //
     * 57.0701 C4H9+ 1 57.0699 4.61 // 67.0542 C5H7+ 1 67.0542 0.35 // 69.0336
     * C4H5O+ 1 69.0335 1.14 sb.append("PK$NUM_PEAK: " + this.PK$PEAK_MZ.length +
     * "\n"); sb.append("PK$PEAK: m/z int. rel.int." + "\n"); for(int idx = 0; idx <
     * this.PK$PEAK_MZ.length; idx++) sb.append("  " + this.PK$PEAK_MZ[idx] + " " +
     * this.PK$PEAK_INT[idx] + " " + this.PK$PEAK_REL[idx] + "\n");
     */
    sb.append("//");

    return sb.toString();
}

From source file:com.microsoft.azure.storage.table.TableEncryptionPolicy.java

/**
 * Return an encrypted entity. This method is used for encrypting entity properties.
 *///from  ww w.  ja va 2s  .  co  m
Map<String, EntityProperty> encryptEntity(Map<String, EntityProperty> properties, String partitionKey,
        String rowKey, EncryptionResolver encryptionResolver) throws StorageException {
    Utility.assertNotNull("properties", properties);

    // The Key should be set on the policy for encryption. Otherwise, throw an error.
    if (this.keyWrapper == null) {
        throw new IllegalArgumentException(SR.KEY_MISSING);
    }

    EncryptionData encryptionData = new EncryptionData();
    encryptionData.setEncryptionAgent(new EncryptionAgent(Constants.EncryptionConstants.ENCRYPTION_PROTOCOL_V1,
            EncryptionAlgorithm.AES_CBC_256));

    try {
        Map<String, EntityProperty> encryptedProperties = new HashMap<String, EntityProperty>();
        HashSet<String> encryptionPropertyDetailsSet = new HashSet<String>();

        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256);

        Cipher myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKey aesKey = keyGen.generateKey();
        myAes.init(Cipher.ENCRYPT_MODE, aesKey);

        // Wrap key
        Pair<byte[], String> encryptedKey = this.keyWrapper
                .wrapKeyAsync(aesKey.getEncoded(), null /* algorithm */).get();
        encryptionData.setWrappedContentKey(new WrappedContentKey(this.keyWrapper.getKid(),
                encryptedKey.getKey(), encryptedKey.getValue()));

        encryptionData.setContentEncryptionIV(myAes.getIV());

        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        for (Map.Entry<String, EntityProperty> kvp : properties.entrySet()) {
            if (encryptionResolver != null
                    && encryptionResolver.encryptionResolver(partitionKey, rowKey, kvp.getKey())) {
                // Throw if users try to encrypt null properties. This could happen in the DynamicTableEntity case
                // where a user adds a new property as follows - ent.Properties.Add("foo2", null);
                if (kvp.getValue() == null) {
                    throw new IllegalArgumentException(SR.ENCRYPTING_NULL_PROPERTIES_NOT_ALLOWED);
                }

                kvp.getValue().setIsEncrypted(true);
            }

            // IsEncrypted is set to true when either the EncryptPropertyAttribute is set on a property or when it is 
            // specified in the encryption resolver or both.
            if (kvp.getValue() != null && kvp.getValue().isEncrypted()) {
                // Throw if users try to encrypt non-string properties.
                if (kvp.getValue().getEdmType() != EdmType.STRING) {
                    throw new IllegalArgumentException(String
                            .format(SR.UNSUPPORTED_PROPERTY_TYPE_FOR_ENCRYPTION, kvp.getValue().getEdmType()));
                }

                byte[] columnIVFull = digest
                        .digest(Utility.binaryAppend(encryptionData.getContentEncryptionIV(),
                                (partitionKey + rowKey + kvp.getKey()).getBytes(Constants.UTF8_CHARSET)));

                byte[] columnIV = new byte[16];
                System.arraycopy(columnIVFull, 0, columnIV, 0, 16);
                myAes.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(columnIV));

                // Throw if users try to encrypt null properties. This could happen in the DynamicTableEntity or POCO
                // case when the property value is null.
                if (kvp.getValue() == null) {
                    throw new IllegalArgumentException(SR.ENCRYPTING_NULL_PROPERTIES_NOT_ALLOWED);
                }

                byte[] src = kvp.getValue().getValueAsString().getBytes(Constants.UTF8_CHARSET);
                byte[] dest = myAes.doFinal(src, 0, src.length);

                // Store the encrypted properties as binary values on the service instead of base 64 encoded strings because strings are stored as a sequence of 
                // WCHARs thereby further reducing the allowed size by half. During retrieve, it is handled by the response parsers correctly 
                // even when the service does not return the type for JSON no-metadata.
                encryptedProperties.put(kvp.getKey(), new EntityProperty(dest));
                encryptionPropertyDetailsSet.add(kvp.getKey());
            } else {
                encryptedProperties.put(kvp.getKey(), kvp.getValue());
            }

            // Encrypt the property details set and add it to entity properties.
            byte[] metadataIVFull = digest.digest(Utility.binaryAppend(encryptionData.getContentEncryptionIV(),
                    (partitionKey + rowKey + Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS)
                            .getBytes(Constants.UTF8_CHARSET)));

            byte[] metadataIV = new byte[16];
            System.arraycopy(metadataIVFull, 0, metadataIV, 0, 16);
            myAes.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(metadataIV));

            byte[] src = Arrays.toString(encryptionPropertyDetailsSet.toArray())
                    .getBytes(Constants.UTF8_CHARSET);
            byte[] dest = myAes.doFinal(src, 0, src.length);
            encryptedProperties.put(Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS,
                    new EntityProperty(dest));
        }

        encryptedProperties.put(Constants.EncryptionConstants.TABLE_ENCRYPTION_KEY_DETAILS,
                new EntityProperty(encryptionData.serialize()));

        return encryptedProperties;
    } catch (Exception e) {
        throw StorageException.translateClientException(e);
    }
}

From source file:com.epam.ngb.cli.manager.command.handler.http.FileRegistrationHandler.java

private RegistrationRequest createRegistrationRequest(Pair<String, String> file,
        BiologicalDataItemFormat format) {
    RegistrationRequest registration = new RegistrationRequest();
    registration.setName(fileName);/*from   w w w.  j  a va  2s. c om*/
    registration.setPrettyName(prettyName);
    registration.setPath(file.getLeft());
    registration.setIndexPath(file.getRight());
    registration.setReferenceId(referenceId);
    registration.setType(BiologicalDataItemResourceType.getTypeFromPath(file.getKey()));

    if (file.getValue() != null) {
        registration.setIndexType(BiologicalDataItemResourceType.getTypeFromPath(file.getValue()));
    }

    if (format == BiologicalDataItemFormat.VCF || format == BiologicalDataItemFormat.GENE) {
        registration.setDoIndex(doIndex);
    }
    return registration;
}

From source file:com.astamuse.asta4d.web.test.dispatch.RequestDispatcherTest.java

@Test(dataProvider = "data")
public void execute(String method, String url, int status, ContentProvider contentProvider) throws Exception {
    WebApplicationContext context = (WebApplicationContext) Context.getCurrentThreadContext();
    HttpServletRequest request = context.getRequest();
    HttpServletResponse response = context.getResponse();
    HttpSession session = mock(HttpSession.class);

    when(request.getParameterNames()).thenReturn(Collections.emptyEnumeration());
    when(request.getCookies()).thenReturn(new Cookie[0]);
    when(request.getHeaderNames()).thenReturn(Collections.emptyEnumeration());
    when(request.getSession(true)).thenReturn(session);

    when(request.getRequestURI()).thenReturn(url);
    when(request.getContextPath()).thenReturn("");
    when(request.getMethod()).thenReturn(method);

    final ByteArrayOutputStream responseBos = new ByteArrayOutputStream();
    when(response.getOutputStream()).thenReturn(new ServletOutputStream() {
        @Override/* www .  ja v a2s.c  o m*/
        public void write(int b) throws IOException {
            responseBos.write(b);
        }
    });

    HandyRuleSet ruleSet = new HandyRuleSet();
    initTestRules(ruleSet);

    if (url.equals("/index-rewrite")) {
        context.setAccessURI("/index");
    }

    dispatcher.dispatchAndProcess(ruleSet.getArrangedRuleList());

    // verify status at first then when contentProvider is null, we do not
    // need to do more verification
    if (status != 0) {
        verify(response).setStatus(status);
    }

    if (contentProvider == null) {
        return;
    }

    // prepare expected results
    HttpServletResponse expectedResponse = mock(HttpServletResponse.class);

    final ByteArrayOutputStream expectedBos = new ByteArrayOutputStream();
    when(expectedResponse.getOutputStream()).thenReturn(new ServletOutputStream() {
        @Override
        public void write(int b) throws IOException {
            expectedBos.write(b);
        }
    });

    final List<Pair<String, String>> expectedHeaderList = new LinkedList<>();

    doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) {
            Object[] args = invocation.getArguments();
            expectedHeaderList.add(Pair.of((String) args[0], (String) args[1]));
            return null;
        }
    }).when(expectedResponse).addHeader(anyString(), anyString());

    UrlMappingRule currentRule = context.getCurrentRule();
    contentProvider.produce(currentRule, expectedResponse);

    // verify extra contents like headers and output stream

    for (Pair<String, String> pair : expectedHeaderList) {
        verify(response).addHeader(pair.getKey(), pair.getValue());
    }

    Assert.assertEquals(new String(responseBos.toByteArray()), new String(expectedBos.toByteArray()));

}