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:de.Keyle.MyPet.util.player.UUIDFetcher.java

public static Map<String, UUID> call(List<String> names) {
    names = new ArrayList<String>(names);
    Iterator<String> iterator = names.iterator();
    while (iterator.hasNext()) {
        String playerName = iterator.next();
        if (fetchedUUIDs.containsKey(playerName)) {
            iterator.remove();//from   ww  w.jav a2s . co  m
        }
    }
    if (names.size() == 0) {
        return readonlyFetchedUUIDs;
    }

    int count = names.size();

    DebugLogger.info("get UUIDs for " + names.size() + " player(s)");
    int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST);
    try {
        for (int i = 0; i < requests; i++) {
            HttpURLConnection connection = createConnection();
            String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size())));
            writeBody(connection, body);
            JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
            count -= array.size();
            for (Object profile : array) {
                JSONObject jsonProfile = (JSONObject) profile;
                String id = (String) jsonProfile.get("id");
                String name = (String) jsonProfile.get("name");
                UUID uuid = UUIDFetcher.getUUID(id);
                fetchedUUIDs.put(name, uuid);
            }
            if (rateLimiting && i != requests - 1) {
                Thread.sleep(100L);
            }
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (count > 0) {
        MyPetLogger.write("Can not get UUIDs for " + count + " players. Pets of these player may be lost.");
    }
    return readonlyFetchedUUIDs;
}

From source file:eu.europa.ec.markt.tlmanager.core.ObjectFiller.java

/**
 * Ensure that all necessary fields are there to which a value might be bound
 * /*from   w  ww . j  ava 2 s  . c o  m*/
 * Note: There are different approaches for parsing data here. E.g. a 'PolicySet' could be stored in a
 * 'CriteriaListType' as well as in the 'otherCriteriaList' as 'AnyType'. However, the following annotation (taken
 * from ts_102231v030102_sie_xsd.xsd) is taken into account here:
 * --------
 * <complexType name="CriteriaListType">
 * <annotation>
 *      <documentation>Please first try to use the CriteriaList before doing the OtherCriteria extension
 *          point.</documentation>
 * </annotation>
 * --------
 *  
 * Note: values could be carried over, otherwise they are lost and
 * have to be reentered in TLManager Example: if there are PolicySets defined in otherCriteria, they could be parsed
 * and set directly below the criteriaList! Furthermore, especially this object seems to be a source for a multitude
 * of different interpretations throughout other MS TSL; data which is not stored in the correct objects (see
 * specification) cannot be parsed and have to be re-entered in TLManager.
 * 
 * @param element the <code>QualificationElementType</code> to fill
 * 
 * @return the filled object
 */
@SuppressWarnings("restriction")
public static QualificationElementType fillQualificationElement(QualificationElementType element)
        throws FillerException {
    try {
        CriteriaListType criteriaList = element.getCriteriaList();
        if (criteriaList == null) {
            criteriaList = objectFactoryECC.createCriteriaListType();
            element.setCriteriaList(criteriaList);
        }
        if (criteriaList.getAssert() == null || criteriaList.getAssert().isEmpty()) {
            criteriaList.setAssert(Util.DEFAULT_NO_SELECTION_ENTRY);
        }

        if (criteriaList.getKeyUsage().isEmpty()) {
            KeyUsageType keyUsageType = objectFactoryECC.createKeyUsageType();
            criteriaList.getKeyUsage().add(keyUsageType);
        }
        for (KeyUsageType keyUsage : criteriaList.getKeyUsage()) {
            fillKeyUsageType(keyUsage);
        }

        if (criteriaList.getPolicySet().isEmpty()) {
            PoliciesListType policiesListType = objectFactoryECC.createPoliciesListType();
            criteriaList.getPolicySet().add(policiesListType);
        }

        if (criteriaList.getOtherCriteriaList() == null) {
            criteriaList.setOtherCriteriaList(objectFactoryXADES.createAnyType());
        }

        boolean createEKUT = true, createCSDAT = true;
        List<Object> otherCriteriaContent = criteriaList.getOtherCriteriaList().getContent();
        if (otherCriteriaContent.isEmpty()) {

            ExtendedKeyUsageType extendedKeyUsageType = objectFactoryTSLX.createExtendedKeyUsageType();
            JAXBElement<ExtendedKeyUsageType> extendedKeyUsage = objectFactoryTSLX
                    .createExtendedKeyUsage(extendedKeyUsageType);

            CertSubjectDNAttributeType certSubjectDNAttributeType = objectFactoryTSLX
                    .createCertSubjectDNAttributeType();
            JAXBElement<CertSubjectDNAttributeType> certSubjectDNAttribute = objectFactoryTSLX
                    .createCertSubjectDNAttribute(certSubjectDNAttributeType);
            otherCriteriaContent.add(extendedKeyUsage);
            otherCriteriaContent.add(certSubjectDNAttribute);
        } else {
            for (Object othCrit : otherCriteriaContent) {
                if (othCrit instanceof JAXBElement<?>) {
                    JAXBElement<?> elem = (JAXBElement<?>) othCrit;

                    if (elem.getName().equals(QNames._ExtendedKeyUsage_QNAME)) {
                        createEKUT = false;
                    } else if (elem.getName().equals(QNames._CertSubjectDNAttribute_QNAME)) {
                        createCSDAT = false;
                    }
                }
            }
        }

        if (createEKUT) {
            ExtendedKeyUsageType extendedKeyUsageType = objectFactoryTSLX.createExtendedKeyUsageType();
            JAXBElement<ExtendedKeyUsageType> extendedKeyUsage = objectFactoryTSLX
                    .createExtendedKeyUsage(extendedKeyUsageType);
            otherCriteriaContent.add(extendedKeyUsage);
        }
        if (createCSDAT) {
            CertSubjectDNAttributeType certSubjectDNAttributeType = objectFactoryTSLX
                    .createCertSubjectDNAttributeType();
            JAXBElement<CertSubjectDNAttributeType> certSubjectDNAttribute = objectFactoryTSLX
                    .createCertSubjectDNAttribute(certSubjectDNAttributeType);
            otherCriteriaContent.add(certSubjectDNAttribute);
        }

        QualifiersType qualifiers = element.getQualifiers();
        if (qualifiers == null) {
            qualifiers = objectFactoryECC.createQualifiersType();
            element.setQualifiers(qualifiers);
        }
        final short NUMBER_OF_QUALIFIERS = 1;
        for (int i = 0; i < NUMBER_OF_QUALIFIERS; i++) {
            if (qualifiers.getQualifier().size() == i) {
                QualifierType qualifier = objectFactoryECC.createQualifierType();
                qualifier.setUri(Util.DEFAULT_NO_SELECTION_ENTRY);
                qualifiers.getQualifier().add(qualifier);
            }
        }
        // remove any qualifier besides of the first NUMBER_OF_QUALIFIERS (a loaded list may contain these)
        List<QualifierType> qualifierList = qualifiers.getQualifier();
        while (qualifierList.size() > NUMBER_OF_QUALIFIERS) {
            qualifierList = qualifierList.subList(0, NUMBER_OF_QUALIFIERS);
        }
    } catch (Exception ex) {
        throw new FillerException("fillQualificationElement", ex);
    }

    return element;
}

From source file:com.github.rinde.opt.localsearch.Insertions.java

/**
 * Inserts <code>item</code> in the specified indices in the
 * <code>originalList</code>.
 * @param originalList The list which will be inserted by <code>item</code>.
 * @param insertionIndices List of insertion indices in ascending order.
 * @param item The item to insert./* w  ww.  ja  va  2  s . co  m*/
 * @param <T> The list item type.
 * @return A list based on the original list but inserted with item in the
 *         specified places.
 */
public static <T> ImmutableList<T> insert(List<T> originalList, List<Integer> insertionIndices, T item) {
    checkArgument(!insertionIndices.isEmpty(), "At least one insertion index must be defined.");
    int prev = 0;
    final ImmutableList.Builder<T> builder = ImmutableList.<T>builder();
    for (int i = 0; i < insertionIndices.size(); i++) {
        final int cur = insertionIndices.get(i);
        checkArgument(cur >= 0 && cur <= originalList.size(),
                "The specified indices must be >= 0 and <= %s (list size), it is %s.", originalList.size(),
                cur);
        checkArgument(cur >= prev, "The specified indices must be in ascending order. Received %s.",
                insertionIndices);
        builder.addAll(originalList.subList(prev, cur));
        builder.add(item);
        prev = cur;
    }
    builder.addAll(originalList.subList(prev, originalList.size()));
    return builder.build();
}

From source file:io.hops.common.INodeUtil.java

public static Map<Long, List<Long>> getINodeIdsForBlockIds(final List<Long> blockIds, int batchSize,
        int nbThreads, ExecutorService executor) throws IOException {
    final Map<Long, List<Long>> inodeIds = new HashMap<>();

    try {/*from   w w w  .  j  a va2s  . com*/
        Slicer.slice(blockIds.size(), batchSize, nbThreads, executor, new Slicer.OperationHandler() {
            @Override
            public void handle(int startIndex, int endIndex) throws Exception {
                List<Long> ids = blockIds.subList(startIndex, endIndex);
                final long[] array = new long[ids.size()];
                int i = 0;
                for (long blockId : ids) {
                    array[i] = blockId;
                    i++;
                }
                LightWeightRequestHandler handler = new LightWeightRequestHandler(
                        HDFSOperationType.RESOLVE_INODES_FROM_BLOCKIDS) {
                    @Override
                    public Object performTask() throws IOException {
                        boolean transactionActive = connector.isTransactionActive();
                        try {

                            if (!transactionActive) {
                                connector.beginTransaction();
                            }
                            BlockLookUpDataAccess<BlockLookUp> da = (BlockLookUpDataAccess) HdfsStorageFactory
                                    .getDataAccess(BlockLookUpDataAccess.class);
                            Map<Long, List<Long>> inodeIds = da.getINodeIdsForBlockIds(array);
                            return inodeIds;
                        } finally {
                            if (!transactionActive) {
                                connector.commit();
                            }
                        }
                    }
                };
                try {
                    Map<Long, List<Long>> map = (Map<Long, List<Long>>) handler.handle();
                    synchronized (inodeIds) {
                        for (long inodeId : map.keySet()) {
                            List<Long> blockIds = inodeIds.get(inodeId);
                            if (blockIds == null) {
                                blockIds = new ArrayList<>();
                                inodeIds.put(inodeId, blockIds);
                            }
                            blockIds.addAll(map.get(inodeId));
                        }
                    }
                } catch (IOException ex) {
                    LOG.error("Could not resolve iNode from blockId (blockid=" + Arrays.toString(array) + ")");
                    throw new StorageException(ex.getMessage());
                }
            }
        });
    } catch (Exception ex) {
        throw new IOException(ex);
    }
    return inodeIds;
}

From source file:CV.java

public static Set<OWLIndividual> getTestingSet(List<OWLIndividual> examples, int[] splits, int fold) {
    int fromIndex;
    // we either start from 0 or after the last fold ended
    if (fold == 0)
        fromIndex = 0;//from  w w w .  j  a v a2  s  .c  o m
    else
        fromIndex = splits[fold - 1];
    // the split corresponds to the ends of the folds
    int toIndex = splits[fold];

    //      System.out.println("from " + fromIndex + " to " + toIndex);

    Set<OWLIndividual> testingSet = new HashSet<OWLIndividual>();
    // +1 because 2nd element is exclusive in subList method
    testingSet.addAll(examples.subList(fromIndex, toIndex));
    return testingSet;
}

From source file:edu.kit.dama.rest.client.generic.KIT_DM_REST_CLIENT.java

/**
 * This method can be used to list the already ingested and available digital
 * data from the KIT DM.//from  w w  w. j a  v a  2s. co  m
 * <b>Attention:</b> If there are more than 10 entries only the last 10
 * entries are listed.
 *
 * @param group specifying under which the ingested metadata will be searched
 * @return CommandStatus
 */
public static CommandStatus listContent(String group) {

    LOGGER.debug("Generating list of available data for group: " + group);

    List<IngestInformation> listEntries = clientHelper.getIngestInformationIDs(100,
            INGEST_STATUS.INGEST_FINISHED.getId());
    CommandStatus status = new CommandStatus(Status.SUCCESSFUL);

    // Get all IngestID
    // Get all Information for 'maxEntries' IDs
    int maxEntries = 10;
    int startIndex = 0;
    int noOfEntries = listEntries.size();

    List<IngestInformation> subList;
    if (noOfEntries < maxEntries) {
        subList = listEntries.subList(startIndex, noOfEntries);
    } else {
        // If more than 'maxEntries' the show only the last 'maxEntries'
        startIndex = noOfEntries - maxEntries;
        subList = listEntries.subList(startIndex, noOfEntries);
    }
    List<IngestInformation> ingestInformation = clientHelper.getIngestInformation(subList);
    // Get Detailed Information for each DigitalObject
    List<DigitalObject> digitalObjectInformationById = clientHelper.getDigitalObjectInformationById(group,
            ingestInformation);
    List<CustomOutputObject> customObjectsList = new ArrayList<>();

    for (DigitalObject digitalObject : digitalObjectInformationById) {
        UserData specificUser = clientHelper.getSpecificUser(digitalObject.getUploader().getUserId());
        CustomOutputObject customObject = new CustomOutputObject.CustomOutputObjectBuilder(specificUser,
                digitalObject).build();
        customObjectsList.add(customObject);
    }
    status.setReturnObject(customObjectsList);

    return status;
}

From source file:org.openlmis.fulfillment.util.Pagination.java

/**
 * Returns the Page for a subset of the specified list, determined by the pageable passed in.
 *
 * @param originalList A list of values, some or all of which should be included in a page.
 * @param pageable     An object used to encapsulate the pagination related values: page and
 *                     size./*w w w .  java 2  s .  c o m*/
 */
public static <T> Page<T> getPage(List<T> originalList, Pageable pageable) {
    int pageSize = getPageSize(pageable);
    int pageNumber = getPageNumber(pageable);

    int fromIndex = pageNumber * pageSize;
    int toIndex = fromIndex + pageSize;

    //Validate toIndex.
    //Note that toIndex is exclusive, which is why we don't want originalList.size() - 1.
    int maxPossibleToIndex = originalList.size();
    if (toIndex > maxPossibleToIndex) {
        toIndex = maxPossibleToIndex;
    }

    //Validate fromIndex
    int maxPossibleFromIndex = originalList.size() - 1;
    if (fromIndex > maxPossibleFromIndex) {
        // If the fronIndex is out of bounds, set it and toIndex to the same value.
        // This will cause us to return an empty list.
        fromIndex = toIndex = 0;
    }

    List<T> subList = originalList.subList(fromIndex, toIndex);
    return getPage(subList, pageable, originalList.size());
}

From source file:Main.java

public static <ELEMENT> List<ELEMENT> moveElementToIndex(List<ELEMENT> list, int fromIndex, int toIndex) {
    assertObjectNotNull("list", list);
    if (fromIndex == toIndex) {
        String msg = "The argument 'fromIndex' and 'toIndex' should not be same:";
        msg = msg + " fromIndex=" + fromIndex + " toIndex" + toIndex;
        throw new IllegalArgumentException(msg);
    }//from ww  w . ja  va2 s.  co  m
    if (fromIndex < 0 || toIndex < 0) {
        String msg = "The argument 'fromIndex' and 'toIndex' should not be minus:";
        msg = msg + " fromIndex=" + fromIndex + " toIndex" + toIndex;
        throw new IllegalArgumentException(msg);
    }
    final boolean fromLess = fromIndex < toIndex;
    final List<ELEMENT> movedList = new ArrayList<ELEMENT>();
    final int firstIndex = fromLess ? fromIndex : toIndex;
    final int secondIndex = !fromLess ? fromIndex : toIndex;
    final List<ELEMENT> first = list.subList(0, firstIndex);
    final ELEMENT element = list.get(fromIndex);
    final int adjustmentIndex = fromLess ? 1 : 0;
    final List<ELEMENT> middle = list.subList(firstIndex + adjustmentIndex, secondIndex + adjustmentIndex);
    final List<ELEMENT> last = list.subList(secondIndex + 1, list.size());
    movedList.addAll(first);
    if (!fromLess) {
        movedList.add(element);
    }
    movedList.addAll(middle);
    if (fromLess) {
        movedList.add(element);
    }
    movedList.addAll(last);
    return movedList;
}

From source file:amie.keys.CombinationsExplorationNew.java

public static HashSet<HashSet<Integer>> powerSet(HashSet<Integer> originalSet) {
    HashSet<HashSet<Integer>> sets = new HashSet<HashSet<Integer>>();
    if (originalSet.isEmpty()) {
        sets.add(new HashSet<Integer>());
        return sets;
    }/*from  w w w.j a v a2  s  . c om*/
    List<Integer> list = new ArrayList<Integer>(originalSet);
    int head = list.get(0);
    HashSet<Integer> rest = new HashSet<Integer>(list.subList(1, list.size()));
    for (HashSet<Integer> set : powerSet(rest)) {
        HashSet<Integer> newSet = new HashSet<Integer>();
        newSet.add(head);
        newSet.addAll(set);
        sets.add(newSet);
        sets.add(set);
    }
    return sets;
}

From source file:eionet.cr.web.util.JstlFunctions.java

/**
 *
 * @param coll/*from  www.jav a 2 s.co m*/
 * @param separator
 * @param sort
 * @param max
 * @return
 */
public static String joinCollection(Collection coll, char separator, boolean sort, int max) {

    if (coll == null || coll.isEmpty()) {
        return "";
    }

    // First, convert the collection objects to set (i.e. excluding duplicates) of strings, using every object's toString(),
    // or if the object is ObjectDTO, then special treatment.
    HashSet<String> set = new HashSet<String>();
    for (Object object : coll) {

        if (object != null) {
            String str = null;
            if (object instanceof ObjectDTO) {
                ObjectDTO objectDTO = (ObjectDTO) object;
                str = objectDTO.getValue();
                if (!objectDTO.isLiteral()) {
                    str = URIUtil.extractURILabel(str, str);
                }
            } else {
                str = object.toString();
            }
            if (StringUtils.isNotBlank(str)) {
                set.add(str);
            }
        }
    }

    // If set empty, then return.
    if (set.isEmpty()) {
        return "";
    }

    // Now convert the set to list.
    List<String> list = new ArrayList<String>(set);

    // If sorting requested, then do so.
    if (sort) {
        Collections.sort(list);
    }

    // Get first "max" elements if max is > 0 and smaller than list size
    if (max > 0 && max < list.size()) {
        list = list.subList(0, max);
        list.add("...");
    }

    // Finally, join the result by separator.
    return StringUtils.join(list, separator);
}