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

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

Introduction

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

Prototype

public static String substringBeforeLast(String str, String separator) 

Source Link

Document

Gets the substring before the last occurrence of a separator.

Usage

From source file:com.amalto.core.storage.StorageWrapper.java

protected String getXmlString(String clusterName, ComplexTypeMetadata type, Iterator<DataRecord> iterator,
        String uniqueID, String encoding, boolean isUserFormat) throws IOException {
    String xmlString = null;/*w ww . j a va2 s.  com*/
    if (iterator.hasNext()) {
        DataRecord result = iterator.next();
        if (iterator.hasNext()) {
            iterateUnexceptedRecords(LOGGER, uniqueID, iterator);
        }
        ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
        // Enforce root element name in case query returned instance of a subtype.
        DataRecordWriter dataRecordXmlWriter = isUserFormat ? new DataRecordXmlWriter(type)
                : new SystemDataRecordXmlWriter(
                        (ClassRepository) getStorage(clusterName).getMetadataRepository(), type);
        if (isUserFormat) {
            dataRecordXmlWriter.setSecurityDelegator(SecuredStorage.getDelegator());
            String key = uniqueID.startsWith(PROVISIONING_PREFIX_INFO)
                    ? StringUtils.substringAfter(uniqueID, PROVISIONING_PREFIX_INFO)
                    : uniqueID.split("\\.")[2]; //$NON-NLS-1$
            long timestamp = result.getRecordMetadata().getLastModificationTime();
            String taskId = result.getRecordMetadata().getTaskId();
            String modelName = StringUtils.substringBeforeLast(clusterName, StorageAdmin.STAGING_SUFFIX);
            byte[] start = ("<ii><c>" + clusterName + "</c><dmn>" + modelName + "</dmn><dmr/><sp/><t>" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                    + timestamp + "</t><taskId>" + taskId + "</taskId><i>" + StringEscapeUtils.escapeXml(key) //$NON-NLS-1$//$NON-NLS-2$
                    + "</i><p>").getBytes(); //$NON-NLS-1$
            output.write(start);
        }
        dataRecordXmlWriter.write(result, output);
        if (isUserFormat) {
            byte[] end = ("</p></ii>").getBytes(); //$NON-NLS-1$
            output.write(end);
        }
        output.flush();
        xmlString = new String(output.toByteArray(), encoding);
    }
    return xmlString;
}

From source file:edu.cornell.kfs.fp.batch.service.impl.AdvanceDepositServiceImpl.java

/**
 * Clears out associated .done files for the processed data files.
 * @param dataFileName//from   ww w . j av  a2 s .  c  om
 */
protected void removeDoneFile(String dataFileName) {
    File doneFile = new File(StringUtils.substringBeforeLast(dataFileName, ".") + ".done");
    if (doneFile.exists()) {
        doneFile.delete();
    }
}

From source file:com.apdplat.platform.struts.APDPlatPackageBasedActionConfigBuilder.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());
        }/*from  w w  w.ja  va2s . c o  m*/
        String actionName = action.value();
        actionNamespace = StringUtils.contains(actionName, "/")
                ? StringUtils.substringBeforeLast(actionName, "/")
                : StringUtils.EMPTY;
    }

    // Next grab the parent annotation from the class
    ParentPackage parent = AnnotationTools.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 = AnnotationTools.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:adalid.commons.velocity.Writer.java

private void deletePreviouslyGeneratedFiles(String name, String[] stringArray, boolean recursive) {
    String root = getRoot().getPath();
    String raiz = root.replace('\\', '/');
    String path, pathname, wildcard;
    String recursively = recursive ? "and all its subdirectories" : "";
    String slashedPath, regex, pattern, message;
    String hint = "; check property: {0}={1}";
    boolean delete;
    File directory;//from w ww . j  a v a2s. c o  m
    IOFileFilter fileFilter;
    IOFileFilter dirFilter = recursive ? ignoreVersionControlFilter : null;
    Collection<File> matchingFiles;
    Arrays.sort(stringArray);
    for (String string : stringArray) {
        pathname = StringUtils.substringBeforeLast(string, SLASH);
        if (StringUtils.isBlank(string) || !StringUtils.contains(string, SLASH)
                || StringUtils.isBlank(pathname)) {
            pattern = "directory is missing or invalid" + hint;
            message = MessageFormat.format(pattern, name, string);
            log(_alertLevel, message);
            warnings++;
            continue;
        }
        wildcard = StringUtils.substringAfterLast(string, SLASH);
        if (StringUtils.isBlank(wildcard)) {
            pattern = "wildcard is missing or invalid" + hint;
            message = MessageFormat.format(pattern, name, string);
            log(_alertLevel, message);
            warnings++;
            continue;
        }
        directory = new File(pathname);
        if (FilUtils.isNotWritableDirectory(directory)) {
            pattern = "{2} is not a writable directory" + hint;
            message = MessageFormat.format(pattern, name, string,
                    StringUtils.removeStartIgnoreCase(pathname, raiz));
            log(_alertLevel, message);
            warnings++;
            continue;
        }
        log(_detailLevel, "deleting files " + wildcard + " from "
                + StringUtils.removeStartIgnoreCase(pathname, raiz) + " " + recursively);
        fileFilter = new WildcardFileFilter(wildcard);
        matchingFiles = FileUtils.listFiles(directory, fileFilter, dirFilter);
        for (File file : matchingFiles) {
            path = file.getPath();
            slashedPath = path.replace('\\', '/');
            delete = true;
            for (Pattern fxp : filePreservationPatterns) {
                regex = fxp.pattern();
                if (slashedPath.matches(regex)) {
                    delete = false;
                    pattern = "file {0} will not be deleted; it matches preservation expression \"{1}\"";
                    message = MessageFormat.format(pattern,
                            StringUtils.removeStartIgnoreCase(slashedPath, raiz), regex);
                    log(_alertLevel, message);
                    warnings++;
                    break;
                }
            }
            if (delete) {
                logger.trace("deleting " + StringUtils.removeStartIgnoreCase(path, root));
                FileUtils.deleteQuietly(file);
            }
        }
    }
}

From source file:de.iteratec.iteraplan.businesslogic.service.legacyExcel.ExcelImportServiceImpl.java

/**
 * Returns the Parent name by passing a hierarchical name, or null if not found.
 * //from w  w w .j  av  a  2s  .c  o m
 * @param nameHierarchy
 * @param nameNonHierarchy
 *          If passed (not null), checks that this is the name contained in the other parameter, returning null on mismatch.
 */
String getParentNameFromHierarchicalName(String nameHierarchy, String nameNonHierarchy,
        String cellCoordinates) {
    if (nameHierarchy == null) {
        return null;
    }

    // If there is at least one :, there is a parent
    final String hierarchySeparator = Constants.HIERARCHYSEP.trim();

    if (nameHierarchy.contains(hierarchySeparator)) {
        // Only verify the name if this parameter was passed
        if (nameNonHierarchy != null) {
            String nameNonHierarchyFound = StringUtils.substringAfterLast(nameHierarchy, hierarchySeparator);
            nameNonHierarchyFound = StringUtils.strip(nameNonHierarchyFound);

            // Check if the Name part of the Hierarchy is the one we expected
            if (!nameNonHierarchyFound.equalsIgnoreCase(nameNonHierarchy)) {
                getProcessingLog().warn(
                        "Hierarchical Name \"{0}\" in cell [{1}] does not contain the name of the BuildingBlock it belongs to ({2}). Not setting parent!",
                        nameHierarchy, cellCoordinates, nameNonHierarchy);
                return null;
            }
        }
        String allBeforeName = StringUtils.substringBeforeLast(nameHierarchy, hierarchySeparator);
        allBeforeName = StringUtils.strip(allBeforeName);

        // Strip grandparents+ if necessary
        if (allBeforeName.contains(hierarchySeparator)) {
            return StringUtils.substringAfterLast(allBeforeName, Constants.HIERARCHYSEP).trim();
        }
        return allBeforeName;
    }
    return null;
}

From source file:net.sourceforge.sqlexplorer.EDriverName.java

public static Boolean isAboveJDK15() {
    Float curVersion = Float
            .parseFloat(StringUtils.substringBeforeLast(System.getProperty("java.version"), "."));
    return NumberUtils.compare(curVersion, 1.5) > 0;
}

From source file:net.ymate.framework.core.util.WebUtils.java

/**
 * @param url           URL?/*ww w  . j  a va2  s  .c  o  m*/
 * @param needStartWith ?'/'
 * @param needEndwith   ?'/'?
 * @return ?URL?
 */
public static String fixURL(String url, boolean needStartWith, boolean needEndwith) {
    url = StringUtils.trimToNull(url);
    if (url != null) {
        if (needStartWith && !StringUtils.startsWith(url, "/")) {
            url = '/' + url;
        } else if (!needStartWith && StringUtils.startsWith(url, "/")) {
            url = StringUtils.substringAfter(url, "/");
        }
        if (needEndwith && !StringUtils.endsWith(url, "/")) {
            url = url + '/';
        } else if (!needEndwith && StringUtils.endsWith(url, "/")) {
            url = StringUtils.substringBeforeLast(url, "/");
        }
        return url;
    }
    return "";
}

From source file:net.ymate.module.webproxy.impl.DefaultModuleCfg.java

public DefaultModuleCfg(YMP owner) {
    Map<String, String> _moduleCfgs = owner.getConfig().getModuleConfigs(IWebProxy.MODULE_NAME);
    ///*from   ww w.java 2  s.  c  om*/
    __serviceBaseUrl = _moduleCfgs.get("service_base_url");
    if (StringUtils.isBlank(__serviceBaseUrl)) {
        throw new NullArgumentException("service_base_url");
    }
    if (!StringUtils.startsWithIgnoreCase(__serviceBaseUrl, "http://")
            && !StringUtils.startsWithIgnoreCase(__serviceBaseUrl, "https://")) {
        throw new IllegalArgumentException("Argument service_base_url must be start with http or https");
    } else if (StringUtils.endsWith(__serviceBaseUrl, "/")) {
        __serviceBaseUrl = StringUtils.substringBeforeLast(__serviceBaseUrl, "/");
    }
    //
    __serviceRequestPrefix = StringUtils.trimToEmpty(_moduleCfgs.get("service_request_prefix"));
    if (StringUtils.isNotBlank(__serviceRequestPrefix)
            && !StringUtils.startsWith(__serviceRequestPrefix, "/")) {
        __serviceRequestPrefix = "/" + __serviceRequestPrefix;
    }
    //
    __useProxy = BlurObject.bind(_moduleCfgs.get("use_proxy")).toBooleanValue();
    if (__useProxy) {
        Proxy.Type _proxyType = Proxy.Type
                .valueOf(StringUtils.defaultIfBlank(_moduleCfgs.get("proxy_type"), "HTTP").toUpperCase());
        int _proxyPrort = BlurObject.bind(StringUtils.defaultIfBlank(_moduleCfgs.get("proxy_port"), "80"))
                .toIntValue();
        String _proxyHost = _moduleCfgs.get("proxy_host");
        if (StringUtils.isBlank(_proxyHost)) {
            throw new NullArgumentException("proxy_host");
        }
        __proxy = new Proxy(_proxyType, new InetSocketAddress(_proxyHost, _proxyPrort));
    }
    //
    __useCaches = BlurObject.bind(_moduleCfgs.get("use_caches")).toBooleanValue();
    __instanceFollowRedirects = BlurObject.bind(_moduleCfgs.get("instance_follow_redirects")).toBooleanValue();
    //
    __connectTimeout = BlurObject.bind(_moduleCfgs.get("connect_timeout")).toIntValue();
    __readTimeout = BlurObject.bind(_moduleCfgs.get("read_timeout")).toIntValue();
    //
    __transferBlackList = Arrays
            .asList(StringUtils.split(StringUtils.trimToEmpty(_moduleCfgs.get("transfer_blacklist")), "|"));
    //
    __transferHeaderEnabled = BlurObject.bind(_moduleCfgs.get("transfer_header_enabled")).toBooleanValue();
    //
    if (__transferHeaderEnabled) {
        String[] _filters = StringUtils
                .split(StringUtils.lowerCase(_moduleCfgs.get("transfer_header_whitelist")), "|");
        if (_filters != null && _filters.length > 0) {
            __transferHeaderWhiteList = Arrays.asList(_filters);
        } else {
            __transferHeaderWhiteList = Collections.emptyList();
        }
        //
        _filters = StringUtils.split(StringUtils.lowerCase(_moduleCfgs.get("transfer_header_blacklist")), "|");
        if (_filters != null && _filters.length > 0) {
            __transferHeaderBlackList = Arrays.asList(_filters);
        } else {
            __transferHeaderBlackList = Collections.emptyList();
        }
        //
        _filters = StringUtils.split(StringUtils.lowerCase(_moduleCfgs.get("response_header_whitelist")), "|");
        if (_filters != null && _filters.length > 0) {
            __responseHeaderWhiteList = Arrays.asList(_filters);
        } else {
            __responseHeaderWhiteList = Collections.emptyList();
        }
    } else {
        __transferHeaderWhiteList = Collections.emptyList();
        __transferHeaderBlackList = Collections.emptyList();
        //
        __responseHeaderWhiteList = Collections.emptyList();
    }
}

From source file:net.ymate.platform.log.AbstractLogger.java

/**
 * ??//  ww w .  j ava  2  s .  co  m
 *
 * @return ??className.methodName:lineNumber?NO_STACK_TRACE:-1
 */
protected String __doMakeCallerInfo() {
    StackTraceElement[] _stacks = new Throwable().getStackTrace();
    // ???
    if (__depth >= 0 && _stacks.length > 1 + __depth) {
        StackTraceElement _element = _stacks[1 + __depth];
        return StringUtils.substringBeforeLast(_element.getClassName(), ".").concat(".")
                .concat(_element.getMethodName()).concat(":")
                .concat(_element.getLineNumber() + StringUtils.EMPTY);
    }
    return "NO_STACK_TRACE:-1";
}

From source file:net.ymate.platform.log.jcl.JCLogger.java

/**
 * ??// w w  w.j  a  v  a 2s  .c  o m
 *
 * @return ??className.methodName:lineNumber?NO_STACK_TRACE:-1
 */
protected String __doMakeCallerInfo() {
    StackTraceElement[] _stacks = new Throwable().getStackTrace();
    // ???
    if (_stacks.length > 3) {
        StackTraceElement _element = _stacks[3];
        return StringUtils.substringBeforeLast(_element.getClassName(), ".").concat(".")
                .concat(_element.getMethodName()).concat(":")
                .concat(_element.getLineNumber() + StringUtils.EMPTY);
    }
    return "NO_STACK_TRACE:-1";
}