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:info.archinnov.achilles.query.slice.SliceQueryValidator.java

public <T> void validateComponentsForSliceQuery(SliceQuery<T> sliceQuery) {

    final List<Object> clusteringsFrom = sliceQuery.getClusteringsFrom();
    final List<Object> clusteringsTo = sliceQuery.getClusteringsTo();
    final OrderingMode validationOrdering = sliceQuery.getOrdering();
    final int partitionComponentsSize = sliceQuery.partitionComponentsSize();

    final String startDescription = StringUtils
            .join(clusteringsFrom.subList(partitionComponentsSize, clusteringsFrom.size()), ",");
    final String endDescription = StringUtils
            .join(clusteringsTo.subList(partitionComponentsSize, clusteringsTo.size()), ",");

    log.trace("Check components for slice query {} / {}", startDescription, endDescription);

    final int startIndex = getLastNonNullIndex(clusteringsFrom);
    final int endIndex = getLastNonNullIndex(clusteringsTo);

    // No more than 1 non-null component difference between clustering keys
    Validator.validateTrue(Math.abs(endIndex - startIndex) <= 1,
            "There should be no more than 1 component difference between clustering keys: [[%s]," + "[%s]",
            startDescription, endDescription);

    for (int i = partitionComponentsSize; i <= Math.max(startIndex, endIndex) - 1; i++) {
        Object startComp = clusteringsFrom.get(i);
        Object endComp = clusteringsTo.get(i);

        int comparisonResult = comparator.compare(startComp, endComp);

        Validator.validateTrue(comparisonResult == 0,
                (i + 1 - partitionComponentsSize)
                        + "th component for clustering keys should be equal: [[%s],[%s]",
                startDescription, endDescription);
    }/*  ww  w. j  a va  2 s .  c om*/

    if (startIndex > 0 && startIndex == endIndex) {
        Object startComp = clusteringsFrom.get(startIndex);
        Object endComp = clusteringsTo.get(endIndex);
        if (ASCENDING.equals(validationOrdering)) {
            Validator.validateTrue(comparator.compare(startComp, endComp) <= 0,
                    "For slice query with ascending order, start clustering last component should be "
                            + "'lesser or equal' to end clustering last component: [[%s],[%s]",
                    startDescription, endDescription);
        } else {
            Validator.validateTrue(comparator.compare(startComp, endComp) >= 0,
                    "For slice query with descending order, start clustering last component should be "
                            + "'greater or equal' to end clustering last component: [[%s],[%s]",
                    startDescription, endDescription);
        }

    }

}

From source file:biz.ganttproject.impex.csv.TaskRecords.java

@Override
protected void postProcess() {
    for (Map.Entry<String, Task> wbsEntry : myWbsMap.entrySet()) {
        String outlineNumber = wbsEntry.getKey();
        List<String> components = Arrays.asList(outlineNumber.split("\\."));
        if (components.size() <= 1) {
            continue;
        }/*from w  ww.j  a v  a2 s . co m*/
        String parentOutlineNumber = Joiner.on('.').join(components.subList(0, components.size() - 1));
        Task parentTask = myWbsMap.get(parentOutlineNumber);
        if (parentTask == null) {
            continue;
        }
        taskManager.getTaskHierarchy().move(wbsEntry.getValue(), parentTask, 0);
    }
    if (resourceManager != null) {
        Map<String, HumanResource> resourceMap = Maps.uniqueIndex(resourceManager.getResources(),
                new Function<HumanResource, String>() {
                    @Override
                    public String apply(HumanResource input) {
                        return input.getName();
                    }
                });
        for (Entry<Task, String> assignment : myAssignmentMap.entrySet()) {
            if (assignment.getValue() == null) {
                continue;
            }
            String[] names = assignment.getValue().split(";");
            for (String name : names) {
                HumanResource resource = resourceMap.get(name);
                if (resource != null) {
                    assignment.getKey().getAssignmentCollection().addAssignment(resource);
                }
            }
        }
    }
    Function<Integer, Task> taskIndex = new Function<Integer, Task>() {
        @Override
        public Task apply(Integer id) {
            return myTaskIdMap.get(String.valueOf(id));
        }
    };
    for (Entry<Task, String> entry : myPredecessorMap.entrySet()) {
        if (entry.getValue() == null) {
            continue;
        }
        Task successor = entry.getKey();
        String[] depSpecs = entry.getValue().split(";");
        try {
            Map<Integer, Supplier<TaskDependency>> constructors = TaskProperties
                    .parseDependencies(Arrays.asList(depSpecs), successor, taskIndex);
            for (Supplier<TaskDependency> constructor : constructors.values()) {
                constructor.get();
            }
        } catch (IllegalArgumentException e) {
            GPLogger.logToLogger(String.format("%s\nwhen parsing predecessor specification %s of task %s",
                    e.getMessage(), entry.getValue(), successor));
        } catch (TaskDependencyException e) {
            GPLogger.logToLogger(e);
        }
    }
}

From source file:com.opengamma.web.holiday.WebHolidayVersionResource.java

/**
 * Creates the output root data./* w ww  .j  a  v  a 2  s.  co  m*/
 * @return the output root data, not null
 */
protected FlexiBean createRootData() {
    FlexiBean out = super.createRootData();
    HolidayDocument latestDoc = data().getHoliday();
    HolidayDocument versionedHoliday = data().getVersioned();
    out.put("latestHolidayDoc", latestDoc);
    out.put("latestHoliday", latestDoc.getHoliday());
    out.put("holidayDoc", versionedHoliday);
    out.put("holiday", versionedHoliday.getHoliday());
    out.put("deleted", !latestDoc.isLatest());
    List<Pair<Year, List<LocalDate>>> map = new ArrayList<Pair<Year, List<LocalDate>>>();
    List<LocalDate> dates = versionedHoliday.getHoliday().getHolidayDates();
    if (dates.size() > 0) {
        int year = dates.get(0).getYear();
        int start = 0;
        int pos = 0;
        for (; pos < dates.size(); pos++) {
            if (dates.get(pos).getYear() == year) {
                continue;
            }
            map.add(Pair.of(Year.of(year), dates.subList(start, pos)));
            year = dates.get(pos).getYear();
            start = pos;
        }
        map.add(Pair.of(Year.of(year), dates.subList(start, pos)));
    }
    out.put("holidayDatesByYear", map);
    return out;
}

From source file:chapter4.src.logistic.CsvRecordFactoryPredict.java

public List<String> getTargetCategories() {
    List<String> r = targetDictionary.values();
    if (r.size() > maxTargetValue) {
        r.subList(maxTargetValue, r.size()).clear();
    }/*  ww  w.  jav a  2 s .  c  o  m*/
    return r;
}

From source file:eu.trentorise.opendata.jackan.test.ckan.ReadCkanIT.java

/**
 * Tries to get some users./* w w  w  .ja va2  s.c om*/
 */
@Test
@Parameters(method = "clients")
public void testUser(CkanClient client) {
    List<CkanUser> ul = client.getUserList();
    assertTrue(ul.size() > 0);
    for (CkanUser u : ul.subList(0, Math.min(ul.size(), TEST_ELEMENTS))) {
        CkanUser fetchedUser = client.getUser(u.getId());
        assertEquals(u.getName(), fetchedUser.getName());
    }
}

From source file:net.sf.katta.tool.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 w  w w  . ja  v a 2s  .c  o m*/
        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<OperationId>();
    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:vlove.virt.VirtBuilder.java

/**
 * Returns the exit value of the process.
 * //  w ww . ja va  2  s.c o m
 * @param out
 * @param err
 * @return
 * @throws VirtException
 */
public int createVirtualMachine(NewVmWizardModel newVm, StreamConsumer out, StreamConsumer err)
        throws VirtException {
    List<String> command = createVirtMachineCommand(newVm);
    if (command == null || command.size() < 1) {
        throw new VirtException("Command needs to be provided.");
    }

    try {
        Commandline cs = new Commandline();
        cs.setExecutable(command.get(0));
        if (command.size() > 1) {
            cs.addArguments(command.subList(1, command.size()).toArray(new String[] {}));
        }
        PipedOutputStream pOut = new PipedOutputStream();
        PipedInputStream pIs = new PipedInputStream(pOut);

        List<ConsumerListener> listeners = new ArrayList<>();
        listeners.add(new ConsumerListener(pOut, Pattern.compile("\\[sudo\\] password for \\w+:"), "password"));

        NestedStreamConsumer nOut = new NestedStreamConsumer(listeners, out);
        return CommandLineUtils.executeCommandLine(cs, pIs, nOut, err);
    } catch (CommandLineException ce) {
        throw new VirtException("Could not execute command.", ce);
    } catch (IOException ie) {
        throw new VirtException("Could not execute command.", ie);
    }
}

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

/**
 * {@inheritDoc}/*from   w w w . j  a v  a2s. co m*/
 * 
 * @see com.xpn.xwiki.user.impl.xwiki.XWikiGroupServiceImpl#getAllMatchedUsers(java.lang.Object[][], boolean, int,
 *      int, java.lang.Object[][], com.xpn.xwiki.XWikiContext) TODO: fully implements this method.
 */
@Override
public List<String> getAllMatchedUsers(Object[][] matchFields, boolean withdetails, int nb, int start,
        Object[][] order, XWikiContext context) throws XWikiException {
    if ((matchFields != null && matchFields.length > 0) || withdetails || (order != null && order.length > 0)) {
        throw new NotImplementedException();
    }

    List<String> usersList = listMemberForGroup(null, context);

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

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

    return usersList;
}

From source file:eu.trentorise.opendata.jackan.test.ckan.ReadCkanIT.java

@Test
@Parameters(method = "clients")
public void testGroup(CkanClient client) {
    List<CkanGroup> gl = client.getGroupList();
    assertTrue(gl.size() > 0);/*from ww  w .  j a v a 2s  .c  o  m*/

    for (CkanGroup g : gl.subList(0, Math.min(gl.size(), TEST_ELEMENTS))) {
        CkanGroup fetchedGroup = client.getGroup(g.getId());
        assertEquals(g.getName(), fetchedGroup.getName());
    }
}

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

@Override
public void repairProcessingMessages() {
    // find messages in PROCESSING state
    List<Message> messages = findProcessingMessages();

    Log.debug("Found {} message(s) for repairing ...", messages.size());

    // repair messages in batches
    int batchStartIncl = 0;
    int batchEndExcl;
    while (batchStartIncl < messages.size()) {
        batchEndExcl = min(batchStartIncl + BATCH_SIZE, messages.size());
        updateMessagesInDB(messages.subList(batchStartIncl, batchEndExcl));
        batchStartIncl = batchEndExcl;//from  ww w .ja va2  s  . c om
    }
}