Example usage for org.apache.commons.lang3 StringUtils countMatches

List of usage examples for org.apache.commons.lang3 StringUtils countMatches

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils countMatches.

Prototype

public static int countMatches(final CharSequence str, final char ch) 

Source Link

Document

Counts how many times the char appears in the given string.

A null or empty ("") String input returns 0 .

 StringUtils.countMatches(null, *)       = 0 StringUtils.countMatches("", *)         = 0 StringUtils.countMatches("abba", 0)  = 0 StringUtils.countMatches("abba", 'a')   = 2 StringUtils.countMatches("abba", 'b')  = 2 StringUtils.countMatches("abba", 'x') = 0 

Usage

From source file:org.owasp.dependencycheck.suppression.SuppressionRule.java

/**
 * Identifies if the cpe specified by the cpe suppression rule does not specify a version.
 *
 * @param c a suppression rule identifier
 * @return true if the property type does not specify a version; otherwise false
 *//*from  w  ww  . ja va2s .  c  om*/
boolean cpeHasNoVersion(PropertyType c) {
    return !c.isRegex() && StringUtils.countMatches(c.getValue(), ':') == 3;
}

From source file:org.polymap.recordstore.lucene.NumberValueCoder.java

public Query searchQuery(QueryExpression exp) {
    // EQUALS//from  w  w w.j a  v a 2  s .c  o  m
    if (exp instanceof QueryExpression.Equal) {
        Equal equalExp = (QueryExpression.Equal) exp;

        if (equalExp.value instanceof String) {
            return new TermQuery(new Term(equalExp.key, (String) equalExp.value));
        } else if (equalExp.value instanceof Integer) {
            String formatted = nf.format(equalExp.value);
            return new TermQuery(new Term(equalExp.key, formatted));
        }
    }
    // MATCHES
    else if (exp instanceof QueryExpression.Match) {
        Match matchExp = (Match) exp;

        if (matchExp.value instanceof String) {
            String value = (String) matchExp.value;

            // FIXME properly substitute wildcard chars
            if (value.endsWith("*") && StringUtils.countMatches(value, "*") == 1
                    && StringUtils.countMatches(value, "?") == 0) {
                return new PrefixQuery(new Term(matchExp.key, value.substring(0, value.length() - 1)));
            } else {
                return new WildcardQuery(new Term(matchExp.key, value));
            }
        }
    }
    return null;
}

From source file:org.polymap.recordstore.lucene.StringValueCoder.java

public Query searchQuery(QueryExpression exp) {
    // EQUALS//  w  w w. jav  a  2  s .  c om
    if (exp instanceof QueryExpression.Equal) {
        Equal equalExp = (QueryExpression.Equal) exp;

        if (equalExp.value == null) {
            throw new UnsupportedOperationException(
                    "Null values are not supported for expression: Equal(String)");
        } else if (equalExp.value instanceof String) {
            return new TermQuery(new Term(equalExp.key, (String) equalExp.value));
        }
    }
    // MATCHES
    else if (exp instanceof QueryExpression.Match) {
        Match matchExp = (Match) exp;

        if (matchExp.value == null) {
            throw new UnsupportedOperationException(
                    "Null values are not supported for expression: Match(String)");
        } else if (matchExp.value instanceof String) {
            String value = (String) matchExp.value;

            // XXX properly substitute wildcard chars
            if (value.endsWith("*") && StringUtils.countMatches(value, "*") == 1
                    && StringUtils.countMatches(value, "?") == 0) {
                return new PrefixQuery(new Term(matchExp.key, value.substring(0, value.length() - 1)));
            } else {
                return new WildcardQuery(new Term(matchExp.key, value));
            }
        }
    }
    return null;
}

From source file:org.primefaces.extensions.converter.JsonConverter.java

protected java.lang.reflect.Type getObjectType(String type, boolean isTypeArg) {
    Class clazz = PRIMITIVE_CLASSES.get(type);
    if (clazz != null) {
        if (!isTypeArg) {
            return clazz;
        } else {/*from w  w w. ja  va2s  .  c om*/
            throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Type argument can not be a primitive type, but it was " + type + ".",
                    Constants.EMPTY_STRING));
        }
    }

    clazz = PRIMITIVE_ARRAY_CLASSES.get(type);
    if (clazz != null) {
        return clazz;
    }

    int arrayBracketIdx = type.indexOf("[");
    int leftBracketIdx = type.indexOf("<");
    if (arrayBracketIdx >= 0 && (leftBracketIdx < 0 || arrayBracketIdx < leftBracketIdx)) {
        // array
        try {
            clazz = Class.forName(type.substring(0, arrayBracketIdx));

            return Array.newInstance(clazz, 0).getClass();
        } catch (ClassNotFoundException e) {
            throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Class " + type.substring(0, arrayBracketIdx) + " not found", Constants.EMPTY_STRING));
        }
    }

    if (leftBracketIdx < 0) {
        try {
            return Class.forName(type);
        } catch (ClassNotFoundException e) {
            throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Class " + type + " not found", Constants.EMPTY_STRING));
        }
    }

    int rightBracketIdx = type.lastIndexOf(">");
    if (rightBracketIdx < 0) {
        throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                type + " is not a valid generic type.", Constants.EMPTY_STRING));
    }

    Class rawType;
    try {
        rawType = Class.forName(type.substring(0, leftBracketIdx));
    } catch (ClassNotFoundException e) {
        throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                "Class " + type.substring(0, leftBracketIdx) + " not found", Constants.EMPTY_STRING));
    }

    String strTypeArgs = type.substring(leftBracketIdx + 1, rightBracketIdx);
    List<String> listTypeArgs = new ArrayList<String>();
    int startPos = 0;
    int seekPos = 0;

    while (true) {
        int commaPos = strTypeArgs.indexOf(",", seekPos);
        if (commaPos >= 0) {
            String term = strTypeArgs.substring(startPos, commaPos);
            int countLeftBrackets = StringUtils.countMatches(term, "<");
            int countRightBrackets = StringUtils.countMatches(term, ">");
            if (countLeftBrackets == countRightBrackets) {
                listTypeArgs.add(term.trim());
                startPos = commaPos + 1;
            }

            seekPos = commaPos + 1;
        } else {
            listTypeArgs.add(strTypeArgs.substring(startPos).trim());

            break;
        }
    }

    if (listTypeArgs.isEmpty()) {
        throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                type + " is not a valid generic type.", Constants.EMPTY_STRING));
    }

    int size = listTypeArgs.size();
    java.lang.reflect.Type[] objectTypes = new java.lang.reflect.Type[size];
    for (int i = 0; i < size; i++) {
        // recursive call for each type argument
        objectTypes[i] = getObjectType(listTypeArgs.get(i), true);
    }

    return new ParameterizedTypeImpl(rawType, objectTypes, null);
}

From source file:org.protocoder.fragments.EditorFragment.java

private int getCurrentCursorLine(Editable editable) {
    int selectionStartPos = Selection.getSelectionStart(editable);

    if (selectionStartPos < 0) {
        // There is no selection, so return -1 like getSelectionStart() does
        // when there is no seleciton.
        return -1;
    }//  w w  w  .  ja  v  a  2 s .c om

    String preSelectionStartText = editable.toString().substring(0, selectionStartPos);
    return StringUtils.countMatches(preSelectionStartText, "\n");
}

From source file:org.rdfhdt.hdt.impl.BufferedCompressedStreaming.java

/**
 * Process a molecule, i.e., set of triples around a common element (typically a subject)
 * /*from  w  ww . j  av a 2  s. c o m*/
 * @param elements
 */
public void processMolecule(ArrayList<TripleString> elements) {
    int tempIDSubject = 0;
    int tempIDPredicate = 0;
    int tempIDObject = 0;
    int tempIDStructure = 0;

    String subject = (String) elements.get(0).getSubject(); // could also be passed by argument
    Molecule mol = new Molecule();

    if (!store_subj_dictionary) {
        // check prefix and replace it if present
        Entry<String, Integer> entry = prefixes.getEntryShared(subject);
        if (entry != null) { // put only suffix
            mol.newSubject_prefix = entry.getValue();
            mol.newSubject = subject.substring(entry.getKey().length());
        } else {
            mol.newSubject_prefix = 0;
            mol.newSubject = subject;
        }
    } else { // store subject dictionary
        // Convert Subject-String to Subject-ID
        if (subjects.containsKey(subject)) {
            tempIDSubject = subjects.get(subject);
        } else {
            try {
                tempIDSubject = subjects.insert(subject);
            } catch (DictionaryException e) {
                System.err.println("LRU Dictionary exception");
                e.printStackTrace();
            }
            if (usePrefixes) {
                // check prefix and replace it if present
                Entry<String, Integer> entry = prefixes.getEntryShared(subject);

                if (entry != null) { // put only suffix
                    mol.newSubject_prefix = entry.getValue();
                    mol.newSubject = subject.substring(entry.getKey().length());
                } else {
                    mol.newSubject_prefix = 0;
                    mol.newSubject = subject;

                }
            } else {
                mol.newSubject_prefix = -1;
            }
        }
        // set molecule subject
        mol.subject = tempIDSubject;
    }

    String predicateStructure = "";
    String objectsDiscrete = "";
    Integer currPredicate = -1;

    Boolean isDiscretePredicate = false;
    String obj = "";
    for (int i = 0; i < elements.size(); i++) {

        obj = elements.get(i).getObject().toString();
        isDiscretePredicate = predicateDiscrete.get(elements.get(i).getPredicate().toString());
        if (predicates.containsKey(elements.get(i).getPredicate().toString())) {
            tempIDPredicate = predicates.get(elements.get(i).getPredicate().toString());
            // check dictionary of objects for this predicate

            // check discrete predicate
            if (isDiscretePredicate == null) {

                tempDictionary = objects.get(predicates.get(elements.get(i).getPredicate()) - 1);

                if (tempDictionary.containsKey(obj)) {
                    tempIDObject = tempDictionary.get(obj);
                    try {

                        mol.addObject(tempIDPredicate, tempIDObject);
                    } catch (BlockException e) {
                        System.err.println("Block exception");
                        e.printStackTrace();
                    }
                } else {
                    try {
                        tempIDObject = tempDictionary.insert(obj);

                        // erase object suffix
                        obj = elements.get(i).getObject().toString();

                        if (predicateLiterals.get(tempIDPredicate - 1)) {
                            // offset_tag=1 by default or it is =0 if disabled_consistent_predicates=true
                            obj = obj.substring(offset_tag,
                                    obj.length() - sizeofTags.get(tempIDPredicate - 1) - offset_tag);

                            mol.addnewObjectLiteral(tempIDPredicate, tempIDObject, obj);
                        } else {
                            if (usePrefixes) {
                                // replace predicate of URI
                                Integer newPreffixURI = 0;
                                // check prefix
                                Entry<String, Integer> entry = prefixes.getEntryShared(obj);

                                if (entry != null) { // put only suffix
                                    newPreffixURI = entry.getValue();
                                    obj = obj.substring(entry.getKey().length());
                                }
                                mol.addnewObjectURIBNode(tempIDPredicate, tempIDObject, obj, newPreffixURI);
                            } else {
                                mol.addnewObjectURIBNode(tempIDPredicate, tempIDObject, obj);
                            }
                        }

                    } catch (DictionaryException e) {
                        System.err.println("LRU Dictionary exception");
                        e.printStackTrace();
                    } catch (BlockException e) {
                        System.err.println("Block exception");
                        e.printStackTrace();
                    }
                }

            }

        } else {
            // insert new Predicate and create LRUDictionary for it
            tempIDPredicate = predicates.size() + 1;
            predicates.put(elements.get(i).getPredicate().toString(), predicates.size() + 1);
            LRUDictionary<String, Integer> newObjects = new LRUDictionary<String, Integer>(
                    CSVocabulary.DEFAULT_MAX_SIZE_DICTIONARY);
            // store the literal tag if present

            String tag = "";
            Boolean isliteral = false;
            Boolean detectedType = false;

            // check discrete predicate
            if (isDiscretePredicate == null) {

                if (!disable_consistent_predicates) {

                    if (obj.charAt(0) == '"') {
                        isliteral = true;

                        int pos_end = obj.lastIndexOf('"'); // tag after last '"'
                        if (obj.length() > (pos_end + 1)) {
                            tag = obj.substring(pos_end + 1);
                            obj = obj.substring(1, pos_end); // replace obj erasing tag

                        } else {
                            obj = obj.substring(1, pos_end); // replace obj erasing '"'
                            // trying to infer embedded tag before last '"'
                            int pos_tag = obj.indexOf("^^");
                            if (pos_tag > 0) {
                                tag = obj.substring(pos_tag) + '"'; // we maintain the last quote to distinguish the inference
                                obj = obj.substring(0, pos_tag); // replace obj erasing quotes '"'

                                detectedType = true;

                            }

                        }
                    }

                } else {
                    isliteral = true; // consider all literals to avoid change much code
                }

                predicateLiterals.set(tempIDPredicate - 1, isliteral);
                literalTagsByPredicate.add(tag); // set tag TODO it could be not needed, the sizeofTags is used instead.
                if (detectedType == false) {
                    sizeofTags.add(tag.length());

                } else {
                    sizeofTags.add(tag.length() - 1); // speed up processing for replacing, -1 to erase last quote character
                }

                try {
                    // replace erasing tags
                    tempIDObject = newObjects.insert(obj);

                    objects.add(newObjects);

                    mol.addNewPredicate(tempIDPredicate, elements.get(i).getPredicate().toString(), isliteral,
                            tag);

                    if (isliteral) {
                        mol.addnewObjectLiteral(tempIDPredicate, tempIDObject, obj);
                    } else {
                        // check prefix
                        Entry<String, Integer> entry = prefixes.getEntryShared(obj);
                        Integer newPreffixURI = 0;
                        if (entry != null) { // put only suffix
                            newPreffixURI = entry.getValue();
                            obj = obj.substring(entry.getKey().length());
                        }
                        mol.addnewObjectURIBNode(tempIDPredicate, tempIDObject, obj, newPreffixURI);
                    }
                } catch (DictionaryException e) {
                    System.err.println("LRU Dictionary exception");
                    e.printStackTrace();
                } catch (BlockException e) {
                    System.err.println("Block exception");
                    e.printStackTrace();
                }
            } else {
                // insert void properties: a void dictionary of objects andno tags
                objects.add(newObjects);
                sizeofTags.add(0);
                isliteral = (obj.charAt(0) == '"');
                mol.addNewPredicate(tempIDPredicate, elements.get(i).getPredicate().toString(), isliteral, "");
            }

        }
        if (currPredicate != tempIDPredicate) {
            if (currPredicate == -1) // first
                predicateStructure += tempIDPredicate;
            else
                predicateStructure += ";" + tempIDPredicate;
        } else {

            predicateStructure += ",";

        }
        // check discrete predicate and append objects
        if (isDiscretePredicate != null) {
            objectsDiscrete = objectsDiscrete + "$" + obj;
        }
        currPredicate = tempIDPredicate;

    }
    predicateStructure = predicateStructure + objectsDiscrete;
    // Insert structure
    if (structures.containsKey(predicateStructure)) {
        tempIDStructure = structures.get(predicateStructure);

        mol.addStructure(tempIDStructure); // add structure of the molecule
    } else {
        try {
            tempIDStructure = structures.insert(predicateStructure);

        } catch (DictionaryException e) {
            System.err.println("LRU Dictionary exception");
            e.printStackTrace();
        }

        // store new structure in compact way (list of predicate-ID and its
        // repetitions and objects discrete
        ArrayList<Integer> listPredsinStructure = new ArrayList<Integer>(5);
        ArrayList<String> allObjectsDiscrete = null;
        if (objectsDiscrete != "") {
            allObjectsDiscrete = new ArrayList<String>(Arrays.asList(objectsDiscrete.split("\\$")));
            allObjectsDiscrete.remove(0); // erase first void element

            predicateStructure = predicateStructure.substring(0,
                    predicateStructure.length() - objectsDiscrete.length());
        }
        String[] partsPredicates = predicateStructure.split(";");
        String currPred = "";
        Integer currPredID = 0;
        for (int j = 0; j < partsPredicates.length; j++) {
            // count if predicate is repeated several times
            int numRepeatedPredicates = StringUtils.countMatches(partsPredicates[j], ",");
            currPred = partsPredicates[j];

            if (numRepeatedPredicates > 0) {
                currPred = partsPredicates[j].substring(0, partsPredicates[j].indexOf(','));
            }
            currPredID = Integer.decode(currPred);
            // store predicate ID and number of repetitions
            listPredsinStructure.add(currPredID);
            listPredsinStructure.add(numRepeatedPredicates + 1); // +1 to count the initial triple (without ',').
        }

        mol.addNewStructure(tempIDStructure, listPredsinStructure, allObjectsDiscrete); // add new string structure
    }

    currentBlock.processMolecule(mol);
}

From source file:org.rdfhdt.hdt.impl.BufferedCompressedStreamingNoDictionary.java

/**
 * Process a molecule, i.e., set of triples around a common element (typically a subject)
 * //  w  w  w . ja  v a  2  s.c om
 * @param elements
 */
public void processMolecule(ArrayList<TripleString> elements) {
    int tempIDSubject = 0;
    int tempIDPredicate = 0;
    int tempIDObject = 0;
    int tempIDStructure = 0;

    String subject = (String) elements.get(0).getSubject(); // could also be passed by argument
    MoleculeNoDictionary mol = new MoleculeNoDictionary();

    if (!store_subj_dictionary) {
        // check prefix and replace it if present
        Entry<String, Integer> entry = prefixes.getEntryShared(subject);
        if (entry != null) { // put only suffix
            mol.newSubject_prefix = entry.getValue();
            mol.newSubject = subject.substring(entry.getKey().length());
        } else {
            mol.newSubject_prefix = 0;
            mol.newSubject = subject;
        }
    } else { // store subject dictionary
        // Convert Subject-String to Subject-ID
        if (subjects.containsKey(subject)) {
            tempIDSubject = subjects.get(subject);
        } else {
            try {
                tempIDSubject = subjects.insert(subject);
            } catch (DictionaryException e) {
                System.err.println("LRU Dictionary exception");
                e.printStackTrace();
            }
            if (usePrefixes) {
                // check prefix and replace it if present
                Entry<String, Integer> entry = prefixes.getEntryShared(subject);

                if (entry != null) { // put only suffix
                    mol.newSubject_prefix = entry.getValue();
                    mol.newSubject = subject.substring(entry.getKey().length());
                } else {
                    mol.newSubject_prefix = 0;
                    mol.newSubject = subject;

                }
            } else {
                mol.newSubject_prefix = -1;
            }
        }
        // set molecule subject
        mol.subject = tempIDSubject;
    }

    String predicateStructure = "";
    String objectsDiscrete = "";
    Integer currPredicate = -1;

    Boolean isDiscretePredicate = false;
    String obj = "";
    for (int i = 0; i < elements.size(); i++) {

        obj = elements.get(i).getObject().toString();
        isDiscretePredicate = predicateDiscrete.get(elements.get(i).getPredicate().toString());
        if (predicates.containsKey(elements.get(i).getPredicate().toString())) {
            tempIDPredicate = predicates.get(elements.get(i).getPredicate().toString());
            // check dictionary of objects for this predicate

            // check discrete predicate
            if (isDiscretePredicate == null) {

                try {

                    // erase object suffix
                    obj = elements.get(i).getObject().toString();

                    if (predicateLiterals.get(tempIDPredicate - 1)) {
                        // offset_tag=1 by default or it is =0 if disabled_consistent_predicates=true
                        obj = obj.substring(offset_tag,
                                obj.length() - sizeofTags.get(tempIDPredicate - 1) - offset_tag);

                        mol.addnewObjectLiteral(tempIDPredicate, tempIDObject, obj);
                    } else {
                        if (usePrefixes) {
                            // replace predicate of URI
                            Integer newPreffixURI = 0;
                            // check prefix
                            Entry<String, Integer> entry = prefixes.getEntryShared(obj);

                            if (entry != null) { // put only suffix
                                newPreffixURI = entry.getValue();
                                obj = obj.substring(entry.getKey().length());
                            }
                            mol.addnewObjectURIBNode(tempIDPredicate, tempIDObject, obj, newPreffixURI);
                        } else {
                            mol.addnewObjectURIBNode(tempIDPredicate, tempIDObject, obj);
                        }
                    }

                } catch (BlockException e) {
                    System.err.println("Block exception");
                    e.printStackTrace();
                }

            }

        } else {
            // insert new Predicate and create LRUDictionary for it
            tempIDPredicate = predicates.size() + 1;

            predicates.put(elements.get(i).getPredicate().toString(), predicates.size() + 1);

            // store the literal tag if present

            String tag = "";
            Boolean isliteral = false;
            Boolean detectedType = false;

            // check discrete predicate
            if (isDiscretePredicate == null) {

                if (!disable_consistent_predicates) {

                    if (obj.charAt(0) == '"') {
                        isliteral = true;

                        int pos_end = obj.lastIndexOf('"'); // tag after last '"'
                        if (obj.length() > (pos_end + 1)) {
                            tag = obj.substring(pos_end + 1);
                            obj = obj.substring(1, pos_end); // replace obj erasing tag

                        } else {
                            obj = obj.substring(1, pos_end); // replace obj erasing '"'
                            // trying to infer embedded tag before last '"'
                            int pos_tag = obj.indexOf("^^");
                            if (pos_tag > 0) {
                                tag = obj.substring(pos_tag) + '"'; // we maintain the last quote to distinguish the inference
                                obj = obj.substring(0, pos_tag); // replace obj erasing quotes '"'

                                detectedType = true;

                            }

                        }
                    }

                } else {
                    isliteral = true; // consider all literals to avoid change much code
                }

                predicateLiterals.set(tempIDPredicate - 1, isliteral);
                literalTagsByPredicate.add(tag); // set tag TODO it could be not needed, the sizeofTags is used instead.
                if (detectedType == false) {
                    sizeofTags.add(tag.length());

                } else {
                    sizeofTags.add(tag.length() - 1); // speed up processing for replacing, -1 to erase last quote character
                }

                try {

                    mol.addNewPredicate(tempIDPredicate, elements.get(i).getPredicate().toString(), isliteral,
                            tag);

                    if (isliteral) {
                        mol.addnewObjectLiteral(tempIDPredicate, tempIDObject, obj);
                    } else {
                        // check prefix
                        Entry<String, Integer> entry = prefixes.getEntryShared(obj);
                        Integer newPreffixURI = 0;
                        if (entry != null) { // put only suffix
                            newPreffixURI = entry.getValue();
                            obj = obj.substring(entry.getKey().length());
                        }
                        mol.addnewObjectURIBNode(tempIDPredicate, tempIDObject, obj, newPreffixURI);
                    }

                } catch (BlockException e) {
                    System.err.println("Block exception");
                    e.printStackTrace();
                }
            } else {
                // insert void properties: a void dictionary of objects and no tags

                sizeofTags.add(0);
                isliteral = (obj.charAt(0) == '"');
                mol.addNewPredicate(tempIDPredicate, elements.get(i).getPredicate().toString(), isliteral, "");
            }

        }
        if (currPredicate != tempIDPredicate) {
            if (currPredicate == -1) // first
                predicateStructure += tempIDPredicate;
            else
                predicateStructure += ";" + tempIDPredicate;
        } else {

            predicateStructure += ",";

        }
        // check discrete predicate and append objects
        if (isDiscretePredicate != null) {
            objectsDiscrete = objectsDiscrete + "$" + obj;
        }
        currPredicate = tempIDPredicate;

    }
    predicateStructure = predicateStructure + objectsDiscrete;
    // Insert structure
    if (structures.containsKey(predicateStructure)) {
        tempIDStructure = structures.get(predicateStructure);

        mol.addStructure(tempIDStructure); // add structure of the molecule
    } else {
        try {
            tempIDStructure = structures.insert(predicateStructure);

        } catch (DictionaryException e) {
            System.err.println("LRU Dictionary exception");
            e.printStackTrace();
        }

        // store new structure in compact way (list of predicate-ID and its
        // repetitions and objects discrete
        ArrayList<Integer> listPredsinStructure = new ArrayList<Integer>(5);
        ArrayList<String> allObjectsDiscrete = null;
        if (objectsDiscrete != "") {
            allObjectsDiscrete = new ArrayList<String>(Arrays.asList(objectsDiscrete.split("\\$")));
            allObjectsDiscrete.remove(0); // erase first void element

            predicateStructure = predicateStructure.substring(0,
                    predicateStructure.length() - objectsDiscrete.length());
        }
        String[] partsPredicates = predicateStructure.split(";");
        String currPred = "";
        Integer currPredID = 0;
        for (int j = 0; j < partsPredicates.length; j++) {
            // count if predicate is repeated several times
            int numRepeatedPredicates = StringUtils.countMatches(partsPredicates[j], ",");
            currPred = partsPredicates[j];

            if (numRepeatedPredicates > 0) {
                currPred = partsPredicates[j].substring(0, partsPredicates[j].indexOf(','));
            }
            currPredID = Integer.decode(currPred);
            // store predicate ID and number of repetitions
            listPredsinStructure.add(currPredID);
            listPredsinStructure.add(numRepeatedPredicates + 1); // +1 to count the initial triple (without ',').
        }

        mol.addNewStructure(tempIDStructure, listPredsinStructure, allObjectsDiscrete); // add new string structure
    }

    currentBlock.processMolecule(mol);
}

From source file:org.roda.core.model.utils.ModelUtils.java

public static StoragePath getPreservationMetadataStoragePath(String id, PreservationMetadataType type,
        String aipId, String representationId, List<String> fileDirectoryPath, String fileId)
        throws RequestNotValidException {
    List<String> path;
    if (type != null) {
        if (type.equals(PreservationMetadataType.AGENT)) {
            path = Arrays.asList(RodaConstants.STORAGE_CONTAINER_PRESERVATION,
                    RodaConstants.STORAGE_DIRECTORY_AGENTS, id + RodaConstants.PREMIS_SUFFIX);
        } else if (type.equals(PreservationMetadataType.REPRESENTATION)) {
            if (aipId != null && representationId != null) {
                String pFileId = id + RodaConstants.PREMIS_SUFFIX;
                path = build(getRepresentationPreservationMetadataPath(aipId, representationId), pFileId);
            } else {
                throw new RequestNotValidException(
                        "Cannot request a representation object with null AIP or Representation. " + "AIP id = "
                                + aipId + " and Representation id = " + representationId);
            }/*from w w  w  .  ja va2  s  .co m*/
        } else if (type.equals(PreservationMetadataType.EVENT)) {
            String pFileId = id + RodaConstants.PREMIS_SUFFIX;
            if (aipId != null) {
                if (representationId != null) {
                    if (fileId != null) {
                        path = getRepresentationPreservationMetadataPath(aipId, representationId);
                        if (fileDirectoryPath != null) {
                            path.addAll(fileDirectoryPath);
                        }

                        try {
                            String separator = URLEncoder.encode(RodaConstants.URN_SEPARATOR,
                                    RodaConstants.DEFAULT_ENCODING);
                            if (StringUtils.countMatches(id, separator) > 0) {
                                path.add(id + RodaConstants.PREMIS_SUFFIX);
                            } else {
                                path.add(id + separator + fileId + RodaConstants.PREMIS_SUFFIX);
                            }
                        } catch (UnsupportedEncodingException e) {
                            LOGGER.error(
                                    "Error encoding urn separator when creating file event preservation metadata");
                        }
                    } else {
                        path = build(getRepresentationPreservationMetadataPath(aipId, representationId),
                                pFileId);
                    }
                } else {
                    path = build(getAIPPreservationMetadataPath(aipId), pFileId);
                }
            } else {
                path = Arrays.asList(RodaConstants.STORAGE_CONTAINER_PRESERVATION,
                        RodaConstants.STORAGE_DIRECTORY_EVENTS, id + RodaConstants.PREMIS_SUFFIX);
            }
        } else if (type.equals(PreservationMetadataType.FILE)) {
            path = getRepresentationMetadataPath(aipId, representationId);
            path.add(RodaConstants.STORAGE_DIRECTORY_PRESERVATION);
            if (fileDirectoryPath != null) {
                path.addAll(fileDirectoryPath);
            }
            path.add(id + RodaConstants.PREMIS_SUFFIX);
        } else if (type.equals(PreservationMetadataType.OTHER)) {
            path = getRepresentationMetadataPath(aipId, representationId);
            path.add(RodaConstants.STORAGE_DIRECTORY_PRESERVATION);
            path.add(RodaConstants.STORAGE_DIRECTORY_OTHER_TECH_METADATA);
            if (fileDirectoryPath != null) {
                path.addAll(fileDirectoryPath);
            }
            path.add(fileId + RodaConstants.OTHER_TECH_METADATA_FILE_SUFFIX);
        } else {
            throw new RequestNotValidException("Unsupported preservation metadata type: " + type);
        }
    } else {
        throw new RequestNotValidException("Preservation metadata type is null");
    }

    return DefaultStoragePath.parse(path);
}

From source file:org.roda.core.model.utils.ResourceParseUtils.java

private static PreservationMetadata convertResourceToPreservationMetadata(Resource resource)
        throws RequestNotValidException {

    if (resource == null) {
        throw new RequestNotValidException(RESOURCE_CANNOT_BE_NULL);
    }/*from   w w  w . j a v a2  s .  co  m*/

    StoragePath resourcePath = resource.getStoragePath();
    String filename = resourcePath.getName();
    PreservationMetadata pm = new PreservationMetadata();

    String id;
    String aipId = ModelUtils.extractAipId(resourcePath);
    String representationId = ModelUtils.extractRepresentationId(resourcePath);
    List<String> fileDirectoryPath = null;
    String fileId = null;

    PreservationMetadataType type;
    if (filename.startsWith(URNUtils.getPremisPrefix(PreservationMetadataType.AGENT))) {
        id = filename.substring(0, filename.length() - RodaConstants.PREMIS_SUFFIX.length());
        type = PreservationMetadataType.AGENT;
        aipId = null;
        representationId = null;
    } else if (filename.startsWith(URNUtils.getPremisPrefix(PreservationMetadataType.EVENT))) {
        id = filename.substring(0, filename.length() - RodaConstants.PREMIS_SUFFIX.length());
        type = PreservationMetadataType.EVENT;
        try {
            String separator = URLEncoder.encode(RodaConstants.URN_SEPARATOR, RodaConstants.DEFAULT_ENCODING);
            if (StringUtils.countMatches(id, separator) > 0) {
                fileDirectoryPath = ModelUtils
                        .extractFilePathFromRepresentationPreservationMetadata(resourcePath);
                fileId = id.substring(id.lastIndexOf(separator) + 1);
            }
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("Error encoding urn separator when converting file event preservation metadata");
        }
    } else if (filename.startsWith(URNUtils.getPremisPrefix(PreservationMetadataType.FILE))) {
        type = PreservationMetadataType.FILE;
        fileDirectoryPath = ModelUtils.extractFilePathFromRepresentationPreservationMetadata(resourcePath);
        fileId = filename.substring(0, filename.length() - RodaConstants.PREMIS_SUFFIX.length());
        id = fileId;
    } else if (filename.startsWith(URNUtils.getPremisPrefix(PreservationMetadataType.OTHER))) {
        type = PreservationMetadataType.OTHER;
        fileDirectoryPath = ModelUtils.extractFilePathFromRepresentationPreservationMetadata(resourcePath);
        fileId = filename.substring(0, filename.length() - RodaConstants.PREMIS_SUFFIX.length());
        id = fileId;
    } else if (filename.startsWith(URNUtils.getPremisPrefix(PreservationMetadataType.REPRESENTATION))) {
        id = filename.substring(0, filename.length() - RodaConstants.PREMIS_SUFFIX.length());
        type = PreservationMetadataType.REPRESENTATION;
    } else {
        throw new RequestNotValidException("Unsupported PREMIS extension type in file: " + filename);
    }

    pm.setId(id);
    pm.setAipId(aipId);
    pm.setRepresentationId(representationId);
    pm.setFileDirectoryPath(fileDirectoryPath);
    pm.setFileId(fileId);
    pm.setType(type);

    return pm;
}

From source file:org.roda.core.plugins.AIPCorruptionRiskAssessmentTest.java

@Test
public void testAIPCorruption() throws RODAException {
    String aipId = IdUtils.createUUID();
    model.createAIP(aipId, corporaService, DefaultStoragePath.parse(CorporaConstants.SOURCE_AIP_CONTAINER,
            CorporaConstants.SOURCE_AIP_CORRUPTED), RodaConstants.ADMIN);

    Job job = TestsHelper.executeJob(AIPCorruptionRiskAssessmentPlugin.class, PluginType.AIP_TO_AIP,
            SelectedItemsList.create(AIP.class, Arrays.asList(aipId)));

    List<Report> jobReports = TestsHelper.getJobReports(index, job, false);
    int count = StringUtils.countMatches(jobReports.get(0).getPluginDetails(),
            "<div class=\"entry level_error\">");
    index.commit(RiskIncidence.class);
    long incidences = index.count(RiskIncidence.class, Filter.ALL);

    // 3 errors: 1 checksum checking error, 1 file without premis, 1 premis
    // without file
    Assert.assertEquals(count, 3);/*from w  w  w.  jav  a2s. c o  m*/
    Assert.assertEquals(incidences, 3);
    Assert.assertEquals(jobReports.get(0).getPluginState(), PluginState.FAILURE);
}