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

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

Introduction

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

Prototype

@Override
public final L getKey() 

Source Link

Document

Gets the key from this pair.

This method implements the Map.Entry interface returning the left element as the key.

Usage

From source file:org.kitodo.dataaccess.storage.memory.GraphPath.java

/**
 * Creates a node representing the graph path string.
 *
 * @param string/*w w  w .  ja v a2 s.com*/
 *            string to parse
 * @param prefixes
 *            a mapping of prefixes to namespaces which was used to shorten
 *            the string
 */
public GraphPath(String string, Map<String, String> prefixes) {
    super(GRAPH_PATH);
    int index = 0;
    Node graphPosition = this;
    int length = string.length();
    while (index < length) {
        while ((index < length) && (string.codePointAt(index) <= ' ')) {
            index++;
        }
        if ((index < length) && (string.codePointAt(index) == '[')) {
            index++;
            Pair<Integer, Node> parseObjectRecursive = parseObject(string.substring(index), prefixes);
            index += parseObjectRecursive.getKey();
            index++;
            graphPosition.put(RDF.OBJECT, parseObjectRecursive.getValue());
        } else {
            Node nextLocationStep = new MemoryNode(LOCATION_STEP);
            NodeReference direction = RDF.NIL;
            switch (index < length ? string.codePointAt(index) : -1) {
            case '<':
                throw new IllegalArgumentException("Directive '<' not supported.");
            case '>':
                index++;
                switch (index < length ? string.codePointAt(index) : -1) {
                case '>':
                    index++;
                    if ((index < length) && (string.codePointAt(index) == '>')) {
                        index++;
                        throw new IllegalArgumentException("Directive '>|' not supported.");
                    } else {
                        throw new IllegalArgumentException("Directive '>>' not supported.");
                    }
                case '|':
                    throw new IllegalArgumentException("Directive '>|' not supported.");
                default:
                    direction = TO;
                    break;
                }
                break;
            case '|':
                if (((index + 1) < length) && (string.codePointAt(index + 1) == '<')) {
                    throw new IllegalArgumentException("Directive '|<' not supported.");
                }
                break;
            default:
                direction = TO;
                break;
            }
            while ((index < length) && (string.codePointAt(index) <= ' ')) {
                index++;
            }
            graphPosition.put(direction, nextLocationStep);
            graphPosition = nextLocationStep;
            int predicatesStart = index;
            int codePoint;
            while ((index < length) && ((codePoint = string.codePointAt(index)) > ' ')) {
                index += Character.charCount(codePoint);
            }
            String predicates = string.substring(predicatesStart, index);
            if (!predicates.equals(ANY_PREDICATE_CHAR)) {
                for (String predicate : predicates.split("\\|")) {
                    graphPosition.put(RDF.PREDICATE, applyPrefixes(prefixes, predicate));
                }
            }
        }
    }
}

From source file:org.kitodo.dataaccess.storage.memory.GraphPath.java

/**
 * Parses an object from a graph path string.
 *
 * @param string//w  w  w .  ja  v a  2s  .c o m
 *            string to parse
 * @return the number of code points consumed and the object parsed
 */
private final Pair<Integer, Node> parseObject(String string, Map<String, String> prefixes) {
    int length = string.length();
    Node result = new MemoryNode();
    int index = 0;
    NodeReference currentPredicate = null;
    do {
        while ((index < length) && (string.codePointAt(index) <= ' ')) {
            index++;
        }
        if ((index >= length) || (string.codePointAt(index) == ']')) {
            return Pair.of(index, result);
        } else if (string.codePointAt(index) == ',') {
            index++;
            currentPredicate = null;
        } else if (string.codePointAt(index) == '[') {
            index++;
            Pair<Integer, Node> recursion = parseObject(string.substring(index), prefixes);
            index += recursion.getKey();
            index++;
            result.put(currentPredicate != null ? currentPredicate : ANY_PREDICATE, recursion.getValue());
        } else {
            if (currentPredicate == null) {
                int predicatesStart = index;
                int codePoint;
                while ((index < length) && ((codePoint = string.codePointAt(index)) > ' ')) {
                    index += Character.charCount(codePoint);
                }
                String predicate = string.substring(predicatesStart, index);
                currentPredicate = predicate.equals(ANY_PREDICATE_CHAR) ? ANY_PREDICATE
                        : MemoryStorage.INSTANCE.createNodeReference(applyPrefixes(prefixes, predicate));
            } else {
                int literalStart = index;
                int cp;
                while ((index < length) && ((cp = string.codePointAt(index)) > ' ') && (cp != ',')
                        && (cp != ']')) {
                    index += Character.charCount(cp);
                }
                String value = applyPrefixes(prefixes, string.substring(literalStart, index));
                result.put(currentPredicate, MemoryLiteral.createLeaf(value, null));
            }
        }
    } while (index < length);
    return Pair.of(length, result);
}

From source file:org.kitodo.dataaccess.storage.memory.MemoryNode.java

@Override
public Optional<Long> first() {
    Pair<Long, Long> range = range();
    return range == null ? Optional.empty() : Optional.of(range.getKey());
}

From source file:org.kitodo.dataaccess.storage.memory.MemoryNode.java

@Override
public List<Result> getEnumerated() {
    Pair<Long, Long> range = range();
    if (range == null) {
        return Collections.emptyList();
    }/*  w ww. j a v  a  2 s.c o  m*/
    ArrayList<Result> result = new ArrayList<>(range.getValue().intValue());
    for (long i = 0; i < (range.getKey() - 1); i++) {
        result.add(new MemoryResult());
    }
    for (long i = range.getKey(); i <= range.getValue(); i++) {
        result.add(get(i));
    }
    return result;
}

From source file:org.kitodo.dataaccess.storage.memory.MemoryNode.java

@Override
public boolean removeFirstOccurrence(Object object) {
    Pair<Long, Long> range = range();
    if (range == null) {
        return false;
    }/* ww w. j av a  2s. com*/
    for (long i = range.getKey(); i <= range.getValue(); i++) {
        String current = RDF.toURL(i);
        Collection<ObjectType> objects = edges.get(current);
        if (objects.remove(object)) {
            if (objects.isEmpty()) {
                edges.remove(current);
                long pos = i;
                String next;
                while (edges.containsKey(next = RDF.toURL(++pos))) {
                    edges.put(current, edges.remove(next));
                    current = next;
                }
            }
            return true;
        }
    }
    return false;
}

From source file:org.kitodo.dataaccess.storage.memory.MemoryNode.java

@Override
public boolean removeLastOccurrence(Object object) {
    Pair<Long, Long> range = range();
    if (range == null) {
        return false;
    }/*from ww  w .  ja  v a2s.  com*/
    for (long i = range.getValue(); i >= range.getKey(); i--) {
        String current = RDF.toURL(i);
        Collection<ObjectType> objects = edges.get(current);
        if (objects.remove(object)) {
            if (objects.isEmpty()) {
                edges.remove(current);
                long pos = i;
                String next;
                while (edges.containsKey(next = RDF.toURL(++pos))) {
                    edges.put(current, edges.remove(next));
                    current = next;
                }
            }
            return true;
        }
    }
    return false;
}

From source file:org.kitodo.dataeditor.ruleset.Labeled.java

/**
 * Lists the entries alphabetically by the translated label, taking into
 * account the language preferred by the user for alphabetical sorting. In
 * the auxiliary map, the keys are sorted by the sequence translated label +
 * separator + key, to account for the case where multiple keys are
 * (inadvertently) translated equally./*from  w  w  w.ja  v  a  2  s .  c o m*/
 *
 * @param ruleset
 *            The ruleset. From the ruleset, we learn which language is a
 *            label that does not have a language attribute, that is what is
 *            the default language of the rule set.
 * @param elements
 *            The items to sort. The function is so generic that you can
 *            sort divisions, keys, and options with it.
 * @param keyGetter
 *            A function to extract from the element the value used in the
 *            result map as key.
 * @param labelGetter
 *            A function that allows you to extract the list of labels from
 *            the element and then select the best translated one.
 * @param priorityList
 *            The list of languages spoken by the user human
 * @return a map in the order of the best-fitting translated label
 */
public static <T> LinkedHashMap<String, String> listByTranslatedLabel(Ruleset ruleset, Collection<T> elements,
        Function<T, String> keyGetter, Function<T, Collection<Label>> labelGetter,
        List<LanguageRange> priorityList) {

    Locale sortLocale = Locale.lookup(priorityList, Arrays.asList(Collator.getAvailableLocales()));
    TreeMap<String, Pair<String, String>> byLabelSorter = sortLocale != null
            ? new TreeMap<>(Collator.getInstance(sortLocale))
            : new TreeMap<>();
    for (T element : elements) {
        String key = keyGetter.apply(element);
        Labeled labeled = new Labeled(ruleset, key, labelGetter.apply(element));
        String label = labeled.getLabel(priorityList);
        byLabelSorter.put(label + '\037' + key, Pair.of(key, label));
    }
    LinkedHashMap<String, String> result = new LinkedHashMap<>((int) Math.ceil(elements.size() / 0.75));
    for (Pair<String, String> entry : byLabelSorter.values()) {
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}

From source file:org.kitodo.filemanagement.locking.ImmutableReadFileManagement.java

/**
 * Returns the immutable read copy for a user and a URI. If necessary, the
 * file must be created at this point./*from  w  w w.j  ava2 s  .co m*/
 *
 * @param user
 *            user for whom the immutable read copy is to be returned
 * @param uri
 *            URI for which the immutable read copy is to be returned
 * @return the immutable read copy
 * @throws IOException
 *             if the file does not exist or if an error occurs in disk
 *             access, e.g. because the write permission for the directory
 *             is missing
 */
URI getImmutableReadCopy(String user, URI uri) throws IOException {
    urisGivenToUsers.computeIfAbsent(uri, create -> new UserMapForURI());
    UserMapForURI userMapForURI = urisGivenToUsers.get(uri);
    if (userMapForURI.containsKey(user)) {
        Pair<URI, AtomicInteger> uriWithCount = userMapForURI.get(user);
        uriWithCount.getValue().incrementAndGet();
        return uriWithCount.getKey();
    } else {
        URI uriOfImmutableReadCopy = getUpToDateCopy(uri);
        userMapForURI.put(user, Pair.of(uriOfImmutableReadCopy, new AtomicInteger(1)));
        return uriOfImmutableReadCopy;
    }
}

From source file:org.kitodo.filemanagement.locking.ImmutableReadFileManagement.java

/**
 * Removes a reference to the use of a file as a temporary copy. If no
 * reference is left, the user is logged out of the temporary copy. Then it
 * will also be checked if the copy can be deleted.
 *
 * @param originUri/*from   w w  w  .j a va2 s.c om*/
 *            URI to which the user requested the immutable read lock, that
 *            is, the URI of the original file
 * @param user
 *            user who held the lock
 */
void maybeRemoveReadFile(URI originUri, String user) {
    UserMapForURI userMapForURI = urisGivenToUsers.get(originUri);
    if (Objects.nonNull(userMapForURI)) {
        Pair<URI, AtomicInteger> copyUriWithCount = userMapForURI.get(user);
        if (copyUriWithCount.getValue().decrementAndGet() == 0) {
            userMapForURI.remove(user);
            if (userMapForURI.isEmpty()) {
                urisGivenToUsers.remove(originUri);
            }
            cleanUp(copyUriWithCount.getKey(), originUri);
        }
    }
}

From source file:org.kitodo.production.forms.dataeditor.FieldedMetadataTableRow.java

/**
 * Reads the contents of the meta-data panel and stores the values in the
 * appropriate place. If the line is used to edit a field of the METS
 * structure, this field is set, otherwise the meta-data will be stored in
 * the list. The hidden meta-data is also written back there again.
 *
 * @throws InvalidMetadataValueException
 *             if the content of a meta-data input field is syntactically
 *             wrong/*from  w  w w.  j a v  a 2s  .  c  om*/
 * @throws NoSuchMetadataFieldException
 *             if an input shall be saved to a field of the structure, but
 *             there is no setter corresponding to the name configured in
 *             the rule set
 */
void preserve() throws InvalidMetadataValueException, NoSuchMetadataFieldException {
    try {
        metadata.clear();
        for (MetadataTableRow row : rows) {
            Pair<Method, Object> metsFieldValue = row.getStructureFieldValue();
            if (Objects.nonNull(metsFieldValue)) {
                try {
                    metsFieldValue.getKey().invoke(structure, metsFieldValue.getValue());
                } catch (IllegalAccessException | InvocationTargetException e) {
                    throw new IllegalStateException(e);
                }
            } else {
                metadata.addAll(row.getMetadata());
            }
        }
        metadata.addAll(hiddenMetadata);
    } catch (InvalidMetadataValueException invalidValueException) {
        if (Objects.isNull(structure)) {
            invalidValueException.addParent(metadataView.getId());
        }
        throw invalidValueException;
    }
}