Example usage for org.apache.commons.lang StringUtils substringAfterLast

List of usage examples for org.apache.commons.lang StringUtils substringAfterLast

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils substringAfterLast.

Prototype

public static String substringAfterLast(String str, String separator) 

Source Link

Document

Gets the substring after the last occurrence of a separator.

Usage

From source file:org.betaconceptframework.astroboa.test.engine.service.ContentServiceTest.java

private ContentObject saveAndAssertBinaryContentIsSaved(ContentObject contentObject, String contentSource,
        File fileWhichContainsContent, String property, Map<String, byte[]> binaryContent) throws Exception {
    try {//  w w  w.  j a  v a  2  s.c o m

        ImportConfiguration configuration = ImportConfiguration.object()
                .persist(PersistMode.PERSIST_ENTITY_TREE).version(false).updateLastModificationTime(true)
                .addBinaryContent(binaryContent).build();

        contentObject = importService.importContentObject(contentSource, configuration);

        //reload object 
        ContentObject object = contentService.getContentObject(contentObject.getId(),
                ResourceRepresentationType.CONTENT_OBJECT_INSTANCE, FetchLevel.ENTITY, CacheRegion.NONE, null,
                false);

        BinaryProperty imageProperty = (BinaryProperty) object.getCmsProperty(property);

        Assert.assertTrue(imageProperty.hasValues(), "No binary channel saved for " + property + " property");

        for (BinaryChannel imageBinaryChannel : imageProperty.getSimpleTypeValues()) {

            String sourceFilename = imageBinaryChannel.getSourceFilename();

            Assert.assertTrue(StringUtils.isNotBlank(sourceFilename),
                    " BinaryChannel " + imageBinaryChannel.getName() + " does not have a source file name");

            File fileWhoseContentsAreSavedInBinaryChannel = null;

            if (sourceFilename.equals(fileWhichContainsContent.getName())) {
                fileWhoseContentsAreSavedInBinaryChannel = fileWhichContainsContent;
            } else {
                throw new Exception("BnaryChannel contains an invalid source file name " + sourceFilename);
            }

            String mimeType = new MimetypesFileTypeMap()
                    .getContentType(fileWhoseContentsAreSavedInBinaryChannel);

            if (property.contains(".")) {
                Assert.assertEquals(imageBinaryChannel.getName(),
                        StringUtils.substringAfterLast(property, "."));
            } else {
                Assert.assertEquals(imageBinaryChannel.getName(), property);
            }
            Assert.assertEquals(imageBinaryChannel.getMimeType(), mimeType);
            Assert.assertEquals(imageBinaryChannel.getSourceFilename(), sourceFilename);
            Assert.assertEquals(imageBinaryChannel.getSize(),
                    FileUtils.readFileToByteArray(fileWhoseContentsAreSavedInBinaryChannel).length);
            Assert.assertEquals(imageBinaryChannel.getModified().getTimeInMillis(),
                    fileWhoseContentsAreSavedInBinaryChannel.lastModified());

            //Now test in jcr to see if the proper node is created
            Node binaryChannelNode = getSession().getNodeByIdentifier(imageBinaryChannel.getId());

            //If node is not found then exception has already been thrown
            Assert.assertEquals(binaryChannelNode.getName(), imageBinaryChannel.getName(),
                    " Invalid name for binary data jcr node " + binaryChannelNode.getPath());

            if (property.contains(".")) {
                Assert.assertEquals(binaryChannelNode.getProperty(CmsBuiltInItem.Name.getJcrName()).getString(),
                        StringUtils.substringAfterLast(property, "."));
            } else {
                Assert.assertEquals(binaryChannelNode.getProperty(CmsBuiltInItem.Name.getJcrName()).getString(),
                        property);
            }

            Assert.assertEquals(
                    binaryChannelNode.getProperty(JcrBuiltInItem.JcrMimeType.getJcrName()).getString(),
                    mimeType);
            Assert.assertEquals(
                    binaryChannelNode.getProperty(CmsBuiltInItem.SourceFileName.getJcrName()).getString(),
                    sourceFilename);
            Assert.assertEquals(binaryChannelNode.getProperty(CmsBuiltInItem.Size.getJcrName()).getLong(),
                    fileWhoseContentsAreSavedInBinaryChannel.length());
            Assert.assertEquals(binaryChannelNode.getProperty(JcrBuiltInItem.JcrLastModified.getJcrName())
                    .getDate().getTimeInMillis(), fileWhoseContentsAreSavedInBinaryChannel.lastModified());

        }

    } catch (Exception e) {
        logger.error("Initial \n{}", contentSource);
        throw e;
    }

    return contentObject;
}

From source file:org.betaconceptframework.astroboa.util.PropertyPath.java

public static String getLastDescendant(String propertyPath) {

    String lastDescendant = StringUtils.substringAfterLast(propertyPath, CmsConstants.PERIOD_DELIM);

    //If no lastDescendant exists return the same propertyPath
    return (StringUtils.isBlank(lastDescendant) ? propertyPath : lastDescendant);

}

From source file:org.betaconceptframework.astroboa.util.PropertyPath.java

public static int extractIndexFromPath(String propertyPath) {
    if (StringUtils.isBlank(propertyPath) || !propertyPath.endsWith(CmsConstants.RIGHT_BRACKET))
        return NO_INDEX;

    try {/*from ww  w  .  j  a  va  2s.c  o m*/
        //Get everything after last '['
        String index = StringUtils.substringAfterLast(propertyPath, CmsConstants.LEFT_BRACKET);

        //Normally what is left is a number followed by a right bracket
        index = StringUtils.substringBeforeLast(index, CmsConstants.RIGHT_BRACKET);

        if (StringUtils.isBlank(index))
            return NO_INDEX;

        return Integer.parseInt(index);
    } catch (Exception e) {
        throw new CmsException(e);
    }

}

From source file:org.betaconceptframework.astroboa.util.ResourceApiURLUtils.java

public static String retrieveSchemaFileName(CmsDefinition cmsDefinition) {

    URI cmsDefinitionFileURI = null;

    if (cmsDefinition instanceof ContentObjectTypeDefinition) {
        cmsDefinitionFileURI = ((ContentObjectTypeDefinitionImpl) cmsDefinition).getDefinitionFileURI();
    } else if (cmsDefinition instanceof ComplexCmsPropertyDefinition) {
        cmsDefinitionFileURI = ((ComplexCmsPropertyDefinitionImpl) cmsDefinition).getDefinitionFileURI();
    } else if (cmsDefinition instanceof SimpleCmsPropertyDefinition) {
        //It is a simple property. Get its parent to provide with the URI
        CmsDefinition parentDefinition = ((SimpleCmsPropertyDefinition) cmsDefinition).getParentDefinition();
        if (parentDefinition != null && parentDefinition instanceof ComplexCmsPropertyDefinition) {
            cmsDefinitionFileURI = ((ComplexCmsPropertyDefinitionImpl) parentDefinition).getDefinitionFileURI();
        }/*from   www.  j a  v  a  2 s  .  com*/
    }

    if (cmsDefinitionFileURI == null) {
        return null;
    }

    String schemaFilename = StringUtils.substringAfterLast(cmsDefinitionFileURI.toString(), File.separator);

    if (StringUtils.isBlank(schemaFilename)) {
        if (!File.separator.equals(CmsConstants.FORWARD_SLASH)) {
            //try with forward slash.
            schemaFilename = StringUtils.substringAfterLast(cmsDefinitionFileURI.toString(),
                    CmsConstants.FORWARD_SLASH);
        }
    }

    if (StringUtils.isBlank(schemaFilename)) {
        return null;
    }

    return schemaFilename;
}

From source file:org.candlepin.resource.JobResource.java

private String prettyPrintJobs(String... jobs) {
    List<String> jobNames = new ArrayList<String>();
    for (String job : jobs) {
        jobNames.add(StringUtils.substringAfterLast(job, "."));
    }/*w  w  w.  ja  va  2s.co m*/
    return StringUtils.join(jobNames, ", ");
}

From source file:org.codehaus.groovy.grails.web.binding.GrailsDataBinder.java

private Class<?> getPropertyTypeForPath(String propertyName) {
    Class<?> type = bean.getPropertyType(propertyName);
    if (type == null) {
        // type not available via BeanWrapper - this happens with e.g. empty list indexes - so
        // find type by examining GrailsDomainClass
        Object target = bean.getWrappedInstance();
        String path = propertyName.replaceAll("\\[.+?\\]", "");
        if (path.indexOf(PATH_SEPARATOR) > -1) {
            // transform x.y.z into value of x.y and path z
            String nestedProp = StringUtils.substringBeforeLast(propertyName, ".");
            target = bean.getPropertyValue(nestedProp);
            path = StringUtils.substringAfterLast(path, ".");
        }//  w  w w . j  a v a2s.co  m
        if (target != null) {
            type = getReferencedTypeForCollection(path, target);
        }
    }
    return type;
}

From source file:org.codehaus.groovy.grails.web.binding.GrailsDataBinder.java

private boolean propertyStartsWithFieldMarkerPrefix(PropertyValue pv, String fieldMarkerPrefix) {
    String propertyName = pv.getName().indexOf(PATH_SEPARATOR) > -1
            ? StringUtils.substringAfterLast(pv.getName(), ".")
            : pv.getName();//from  w  ww.  j av  a 2 s  .  co  m
    return propertyName.startsWith(fieldMarkerPrefix);
}

From source file:org.codice.ddf.catalog.ui.config.ConfigurationApplication.java

public String getProductVersion() {
    if (branding != null) {
        // Remove the version number
        return StringUtils.substringAfterLast(branding.getProductName(), " ");
    } else {/*from   w  w w. j  av a2  s. c o m*/
        return "";
    }
}

From source file:org.codice.ddf.commands.solr.BackupCommandTest.java

private String getRequestId(String consoleOutput) {
    return StringUtils.trim(
            StringUtils.substringAfterLast(ASCII_COLOR_CODES_REGEX.matcher(consoleOutput).replaceAll(""), ":"));
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.common.GetRecordsRequest.java

/**
 * Convert the KVP values into a GetRecordsType, validates format of fields and enumeration
 * constraints required to meet the schema requirements of the GetRecordsType. No further
 * validation is done at this point//from  w w  w .ja  va  2 s .  c om
 *
 * @return GetRecordsType representation of this key-value representation
 * @throws CswException
 *             An exception when some field cannot be converted to the equivalent GetRecordsType
 *             value
 */
public GetRecordsType get202RecordsType() throws CswException {
    GetRecordsType getRecords = new GetRecordsType();

    getRecords.setOutputSchema(getOutputSchema());
    getRecords.setRequestId(getRequestId());

    if (getMaxRecords() != null) {
        getRecords.setMaxRecords(getMaxRecords());
    }
    if (getStartPosition() != null) {
        getRecords.setStartPosition(getStartPosition());
    }
    if (getOutputFormat() != null) {
        getRecords.setOutputFormat(getOutputFormat());
    }
    if (getResponseHandler() != null) {
        getRecords.setResponseHandler(Arrays.asList(getResponseHandler()));
    }
    if (getResultType() != null) {
        try {
            getRecords.setResultType(ResultType.fromValue(getResultType()));
        } catch (IllegalArgumentException iae) {
            LOGGER.warn("Failed to find \"{}\" as a valid ResultType, Exception {}", getResultType(), iae);
            throw new CswException(
                    "A CSW getRecords request ResultType must be \"hits\", \"results\", or \"validate\"");
        }
    }
    if (getDistributedSearch() != null && getDistributedSearch()) {
        DistributedSearchType disSearch = new DistributedSearchType();
        disSearch.setHopCount(getHopCount());
        getRecords.setDistributedSearch(disSearch);
    }

    QueryType query = new QueryType();

    Map<String, String> namespaces = parseNamespaces(getNamespace());
    List<QName> typeNames = typeStringToQNames(getTypeNames(), namespaces);
    query.setTypeNames(typeNames);

    if (getElementName() != null && getElementSetName() != null) {
        LOGGER.warn(
                "CSW getRecords request received with mutually exclusive ElementName and SetElementName set");
        throw new CswException(
                "A CSW getRecords request can only have an \"ElementName\" or an \"ElementSetName\"");
    }

    if (getElementName() != null) {
        query.setElementName(typeStringToQNames(getElementName(), namespaces));
    }

    if (getElementSetName() != null) {
        try {
            ElementSetNameType eleSetName = new ElementSetNameType();
            eleSetName.setTypeNames(typeNames);
            eleSetName.setValue(ElementSetType.fromValue(getElementSetName()));
            query.setElementSetName(eleSetName);
        } catch (IllegalArgumentException iae) {
            LOGGER.warn("Failed to find \"{}\" as a valid elementSetType, Exception {}", getElementSetName(),
                    iae);
            throw new CswException(
                    "A CSW getRecords request ElementSetType must be \"brief\", \"summary\", or \"full\"");
        }

    }

    if (getSortBy() != null) {
        SortByType sort = new SortByType();

        List<SortPropertyType> sortProps = new LinkedList<SortPropertyType>();

        String[] sortOptions = getSortBy().split(",");

        for (String sortOption : sortOptions) {
            if (sortOption.lastIndexOf(':') < 1) {
                throw new CswException("Invalid Sort Order format: " + getSortBy());
            }
            SortPropertyType sortProperty = new SortPropertyType();
            PropertyNameType propertyName = new PropertyNameType();

            String propName = StringUtils.substringBeforeLast(sortOption, ":");
            String direction = StringUtils.substringAfterLast(sortOption, ":");
            propertyName.setContent(Arrays.asList((Object) propName));
            SortOrderType sortOrder;

            if (direction.equals("A")) {
                sortOrder = SortOrderType.ASC;
            } else if (direction.equals("D")) {
                sortOrder = SortOrderType.DESC;
            } else {
                throw new CswException("Invalid Sort Order format: " + getSortBy());
            }

            sortProperty.setPropertyName(propertyName);
            sortProperty.setSortOrder(sortOrder);

            sortProps.add(sortProperty);
        }

        sort.setSortProperty(sortProps);

        query.setElementName(typeStringToQNames(getElementName(), namespaces));
        query.setSortBy(sort);
    }

    if (getConstraint() != null) {
        QueryConstraintType queryConstraint = new QueryConstraintType();

        if (getConstraintLanguage().equalsIgnoreCase(CswConstants.CONSTRAINT_LANGUAGE_CQL)) {
            queryConstraint.setCqlText(getConstraint());
        } else if (getConstraintLanguage().equalsIgnoreCase(CswConstants.CONSTRAINT_LANGUAGE_FILTER)) {
            try {
                XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
                xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
                xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
                XMLStreamReader xmlStreamReader = xmlInputFactory
                        .createXMLStreamReader(new StringReader(constraint));

                Unmarshaller unmarshaller = JAX_BCONTEXT.createUnmarshaller();
                @SuppressWarnings("unchecked")
                JAXBElement<FilterType> jaxbFilter = (JAXBElement<FilterType>) unmarshaller
                        .unmarshal(xmlStreamReader);
                queryConstraint.setFilter(jaxbFilter.getValue());
            } catch (JAXBException e) {
                throw new CswException("JAXBException parsing OGC Filter:" + getConstraint(), e);
            } catch (Exception e) {
                throw new CswException("Unable to parse OGC Filter:" + getConstraint(), e);
            }
        } else {
            throw new CswException("Invalid Constraint Language defined: " + getConstraintLanguage());
        }
        query.setConstraint(queryConstraint);
    }

    JAXBElement<QueryType> jaxbQuery = new JAXBElement<QueryType>(new QName(CswConstants.CSW_OUTPUT_SCHEMA),
            QueryType.class, query);

    getRecords.setAbstractQuery(jaxbQuery);

    return getRecords;
}