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:org.apache.taverna.databundle.DataBundles.java

public static ErrorDocument getError(Path path) throws IOException {
    if (path == null)
        return null;

    Path errorPath = withExtension(path, DOT_ERR);
    List<String> errorList = readAllLines(errorPath, UTF8);
    int split = errorList.indexOf("");
    if (split == -1 || errorList.size() <= split)
        throw new IOException("Invalid error document: " + errorPath);

    ErrorDocument errorDoc = new ErrorDocument();

    for (String cause : errorList.subList(0, split))
        errorDoc.getCausedBy().add(path.resolveSibling(cause));

    errorDoc.setMessage(errorList.get(split + 1));

    StringBuilder errorTrace = new StringBuilder();
    for (String line : errorList.subList(split + 2, errorList.size())) {
        errorTrace.append(line);//from   w  w  w .  j  a  va2 s  .c  o m
        errorTrace.append("\n");
    }
    if (errorTrace.length() > 0)
        // Delete last \n
        errorTrace.deleteCharAt(errorTrace.length() - 1);
    errorDoc.setTrace(errorTrace.toString());
    return errorDoc;
}

From source file:de.sub.goobi.metadaten.copier.DataCopyrule.java

/**
 * Factory method to create a class implementing the metadata copy rule
 * referenced by a given command string/*from   w  ww . j  a  va2  s  .  c  om*/
 *
 * @param command
 *            A space-separated string consisting of subject (aka. patiens),
 *            operator (aka. agens) and (optional) objects (depending on
 *            what objects the operator requires).
 * @return a class implementing the metadata copy rule referenced
 * @throws ConfigurationException
 *             if the operator cannot be resolved or the number of arguments
 *             doesnt match
 */
public static DataCopyrule createFor(String command) throws ConfigurationException {
    List<String> arguments = Arrays.asList(command.split("\\s+"));
    String operator;
    try {
        operator = arguments.get(1);
    } catch (IndexOutOfBoundsException e) {
        throw new ConfigurationException("Missing operator (second argument) in line: " + command);
    }
    Class<? extends DataCopyrule> ruleClass = AVAILABLE_RULES.get(operator);
    if (ruleClass == null) {
        throw new ConfigurationException("Unknown operator: " + operator);
    }
    DataCopyrule ruleImplementation;
    try {
        ruleImplementation = ruleClass.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    ruleImplementation.setSubject(arguments.get(0));
    if (ruleImplementation.getMaxObjects() > 0) {
        List<String> objects = arguments.subList(2, arguments.size());
        if (objects.size() < ruleImplementation.getMinObjects()) {
            throw new ConfigurationException("Too few arguments in line: " + command);
        }
        if (objects.size() > ruleImplementation.getMaxObjects()) {
            throw new ConfigurationException("Too many arguments in line: " + command);
        }
        ruleImplementation.setObjects(objects);
    }
    return ruleImplementation;
}

From source file:org.avidj.zuul.core.DefaultEmbeddedLockManager.java

private static boolean currentThreadHoldsNoLocksOnPath(LockTreeNode root, List<String> path) {
    LockTreeNode current = root;//from   w  ww .ja  v  a  2  s .co  m
    if (current.isHeldByCurrentThread()) {
        return false;
    }
    for (int i = 0, n = path.size(); i < n; i++) {
        String step = path.get(i);
        current = current.children.get(step);
        if (current == null) {
            return true;
        } else if (current.isHeldByCurrentThread()) {
            LOG.error("Current thread holds a lock on mutex of node: {}", Strings.join(path.subList(0, i + 1)));
            return false;
        }
    }
    return true;
}

From source file:fr.paris.lutece.plugins.mylutece.util.SecurityUtils.java

/**
 * Test a password validity/*from  ww  w.  j a v a2s  . c o m*/
 * @param parameterService Paramter service to use
 * @param plugin The plugin
 * @param strPassword The password to test validity
 * @param nUserId The id of the user
 * @return Returns null if the password is correct, or a code depending on
 *         the error found. Errors can be 'password_minimum_length' if the
 *         password is too short, or 'password_format' if the format of the
 *         password is not correct.
 */
public static String checkPasswordForFrontOffice(IUserParameterService parameterService, Plugin plugin,
        String strPassword, int nUserId) {
    // Check minimum length password
    if (!(SecurityUtils.checkUserPasswordMinimumLength(strPassword, parameterService, plugin))) {
        return ERROR_PASSWORD_MINIMUM_LENGTH;
    }

    // Check password format
    if (!(SecurityUtils.checkPasswordFormat(strPassword, parameterService, plugin))) {
        return ERROR_PASSWORD_WRONG_FORMAT;
    }

    // Check password history
    if (nUserId > 0) {
        int nPasswordHistorySize = getIntegerSecurityParameter(parameterService, plugin,
                MARK_PASSWORD_HISTORY_SIZE);

        if (nPasswordHistorySize > 0) {
            String strEncryptedPassword = buildPassword(parameterService, plugin, strPassword);
            List<String> passwordHistory = parameterService.selectUserPasswordHistory(nUserId, plugin);

            if (nPasswordHistorySize < passwordHistory.size()) {
                passwordHistory = passwordHistory.subList(0, nPasswordHistorySize);
            }

            if (passwordHistory.contains(strEncryptedPassword)) {
                return ERROR_PASSWORD_ALREADY_USED;
            }
        }

        int nTSWSizePasswordChange = getIntegerSecurityParameter(parameterService, plugin,
                MARK_TSW_SIZE_PASSWORD_CHANGE);
        int nMaximumNumberPasswordChange = getIntegerSecurityParameter(parameterService, plugin,
                MARK_MAXIMUM_NUMBER_PASSWORD_CHANGE);

        if (nMaximumNumberPasswordChange > 0) {
            Timestamp minDate = null;

            if (nTSWSizePasswordChange > 0) {
                minDate = new Timestamp(new java.util.Date().getTime()
                        - DateUtil.convertDaysInMiliseconds(nTSWSizePasswordChange));
            } else {
                minDate = new Timestamp(0);
            }

            if (parameterService.countUserPasswordHistoryFromDate(minDate, nUserId,
                    plugin) >= nMaximumNumberPasswordChange) {
                return ERROR_MAX_PASSWORD_CHANGE;
            }
        }
    }

    return null;
}

From source file:com.uber.stream.kafka.mirrormaker.common.utils.C3QueryUtils.java

public static Map<String, TopicWorkload> retrieveTopicInRate(long timeInMs, long windowInMs, String c3Host,
        int c3Port, String kafkaCluster, List<String> topics) throws IOException {
    Map<String, TopicWorkload> workloads = new HashMap<>();
    if (c3Port == 0) {
        return workloads;
    }//from ww  w.  ja v a2  s . c  o  m
    long endSec = (timeInMs / 1000 - DEFAULT_QUERY_MINIMUM_END_TO_CURRENT_SEC) / 600 * 600;
    long startSec = endSec - windowInMs / 1000L;
    LOGGER.info("Retrieve workload for [{}, {}] for {} for {} topics", startSec, endSec, kafkaCluster,
            topics.size());
    long ts1 = System.currentTimeMillis();
    for (int i = 0; i < topics.size(); i += DEFAULT_BATCH_TOPICS) {
        StringBuilder query = new StringBuilder();
        query.append("startSec=");
        query.append(startSec);
        query.append("&endSec=");
        query.append(endSec);
        query.append("&tier=");
        query.append(kafkaCluster);
        query.append("&topicList=");
        List<String> batch = topics.subList(i, Math.min(i + DEFAULT_BATCH_TOPICS, topics.size()));
        query.append(StringUtils.join(batch, ","));
        String jsonStr = makeQuery(c3Host, c3Port, query.toString());
        extractJsonResults(jsonStr, batch, workloads);
    }
    LOGGER.info("took {} ms to retrieve {} topics for {}", System.currentTimeMillis() - ts1, topics.size(),
            kafkaCluster);
    return workloads;
}

From source file:org.zalando.problem.JacksonStackTraceProcessor.java

private <T> Function<Integer, List<T>> subList(final List<T> list) {
    return index -> list.subList(index, list.size());
}

From source file:info.magnolia.jcr.util.NodeUtil.java

/**
 * Gets the siblings before this node./*www . j  a v  a  2  s.  co  m*/
 * @param node node from which will be siblings retrieved
 * @return list of siblings before the given Node (the given node is excluded)
 */
public static Iterable<Node> getSiblingsBefore(Node node) throws RepositoryException {
    int toIndex = 0;
    Node parent = node.getParent();
    List<Node> allSiblings = NodeUtil.asList(NodeUtil.getNodes(parent));

    for (Node sibling : allSiblings) {
        if (NodeUtil.isSame(node, sibling)) {
            break;
        }
        toIndex++;
    }
    return allSiblings.subList(0, toIndex);
}

From source file:eu.trentorise.smartcampus.mobility.util.GamificationHelper.java

private static List<List<Geolocation>> splitList(List<Geolocation> list) {
    List<List<Geolocation>> result = Lists.newArrayList();
    int half = list.size() / 2;
    List<Geolocation> l1 = list.subList(0, half);
    List<Geolocation> l2 = list.subList(half, list.size());
    result.add(l1);//from ww  w  .  j a v a 2 s. com
    result.add(l2);
    return result;
}

From source file:mondrian.rolap.RolapMember.java

/**
 * Sets member ordinal values using a Bottom-up/Top-down algorithm.
 *
 * <p>Gets an array of members for each level and traverses
 * array for the lowest level, setting each member's
 * parent's parent's etc. member's ordinal if not set working back
 * down to the leaf member and then going to the next leaf member
 * and traversing up again.//from ww w . ja va2  s . c o m
 *
 * <p>The above algorithm only works for a hierarchy that has all of its
 * leaf members in the same level (that is, a non-ragged hierarchy), which
 * is the norm. After all member ordinal values have been set, traverses
 * the array of members, making sure that all members' ordinals have been
 * set. If one is found that is not set, then one must to a full Top-down
 * setting of the ordinals.
 *
 * <p>The Bottom-up/Top-down algorithm is MUCH faster than the Top-down
 * algorithm.
 *
 * @param schemaReader Schema reader
 * @param seedMember Member
 */
public static void setOrdinals(SchemaReader schemaReader, Member seedMember) {
    /*
     * The following are times for executing different set ordinals
     * algorithms for both the FoodMart Sales cube/Store dimension
     * and a Large Data set with a dimension with about 250,000 members.
     *
     * Times:
     *    Original setOrdinals Top-down
     *       Foodmart: 63ms
     *       Large Data set: 651865ms
     *    Calling getAllMembers before calling original setOrdinals Top-down
     *       Foodmart: 32ms
     *       Large Data set: 73880ms
     *    Bottom-up/Top-down
     *       Foodmart: 17ms
     *       Large Data set: 4241ms
     */
    long start = System.currentTimeMillis();

    try {
        Hierarchy hierarchy = seedMember.getHierarchy();
        int ordinal = hierarchy.hasAll() ? 1 : 0;
        List<List<Member>> levelMembers = getAllMembers(schemaReader, hierarchy);
        List<Member> leafMembers = levelMembers.get(levelMembers.size() - 1);
        levelMembers = levelMembers.subList(0, levelMembers.size() - 1);

        // Set all ordinals
        for (Member child : leafMembers) {
            ordinal = bottomUpSetParentOrdinals(ordinal, child);
            ordinal = setOrdinal(child, ordinal);
        }

        boolean needsFullTopDown = needsFullTopDown(levelMembers);

        // If we must to a full Top-down, then first reset all ordinal
        // values to -1, and then call the Top-down
        if (needsFullTopDown) {
            for (List<Member> members : levelMembers) {
                for (Member member : members) {
                    if (member instanceof RolapMember) {
                        ((RolapMember) member).resetOrdinal();
                    }
                }
            }

            // call full Top-down
            setOrdinalsTopDown(schemaReader, seedMember);
        }
    } finally {
        if (LOGGER.isDebugEnabled()) {
            long end = System.currentTimeMillis();
            LOGGER.debug("RolapMember.setOrdinals: time=" + (end - start));
        }
    }
}

From source file:Main.java

/**
 * Move a single entry (indicated by its key) up or down by one step inside an insert sorted map (e.g. a {@link LinkedHashMap}).
 * /* w w w  . j av a 2s .  c o m*/
 * @param <K>
 *            type of the map's keys
 * @param <V>
 *            type of the map's values
 * @param insertSortedMap
 *            map containing the entry to be moved; should be a map implementation preserving the insert order (e.g. a {@link LinkedHashMap})
 * @param entryKey
 *            key of the entry to be moved up/down by one step
 * @param increaseIndexByOne
 *            if the entry's index should be increased by one (i.e. moved down); otherwise decrease the entry's index by one (i.e. moved up)
 * @throws IllegalArgumentException
 *             <ul>
 *             <li>if the given map does not contain the specified key,</li>
 *             <li>if the specified entry is the first in the map and cannot be moved further up, or</li>
 *             <li>if the specified entry is the last in the map and cannot be moved further down</li>
 *             </ul>
 */
public static <K, V> void moveEntryInInsertSortedMap(final Map<K, V> insertSortedMap, final K entryKey,
        final boolean increaseIndexByOne) {
    // #1 create a copy of the original key order as list (to make it accessible via index)
    final List<K> keyList = new ArrayList<K>(insertSortedMap.keySet());
    // #2 determine the designated entry's current position
    final int index = keyList.indexOf(entryKey);
    // #3 determine the entry's new position
    final int indexToSwitchWith;
    if (increaseIndexByOne) {
        indexToSwitchWith = index + 1;
    } else {
        indexToSwitchWith = index - 1;
    }
    final int totalEntryCount = keyList.size();
    if (index == -1 || indexToSwitchWith == -1 || indexToSwitchWith == totalEntryCount) {
        // the entry cannot be moved as indicated
        throw new IllegalArgumentException();
    }
    // #4 create a copy of the unchanged relation template groups map
    final Map<K, V> groupsCopy = new LinkedHashMap<K, V>(insertSortedMap);
    // #5 remove all mapping from the original relation template groups map, starting at the affected groups' indices
    insertSortedMap.keySet().retainAll(keyList.subList(0, Math.min(index, indexToSwitchWith)));
    final K entryToSwitchWith = keyList.get(indexToSwitchWith);
    // #6 re-insert the two affected groups in their new (inverse) order
    if (increaseIndexByOne) {
        insertSortedMap.put(entryToSwitchWith, groupsCopy.get(entryToSwitchWith));
        insertSortedMap.put(entryKey, groupsCopy.get(entryKey));
    } else {
        insertSortedMap.put(entryKey, groupsCopy.get(entryKey));
        insertSortedMap.put(entryToSwitchWith, groupsCopy.get(entryToSwitchWith));
    }
    // #7 re-insert all groups that are following the affected two relation tempate groups
    final int firstTrailingRetainedIndex = Math.max(index, indexToSwitchWith) + 1;
    if (firstTrailingRetainedIndex < totalEntryCount) {
        // there is at least one more value behind the affected two entries that needs to be re-inserted
        groupsCopy.keySet().retainAll(keyList.subList(firstTrailingRetainedIndex, totalEntryCount));
        insertSortedMap.putAll(groupsCopy);
    }
}