Example usage for java.util List subList

List of usage examples for java.util List subList

Introduction

In this page you can find the example usage for java.util List subList.

Prototype

List<E> subList(int fromIndex, int toIndex);

Source Link

Document

Returns a view of the portion of this list between the specified fromIndex , inclusive, and toIndex , exclusive.

Usage

From source file:co.cask.tigon.sql.ioserver.OutputServerSocketTest.java

@Test
public void testStreamHeaderParser() throws InterruptedException, IOException {
    String outputName = "output";
    GDATEncoder encoder = new GDATEncoder();
    encoder.writeLong(3L);/*from w w  w .ja va 2  s .c  om*/
    encoder.writeString("Hello");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    encoder.writeTo(out);
    byte[] dataBytes = out.toByteArray();
    OutputServerSocket outputServerSocket = new OutputServerSocket(serverFacotry, outputName,
            "SELECT foo FROM bar", new GDATRecordQueue());
    outputServerSocket.startAndWait();
    InetSocketAddress serverAddress = outputServerSocket.getSocketAddressMap().get(Constants.StreamIO.DATASINK);
    LOG.info("Server is running at {}", serverAddress);
    setupClientPipeline();
    ChannelFuture future = clientBootstrap.connect(serverAddress);
    future.await(3, TimeUnit.SECONDS);
    Channel channel = future.getChannel();
    String gdatHeader = new StreamInputHeader(outputName, testSchema).getStreamHeader();
    List<Byte> gdatByteList = new ArrayList<Byte>(Bytes.asList(gdatHeader.getBytes(Charsets.UTF_8)));
    gdatByteList.addAll(new ArrayList<Byte>(Bytes.asList(dataBytes)));

    int partitionSize = 10;
    List<List<Byte>> byteChunks = Lists.newArrayList();
    for (int i = 0; i < gdatByteList.size(); i += partitionSize) {
        byteChunks.add(gdatByteList.subList(i, i + Math.min(partitionSize, gdatByteList.size() - i)));
    }

    ChannelBuffer buffer;
    for (List<Byte> chunk : byteChunks) {
        buffer = ChannelBuffers.wrappedBuffer(ArrayUtils.toPrimitive(chunk.toArray(new Byte[chunk.size()])));
        channel.write(buffer).await();
        TimeUnit.MILLISECONDS.sleep(10);
    }
    TimeUnit.SECONDS.sleep(2);
    Assert.assertEquals(1, outputServerSocket.getDataRecordsReceived());
}

From source file:org.cleverbus.core.common.asynch.repair.RepairExternalCallDbImpl.java

@Override
public void repairProcessingExternalCalls() {
    // find external calls in PROCESSING state
    List<ExternalCall> extCalls = findProcessingExternalCalls();

    Log.debug("Found {} external call(s) for repairing ...", extCalls.size());

    // repair external calls in batches
    int batchStartIncl = 0;
    int batchEndExcl;
    while (batchStartIncl < extCalls.size()) {
        batchEndExcl = min(batchStartIncl + BATCH_SIZE, extCalls.size());
        updateExternalCallsInDB(extCalls.subList(batchStartIncl, batchEndExcl));
        batchStartIncl = batchEndExcl;//from   w  w w  . j  a va 2 s .c o m
    }

}

From source file:com.sg.capstone.controller.BlogPostController.java

private List<BlogPost> displayPostsPerPage(List<BlogPost> blogPosts, int pageNumber, int numOfPostsPerPage) {
    int postsToShowBegin = (((pageNumber - 1) * numOfPostsPerPage));
    int postsToShowEnd = (pageNumber * numOfPostsPerPage);

    List<BlogPost> postsToDisplay;
    try {//from w  ww  . ja v  a 2 s  .com
        postsToDisplay = blogPosts.subList(postsToShowBegin, postsToShowEnd);
    } catch (IndexOutOfBoundsException inOutEx) {
        postsToDisplay = blogPosts.subList(postsToShowBegin, blogPosts.size());
    }
    return postsToDisplay;
}

From source file:es.udc.gii.common.eaf.algorithm.operator.reproduction.crossover.CrossOverOperator.java

@Override
public List<Individual> operate(EvolutionaryAlgorithm algorithm, List<Individual> individuals)
        throws OperatorException {

    if (individuals == null) {
        throw new OperatorException("CrossOver - " + "Empty individuals");
    }//  w  w w . j a  v  a  2  s. c  o  m

    for (int i = 0; i < individuals.size() / 2; i++) {
        if (this.probability >= EAFRandom.nextDouble() * 100) {
            this.crossOver(algorithm, individuals.subList(i * 2, (i + 1) * 2));
        }
    }

    return individuals;

}

From source file:au.org.ala.delta.intkey.directives.DefineNamesDirective.java

@Override
protected BasicIntkeyDirectiveInvocation doProcess(IntkeyContext context, String data) throws Exception {
    String keyword = null;//from  w ww . j a  v a 2 s.  com
    List<String> names = new ArrayList<String>();

    // Need to prompt if data starts with a wildcard - don't bother
    // tokenizing
    if (!data.toUpperCase().startsWith(IntkeyDirectiveArgument.DEFAULT_DIALOG_WILDCARD)) {
        // Taxon names are separated by newlines or by commas
        List<String> tokens = new StrTokenizer(data, StrMatcher.charSetMatcher(new char[] { '\n', '\r', ',' }))
                .getTokenList();

        if (!tokens.isEmpty()) {
            String firstToken = tokens.get(0);

            // The keyword (which may quoted) and first taxon name may be
            // separated by a space
            List<String> splitFirstToken = new StrTokenizer(firstToken,
                    StrMatcher.charSetMatcher(new char[] { ' ' }), StrMatcher.quoteMatcher()).getTokenList();

            keyword = splitFirstToken.get(0);

            if (splitFirstToken.size() > 1) {
                names.add(StringUtils.join(splitFirstToken.subList(1, splitFirstToken.size()), " "));
            }

            for (int i = 1; i < tokens.size(); i++) {
                names.add(tokens.get(i).trim());
            }

            //If first name begins with a wildcard, we need to prompt for names. Clear out the names list if this is the case.
            if (!names.isEmpty()) {
                if (names.get(0).toUpperCase().startsWith(IntkeyDirectiveArgument.DEFAULT_DIALOG_WILDCARD)) {
                    names.clear();
                }
            }
        }
    }

    List<Item> taxa = new ArrayList<Item>();
    for (String taxonName : names) {
        Item taxon = context.getDataset().getTaxonByName(taxonName);
        if (taxon == null) {
            throw new IntkeyDirectiveParseException(
                    UIUtils.getResourceString("InvalidTaxonName.error", taxonName));
        } else {
            taxa.add(taxon);
        }
    }

    String directiveName = StringUtils.join(getControlWords(), " ").toUpperCase();

    if (StringUtils.isEmpty(keyword)) {
        keyword = context.getDirectivePopulator()
                .promptForString(UIUtils.getResourceString("EnterKeyword.caption"), null, directiveName);
        if (keyword == null) {
            // cancelled
            return null;
        }
    }

    if (taxa.isEmpty()) {
        List<String> selectedKeywords = new ArrayList<String>(); // Not
                                                                 // used,
                                                                 // but
                                                                 // required
                                                                 // as an
                                                                 // argument
        taxa = context.getDirectivePopulator().promptForTaxaByList(directiveName, false, false, false, false,
                null, selectedKeywords);
        if (taxa == null || taxa.isEmpty()) {
            // cancelled
            return null;
        }

        // extract taxon names for use in building string representation of
        // command
        for (Item taxon : taxa) {
            names.add(_taxonFormatter.formatItemDescription(taxon));
        }
    }

    DefineNamesDirectiveInvocation invoc = new DefineNamesDirectiveInvocation(keyword, taxa);
    invoc.setStringRepresentation(
            String.format("%s \"%s\" %s", getControlWordsAsString(), keyword, StringUtils.join(names, ", ")));

    return invoc;
}

From source file:com.dasasian.chok.testutil.loadtest.LoadTestMasterOperation.java

@Override
public List<OperationId> execute(MasterContext context, List<MasterOperation> runningOperations)
        throws Exception {
    currentIterationStartTime = System.currentTimeMillis();
    if (masterName == null) {
        masterName = context.getMaster().getMasterName();
        resultDir.mkdirs();/*from  www  . ja  v  a  2 s  .c om*/
        if (!resultDir.isDirectory()) {
            throw new IllegalStateException(
                    "result dir '" + resultDir.getAbsolutePath() + "' cannot be created");
        }
    } else if (!masterName.equals(context.getMaster().getMasterName())) {
        throw new IllegalStateException(
                "master change detected - load test not safe for this since it writes local log files!");
    }
    List<String> testNodes = context.getProtocol().getLiveNodes();
    if (testNodes.size() < numberOfTesterNodes) {
        throw new IllegalStateException(
                "only " + testNodes.size() + " available, needing " + numberOfTesterNodes);
    }
    testNodes = testNodes.subList(0, numberOfTesterNodes);

    final int queryRate = calculateCurrentQueryRate();
    if (currentIteration == 0) {
        LOG.info("starting load test with " + testNodes.size() + " nodes");
    }
    LOG.info("executing tests in iteration " + currentIteration + " at query rate: " + queryRate
            + " queries per second and with a run time of " + runTime / 1000 + " seconds");

    int remainingQueryRate = queryRate;
    int remainingNodes = testNodes.size();

    List<OperationId> nodeOperationIds = new ArrayList<>();
    for (String testNode : testNodes) {
        int queryRateForNode = remainingQueryRate / remainingNodes;
        LOG.info("instructing test on node " + testNode + " using query rate: " + queryRateForNode
                + " queries per second.");

        LoadTestNodeOperation nodeOperation = new LoadTestNodeOperation(queryExecutor, queryRateForNode,
                runTime);
        --remainingNodes;
        remainingQueryRate -= queryRateForNode;
        OperationId operationId = context.getProtocol().addNodeOperation(testNode, nodeOperation);
        nodeOperationIds.add(operationId);
    }
    return nodeOperationIds;
}

From source file:com.google.gwt.emultest.java.util.ListTestBase.java

/**
 * Test add() method for list returned by List<E>.subList() method.
 *//*  w  w w .j av  a2 s .  c om*/
public void testSubListAdd() {
    List<Integer> baseList = createListWithContent(new int[] { 1, 2, 3, 4, 5 });
    List<Integer> sublist = baseList.subList(1, 3);
    assertEquals(2, sublist.size());

    sublist.add(33);
    sublist.add(34);

    assertEquals(4, sublist.size());
    assertEquals(7, baseList.size());

    /*
     * Assert correct values are found right before and after insertion. We're
     * checking the original list (baseList) even though the changes were made
     * in the sublist. That is because modifications made to the list returned
     * by sublist method should reflect in the original list.
     */
    assertEquals(3, (int) baseList.get(2));
    assertEquals(33, (int) baseList.get(3));
    assertEquals(34, (int) baseList.get(4));
    assertEquals(4, (int) baseList.get(5));

    /*
     * Assert that it is possible to add element at the beginning of the
     * sublist.
     */
    sublist.add(0, 22);
    sublist.add(0, 21);
    checkListSizeAndContent(sublist, 21, 22, 2, 3, 33, 34);
    checkListSizeAndContent(baseList, 1, 21, 22, 2, 3, 33, 34, 4, 5);

    // check adding at the end by specifying the index
    sublist.add(6, 35);
    checkListSizeAndContent(sublist, 21, 22, 2, 3, 33, 34, 35);
    checkListSizeAndContent(baseList, 1, 21, 22, 2, 3, 33, 34, 35, 4, 5);

    /*
     * Assert adding to underlying list after the sublist view has been defined.
     * After such an action behavior of sublist is undefined.
     */
    baseList.add(9, 44);
    baseList.add(55);
    baseList.add(0, 10);
    checkListSizeAndContent(baseList, 10, 1, 21, 22, 2, 3, 33, 34, 35, 4, 44, 5, 55);
}

From source file:com.xpn.xwiki.user.impl.exo.ExoGroupServiceImpl.java

/**
 * {@inheritDoc}/*from   w ww.j a v  a2  s  .co  m*/
 * 
 * @see com.xpn.xwiki.user.impl.xwiki.XWikiGroupServiceImpl#getAllMatchedGroups(java.lang.Object[][], boolean, int,
 *      int, java.lang.Object[][], com.xpn.xwiki.XWikiContext)
 */
@Override
public List<String> getAllMatchedGroups(Object[][] matchFields, boolean withdetails, int nb, int start,
        Object[][] order, XWikiContext context) throws XWikiException {
    // TODO : fully implement this methods for eXo platform

    if ((matchFields != null && matchFields.length > 0) || withdetails || (order != null && order.length > 0)) {
        throw new NotImplementedException();
    }

    List<String> groupList = listAllGroups(context);

    if (nb > 0 || start > 0) {
        int fromIndex = start < 0 ? 0 : start;
        int toIndex = fromIndex + (nb <= 0 ? groupList.size() - 1 : nb);

        groupList = groupList.subList(fromIndex, toIndex);
    }

    return groupList;
}

From source file:eu.stratosphere.sopremo.cleansing.mapping.GenerateSkolemGenerators.java

private void addSkolemGeneratorsForKeys(FORule tgd, Map<VariablePathExpression, IValueGenerator> generators,
        List<GeneratorWithPath> functionGenerators, IDataSourceProxy target) {
    for (SetAlias targetSetVariable : tgd.getTargetView().getGenerators()) {

        for (SetAlias targetVar = targetSetVariable; targetVar != null; targetVar = targetVar
                .getBindingPathExpression().getStartingVariable()) {
            VariableFunctionalDependency primaryKey = findPrimaryKeyForSet(targetVar, target);
            if (primaryKey != null) {
                for (int i = 0; i < primaryKey.getLeftPaths().size(); i++) {
                    VariablePathExpression keyPath = primaryKey.getLeftPaths().get(i);
                    VariablePathExpression correctedPath = new VariablePathExpression(keyPath, targetVar);
                    IValueGenerator keyGenerator = generators.get(correctedPath);
                    if (keyGenerator == null) {
                        List<GeneratorWithPath> generatorsForKey = findGeneratorsForKey(keyPath, generators);
                        SkolemFunctionGenerator keySkolemGenerator = new SkolemFunctionGenerator(
                                correctedPath.getAbsolutePath().toString(), true, tgd, generatorsForKey);
                        keySkolemGenerator.setType(SkolemFunctionGenerator.KEY);
                        keySkolemGenerator.addFunctionalDependencies(primaryKey);
                        keySkolemGenerator.setPosition(i);
                        generators.put(correctedPath, keyGenerator = keySkolemGenerator);
                    }/* ww w. j  a v  a  2 s.c  o m*/
                    INode keyNode = new FindNode().findNodeInSchema(keyPath.getAbsolutePath(), target);
                    if (keyNode instanceof AttributeNode) {
                        GeneratePathExpression pathGenerator = new GeneratePathExpression();
                        List<String> steps = new ArrayList<String>(
                                pathGenerator.generatePathFromRoot(keyNode.getChild(0)).getPathSteps());
                        steps.subList(0, steps.size() - 1).clear();
                        steps.addAll(0, correctedPath.getPathSteps());
                        VariablePathExpression nodePath = new VariablePathExpression(targetVar, steps);
                        generators.put(nodePath, keyGenerator);
                    }

                }
            }
        }
    }
}

From source file:annis.gui.frequency.FrequencyResultPanel.java

private void showResult(FrequencyTable table) {
    if (queryPanel != null) {
        queryPanel.notifiyQueryFinished();
    }/*from www  . j ava 2 s  .co m*/
    recreateTable(table);

    btDownloadCSV.setVisible(true);
    FileDownloader downloader = new FileDownloader(
            new StreamResource(new CSVResource(table, freqDefinition), "frequency.txt"));
    downloader.extend(btDownloadCSV);

    chart.setVisible(true);
    FrequencyTable clippedTable = table;
    if (clippedTable.getEntries().size() > MAX_NUMBER_OF_CHART_ITEMS) {
        List<FrequencyTable.Entry> entries = new ArrayList<>(clippedTable.getEntries());

        clippedTable = new FrequencyTable();
        clippedTable.setEntries(entries.subList(0, MAX_NUMBER_OF_CHART_ITEMS));
        clippedTable.setSum(table.getSum());
        chart.setCaption("Showing historgram of top " + MAX_NUMBER_OF_CHART_ITEMS
                + " results, see table below for complete dataset.");
    }
    chart.setFrequencyData(clippedTable);

}