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

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

Introduction

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

Prototype

public static String substringBeforeLast(final String str, final String separator) 

Source Link

Document

Gets the substring before the last occurrence of a separator.

Usage

From source file:org.apache.olingo.commons.core.serialization.ContextURLParser.java

public static ContextURL parse(final URI contextURL) {
    if (contextURL == null) {
        return null;
    }//from   www  .  ja v  a  2 s.com

    final ContextURL.Builder builder = ContextURL.Builder.create();

    String contextURLasString = contextURL.toASCIIString();

    boolean isEntity = false;
    if (contextURLasString.endsWith("/$entity") || contextURLasString.endsWith("/@Element")) {
        isEntity = true;
        builder.suffix(Suffix.ENTITY);
        contextURLasString = contextURLasString.replace("/$entity", StringUtils.EMPTY).replace("/@Element",
                StringUtils.EMPTY);
    } else if (contextURLasString.endsWith("/$ref")) {
        builder.suffix(Suffix.REFERENCE);
        contextURLasString = contextURLasString.replace("/$ref", StringUtils.EMPTY);
    } else if (contextURLasString.endsWith("/$delta")) {
        builder.suffix(Suffix.DELTA);
        contextURLasString = contextURLasString.replace("/$delta", StringUtils.EMPTY);
    } else if (contextURLasString.endsWith("/$deletedEntity")) {
        builder.suffix(Suffix.DELTA_DELETED_ENTITY);
        contextURLasString = contextURLasString.replace("/$deletedEntity", StringUtils.EMPTY);
    } else if (contextURLasString.endsWith("/$link")) {
        builder.suffix(Suffix.DELTA_LINK);
        contextURLasString = contextURLasString.replace("/$link", StringUtils.EMPTY);
    } else if (contextURLasString.endsWith("/$deletedLink")) {
        builder.suffix(Suffix.DELTA_DELETED_LINK);
        contextURLasString = contextURLasString.replace("/$deletedLink", StringUtils.EMPTY);
    }

    builder.serviceRoot(URI.create(StringUtils.substringBefore(contextURLasString, Constants.METADATA)));

    final String rest = StringUtils.substringAfter(contextURLasString, Constants.METADATA + "#");

    String firstToken;
    String entitySetOrSingletonOrType = null;
    if (rest.startsWith("Collection(")) {
        firstToken = rest.substring(0, rest.indexOf(')') + 1);
        entitySetOrSingletonOrType = firstToken;
    } else {
        final int openParIdx = rest.indexOf('(');
        if (openParIdx == -1) {
            firstToken = StringUtils.substringBeforeLast(rest, "/");

            entitySetOrSingletonOrType = firstToken;
        } else {
            firstToken = isEntity ? rest : StringUtils.substringBeforeLast(rest, ")") + ")";

            final List<String> parts = new ArrayList<String>();
            for (String split : firstToken.split("\\)/")) {
                parts.add(split.replaceAll("\\(.*", ""));
            }
            entitySetOrSingletonOrType = StringUtils.join(parts, '/');
            final int commaIdx = firstToken.indexOf(',');
            if (commaIdx != -1) {
                builder.selectList(firstToken.substring(openParIdx + 1, firstToken.length() - 1));
            }
        }
    }
    builder.entitySetOrSingletonOrType(entitySetOrSingletonOrType);

    final int slashIdx = entitySetOrSingletonOrType.lastIndexOf('/');
    if (slashIdx != -1 && entitySetOrSingletonOrType.substring(slashIdx + 1).indexOf('.') != -1) {
        final String clone = entitySetOrSingletonOrType;
        builder.entitySetOrSingletonOrType(clone.substring(0, slashIdx));
        builder.derivedEntity(clone.substring(slashIdx + 1));
    }

    if (!firstToken.equals(rest)) {
        final String[] pathElems = StringUtils.substringAfter(rest, "/").split("/");
        if (pathElems.length > 0 && pathElems[0].length() > 0) {
            if (pathElems[0].indexOf('.') == -1) {
                builder.navOrPropertyPath(pathElems[0]);
            } else {
                builder.derivedEntity(pathElems[0]);
            }

            if (pathElems.length > 1) {
                builder.navOrPropertyPath(pathElems[1]);
            }
        }
    }

    return builder.build();
}

From source file:org.apache.olingo.fit.metadata.Metadata.java

public EntityType getEntityOrComplexType(final String fqn) {
    EntityType result = null;//from  www .  j  av a 2s.  c  o m

    final String ns = StringUtils.substringBeforeLast(fqn, ".");
    if (getSchema(ns) != null) {
        final String name = StringUtils.substringAfterLast(fqn, ".");
        result = getSchema(ns).getEntityType(name);
        if (result != null && result.getBaseType() != null) {
            final String baseNS = StringUtils.substringBeforeLast(result.getBaseType(), ".");
            if (getSchema(baseNS) != null) {
                final String baseName = StringUtils.substringAfterLast(result.getBaseType(), ".");
                final EntityType baseType = getSchema(baseNS).getEntityType(baseName);
                if (baseType != null) {
                    for (Map.Entry<String, Property> entry : baseType.getPropertyMap().entrySet()) {
                        result.addProperty(entry.getKey(), entry.getValue());
                    }
                    for (Map.Entry<String, NavigationProperty> entry : baseType.getNavigationPropertyMap()
                            .entrySet()) {
                        result.addNavigationProperty(entry.getKey(), entry.getValue());
                    }
                }
            }
        }
    }

    return result;
}

From source file:org.apache.sling.testing.clients.SlingClient.java

/**
 * Extracts the parent path from the given String
 *
 * @param path string containing the path
 * @return the parent path if exists or empty string otherwise
 *///from  ww  w.ja  va  2s . c  o  m
protected String getParentPath(final String path) {
    // TODO define more precisely what is the parent of a folder and of a file
    final String normalizedPath = StringUtils.removeEnd(path, "/"); // remove trailing slash in case of folders
    return StringUtils.substringBeforeLast(normalizedPath, "/");
}

From source file:org.apache.streams.util.schema.UriUtil.java

public static URI removeFile(URI id) {
    return URI.create(StringUtils.substringBeforeLast(id.toString(), "/"));
}

From source file:org.apache.struts2.convention.PackageBasedActionConfigBuilder.java

protected PackageConfig.Builder getPackageConfig(final Map<String, PackageConfig.Builder> packageConfigs,
        String actionNamespace, final String actionPackage, final Class<?> actionClass, Action action) {
    if (action != null && !action.value().equals(Action.DEFAULT_VALUE)) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Using non-default action namespace from the Action annotation of [#0]", action.value());
        }//  ww w  .  j a  v a  2s .  co  m
        String actionName = action.value();
        actionNamespace = StringUtils.contains(actionName, "/")
                ? StringUtils.substringBeforeLast(actionName, "/")
                : StringUtils.EMPTY;
    }

    // Next grab the parent annotation from the class
    ParentPackage parent = AnnotationUtils.findAnnotation(actionClass, ParentPackage.class);
    String parentName = null;
    if (parent != null) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Using non-default parent package from annotation of [#0]", parent.value());
        }

        parentName = parent.value();
    }

    // Finally use the default
    if (parentName == null) {
        parentName = defaultParentPackage;
    }

    if (parentName == null) {
        throw new ConfigurationException("Unable to determine the parent XWork package for the action class ["
                + actionClass.getName() + "]");
    }

    PackageConfig parentPkg = configuration.getPackageConfig(parentName);
    if (parentPkg == null) {
        throw new ConfigurationException("Unable to locate parent package [" + parentName + "]");
    }

    // Grab based on package-namespace and if it exists, we need to ensure the existing one has
    // the correct parent package. If not, we need to create a new package config
    String name = actionPackage + "#" + parentPkg.getName() + "#" + actionNamespace;
    PackageConfig.Builder pkgConfig = packageConfigs.get(name);
    if (pkgConfig == null) {
        pkgConfig = new PackageConfig.Builder(name).namespace(actionNamespace).addParent(parentPkg);
        packageConfigs.put(name, pkgConfig);

        //check for @DefaultInterceptorRef in the package
        DefaultInterceptorRef defaultInterceptorRef = AnnotationUtils.findAnnotation(actionClass,
                DefaultInterceptorRef.class);
        if (defaultInterceptorRef != null) {
            pkgConfig.defaultInterceptorRef(defaultInterceptorRef.value());

            if (LOG.isTraceEnabled())
                LOG.trace("Setting [#0] as the default interceptor ref for [#1]", defaultInterceptorRef.value(),
                        pkgConfig.getName());
        }
    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("Created package config named [#0] with a namespace [#1]", name, actionNamespace);
    }

    return pkgConfig;
}

From source file:org.apache.struts2.JSPLoader.java

public Servlet load(String location) throws Exception {
    location = StringUtils.substringBeforeLast(location, "?");

    if (LOG.isDebugEnabled()) {
        LOG.debug("Compiling JSP [#0]", location);
    }//from  w  w w. j a va 2  s. co  m

    //use Jasper to compile the JSP into java code
    JspC jspC = compileJSP(location);
    String source = jspC.getSourceCode();

    //System.out.print(source);

    String className = extractClassName(source);

    //use Java Compiler API to compile the java code into a class
    //the tlds that were discovered are added (their jars) to the classpath
    compileJava(className, source, jspC.getTldAbsolutePaths());

    //load the class that was just built
    Class clazz = Class.forName(className, false, classLoader);
    return createServlet(clazz);
}

From source file:org.apache.syncope.core.provisioning.java.MappingManagerImpl.java

@Override
public void setIntValues(final Item orgUnitItem, final Attribute attr, final RealmTO realmTO) {
    List<Object> values = null;
    if (attr != null) {
        values = attr.getValue();/*w  w  w.  java 2  s  . c  o m*/
        for (ItemTransformer transformer : MappingUtils.getItemTransformers(orgUnitItem)) {
            values = transformer.beforePull(orgUnitItem, realmTO, values);
        }
    }

    if (values != null && !values.isEmpty() && values.get(0) != null) {
        switch (orgUnitItem.getIntAttrName()) {
        case "name":
            realmTO.setName(values.get(0).toString());
            break;

        case "fullpath":
            String parentFullPath = StringUtils.substringBeforeLast(values.get(0).toString(), "/");
            Realm parent = realmDAO.findByFullPath(parentFullPath);
            if (parent == null) {
                LOG.warn("Could not find Realm with path {}, ignoring", parentFullPath);
            } else {
                realmTO.setParent(parent.getFullPath());
            }
            break;

        default:
        }
    }
}

From source file:org.apache.syncope.core.rest.cxf.ExtendedSwagger2Serializers.java

@Override
public void writeTo(final Swagger data, final Class<?> type, final Type genericType,
        final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> headers,
        final OutputStream out) throws IOException {

    if (dynamicBasePath) {
        MessageContext ctx = JAXRSUtils.createContextValue(JAXRSUtils.getCurrentMessage(), null,
                MessageContext.class);
        data.setBasePath(StringUtils.substringBeforeLast(ctx.getHttpServletRequest().getRequestURI(), "/"));
    }// w  w  w . ja  v a  2s. co  m

    if (replaceTags || javadocProvider != null) {
        Map<String, ClassResourceInfo> operations = new HashMap<>();
        Map<Pair<String, String>, OperationResourceInfo> methods = new HashMap<>();
        for (ClassResourceInfo cri : cris) {
            for (OperationResourceInfo ori : cri.getMethodDispatcher().getOperationResourceInfos()) {
                String normalizedPath = getNormalizedPath(cri.getURITemplate().getValue(),
                        ori.getURITemplate().getValue());

                operations.put(normalizedPath, cri);
                methods.put(ImmutablePair.of(ori.getHttpMethod(), normalizedPath), ori);
            }
        }

        if (replaceTags && data.getTags() != null) {
            data.getTags().clear();
        }
        for (final Map.Entry<String, Path> entry : data.getPaths().entrySet()) {
            Tag tag = null;
            if (replaceTags && operations.containsKey(entry.getKey())) {
                ClassResourceInfo cri = operations.get(entry.getKey());

                tag = new Tag();
                tag.setName(cri.getURITemplate().getValue());
                if (javadocProvider != null) {
                    tag.setDescription(javadocProvider.getClassDoc(cri));
                }

                data.addTag(tag);
            }

            for (Map.Entry<HttpMethod, Operation> subentry : entry.getValue().getOperationMap().entrySet()) {
                if (replaceTags && tag != null) {
                    subentry.getValue().setTags(Collections.singletonList(tag.getName()));
                }

                Pair<String, String> key = ImmutablePair.of(subentry.getKey().name(), entry.getKey());
                if (methods.containsKey(key) && javadocProvider != null) {
                    OperationResourceInfo ori = methods.get(key);

                    subentry.getValue().setSummary(javadocProvider.getMethodDoc(ori));

                    boolean domainHeaderParameterFound = false;
                    for (int i = 0; i < subentry.getValue().getParameters().size(); i++) {
                        subentry.getValue().getParameters().get(i)
                                .setDescription(javadocProvider.getMethodParameterDoc(ori, i));

                        if (subentry.getValue().getParameters().get(i) instanceof HeaderParameter
                                && RESTHeaders.DOMAIN
                                        .equals(subentry.getValue().getParameters().get(i).getName())) {

                            domainHeaderParameterFound = true;
                        }
                    }
                    if (!domainHeaderParameterFound) {
                        HeaderParameter domainHeaderParameter = new HeaderParameter();
                        domainHeaderParameter.setName(RESTHeaders.DOMAIN);
                        domainHeaderParameter.setRequired(true);
                        domainHeaderParameter.setType("string");
                        domainHeaderParameter.setEnum(domains);
                        domainHeaderParameter.setDefault(SyncopeConstants.MASTER_DOMAIN);

                        subentry.getValue().getParameters().add(domainHeaderParameter);
                    }

                    if (subentry.getValue().getResponses() != null
                            && !subentry.getValue().getResponses().isEmpty()) {

                        subentry.getValue().getResponses().entrySet().iterator().next().getValue()
                                .setDescription(javadocProvider.getMethodResponseDoc(ori));
                    }
                }
            }
        }
    }
    if (replaceTags && data.getTags() != null) {
        Collections.sort(data.getTags(), new Comparator<Tag>() {

            @Override
            public int compare(final Tag tag1, final Tag tag2) {
                return ComparatorUtils.<String>naturalComparator().compare(tag1.getName(), tag2.getName());
            }
        });
    }

    super.writeTo(data, type, genericType, annotations, mediaType, headers, out);
}

From source file:org.apache.unomi.persistence.elasticsearch.ElasticSearchPersistenceServiceImpl.java

private <T extends Item> PartialList<T> query(final QueryBuilder query, final String sortBy,
        final Class<T> clazz, final int offset, final int size, final String[] routing,
        final String scrollTimeValidity) {
    return new InClassLoaderExecute<PartialList<T>>() {

        @Override/*from  w ww.  j a  v  a2 s. c o m*/
        protected PartialList<T> execute(Object... args) throws Exception {
            List<T> results = new ArrayList<T>();
            String scrollIdentifier = null;
            long totalHits = 0;
            try {
                String itemType = getItemType(clazz);
                TimeValue keepAlive = TimeValue.timeValueHours(1);
                SearchRequestBuilder requestBuilder = null;
                if (scrollTimeValidity != null) {
                    keepAlive = TimeValue.parseTimeValue(scrollTimeValidity, TimeValue.timeValueHours(1),
                            "scrollTimeValidity");
                    requestBuilder = client.prepareSearch(getIndexNameForQuery(itemType)).setTypes(itemType)
                            .setFetchSource(true).setScroll(keepAlive).setFrom(offset).setQuery(query)
                            .setSize(size);
                } else {
                    requestBuilder = client.prepareSearch(getIndexNameForQuery(itemType)).setTypes(itemType)
                            .setFetchSource(true).setQuery(query).setFrom(offset);
                }

                if (size == Integer.MIN_VALUE) {
                    requestBuilder.setSize(defaultQueryLimit);
                } else if (size != -1) {
                    requestBuilder.setSize(size);
                } else {
                    // size == -1, use scroll query to retrieve all the results
                    requestBuilder = client.prepareSearch(getIndexNameForQuery(itemType)).setTypes(itemType)
                            .setFetchSource(true).setScroll(keepAlive).setFrom(offset).setQuery(query)
                            .setSize(100);
                }
                if (routing != null) {
                    requestBuilder.setRouting(routing);
                }
                if (sortBy != null) {
                    String[] sortByArray = sortBy.split(",");
                    for (String sortByElement : sortByArray) {
                        if (sortByElement.startsWith("geo:")) {
                            String[] elements = sortByElement.split(":");
                            GeoDistanceSortBuilder distanceSortBuilder = SortBuilders
                                    .geoDistanceSort(elements[1], Double.parseDouble(elements[2]),
                                            Double.parseDouble(elements[3]))
                                    .unit(DistanceUnit.KILOMETERS);
                            if (elements.length > 4 && elements[4].equals("desc")) {
                                requestBuilder = requestBuilder
                                        .addSort(distanceSortBuilder.order(SortOrder.DESC));
                            } else {
                                requestBuilder = requestBuilder
                                        .addSort(distanceSortBuilder.order(SortOrder.ASC));
                            }
                        } else {
                            String name = getPropertyNameWithData(
                                    StringUtils.substringBeforeLast(sortByElement, ":"), itemType);
                            if (name != null) {
                                if (sortByElement.endsWith(":desc")) {
                                    requestBuilder = requestBuilder.addSort(name, SortOrder.DESC);
                                } else {
                                    requestBuilder = requestBuilder.addSort(name, SortOrder.ASC);
                                }
                            } else {
                                // in the case of no data existing for the property, we will not add the sorting to the request.
                            }

                        }
                    }
                }
                SearchResponse response = requestBuilder.execute().actionGet();
                if (size == -1) {
                    // Scroll until no more hits are returned
                    while (true) {

                        for (SearchHit searchHit : response.getHits().getHits()) {
                            // add hit to results
                            String sourceAsString = searchHit.getSourceAsString();
                            final T value = CustomObjectMapper.getObjectMapper().readValue(sourceAsString,
                                    clazz);
                            value.setItemId(searchHit.getId());
                            results.add(value);
                        }

                        response = client.prepareSearchScroll(response.getScrollId()).setScroll(keepAlive)
                                .execute().actionGet();

                        // If we have no more hits, exit
                        if (response.getHits().getHits().length == 0) {
                            break;
                        }
                    }
                    client.prepareClearScroll().addScrollId(response.getScrollId()).execute().actionGet();
                } else {
                    SearchHits searchHits = response.getHits();
                    scrollIdentifier = response.getScrollId();
                    totalHits = searchHits.getTotalHits();
                    for (SearchHit searchHit : searchHits) {
                        String sourceAsString = searchHit.getSourceAsString();
                        final T value = CustomObjectMapper.getObjectMapper().readValue(sourceAsString, clazz);
                        value.setItemId(searchHit.getId());
                        results.add(value);
                    }
                }
            } catch (Exception t) {
                throw new Exception(
                        "Error loading itemType=" + clazz.getName() + " query=" + query + " sortBy=" + sortBy,
                        t);
            }

            PartialList<T> result = new PartialList<T>(results, offset, size, totalHits);
            if (scrollIdentifier != null && totalHits != 0) {
                result.setScrollIdentifier(scrollIdentifier);
                result.setScrollTimeValidity(scrollTimeValidity);
            }
            return result;
        }
    }.catchingExecuteInClassLoader(true);
}

From source file:org.blockartistry.mod.Restructured.util.ItemStackHelper.java

public static ItemStack getItemStack(final String name, final int quantity) {

    ItemStack result = null;//from  ww w.  j a  v  a  2s .c  om

    // Parse out the possible subtype from the end of the string
    String workingName = name;
    int subType = -1;

    if (StringUtils.countMatches(name, ":") == 2) {
        workingName = StringUtils.substringBeforeLast(name, ":");
        final String num = StringUtils.substringAfterLast(name, ":");

        if (num != null && !num.isEmpty()) {

            if ("*".compareTo(num) == 0)
                subType = OreDictionary.WILDCARD_VALUE;
            else {
                try {
                    subType = Integer.parseInt(num);
                } catch (Exception e) {
                    // It appears malformed - assume the incoming name
                    // is
                    // the real name and continue.
                    ;
                }
            }
        }
    }

    // Check the OreDictionary first for any alias matches. Otherwise
    // go to the game registry to find a match.
    final List<ItemStack> ores = OreDictionary.getOres(workingName);
    if (!ores.isEmpty()) {
        result = ores.get(0).copy();
        result.stackSize = quantity;
    } else {
        final Item i = GameData.getItemRegistry().getObject(new ResourceLocation(workingName));
        if (i != null) {
            result = new ItemStack(i, quantity);
        }
    }

    // If we did have a hit on a base item, set the subtype
    // as needed.
    if (result != null && subType != -1) {
        result.setItemDamage(subType);
    }

    return result;
}