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.server.StorageAdminImpl.java

public Storage get(String storageName, StorageType type) {
    // Remove #STAGING (if any) at end of storage name
    String cleanedStorageName = StringUtils.substringBeforeLast(storageName, STAGING_SUFFIX);
    // Look up for already registered storages
    Storage storage = getRegisteredStorage(cleanedStorageName, type);
    Map<String, XSystemObjects> xDataClustersMap = XSystemObjects.getXSystemObjects(XObjectType.DATA_CLUSTER);
    if (getRegisteredStorage(SYSTEM_STORAGE, StorageType.SYSTEM) != null
            && !XSystemObjects.DC_UPDATE_PREPORT.getName().equals(cleanedStorageName)
            && !XSystemObjects.DC_CROSSREFERENCING.getName().equals(cleanedStorageName)
            && (XSystemObjects.isXSystemObject(xDataClustersMap, cleanedStorageName)
                    || cleanedStorageName.startsWith("amaltoOBJECTS"))) { //$NON-NLS-1$
        return getRegisteredStorage(SYSTEM_STORAGE, StorageType.SYSTEM);
    }/*www .j  a  v a  2s  .  c om*/
    if (storage == null) {
        // May get request for "StorageName/Concept" (especially in case of XML DB -> SQL migration).
        storage = getRegisteredStorage(StringUtils.substringBefore(cleanedStorageName, "/"), type); //$NON-NLS-1$
    }
    if (storage == null) {
        LOGGER.info("Container '" + cleanedStorageName + "' does not exist.");
        // If data model xsd exists on server, create storage
        MetadataRepositoryAdmin metadataRepositoryAdmin = ServerContext.INSTANCE.get()
                .getMetadataRepositoryAdmin();
        if (metadataRepositoryAdmin.exist(storageName)) {
            String dataSourceName = getDatasource(cleanedStorageName);
            storage = create(cleanedStorageName, cleanedStorageName, type, dataSourceName);
        }
    }
    return storage;
}

From source file:adalid.util.velocity.SecondBaseBuilder.java

private void createTextFilePropertiesFile(String source, String target) {
    boolean java = StringUtils.endsWithIgnoreCase(source, ".java");
    boolean bundle = StringUtils.endsWithIgnoreCase(source, ".properties");
    File sourceFile = new File(source);
    String sourceFileName = sourceFile.getName();
    String sourceFileSimpleName = StringUtils.substringBeforeLast(sourceFileName, ".");
    String sourceFolderName = sourceFile.getParentFile().getName();
    String sourceFolderSimpleName = StringUtils.substringBeforeLast(sourceFolderName, ".");
    String sourceEntityName = getOptionalEntityName(sourceFileSimpleName, sourceFolderSimpleName);
    String properties = source.replace(projectFolderPath, velocityPlatformsTargetFolderPath) + ".properties";
    String folder = StringUtils.substringBeforeLast(properties, FS);
    String template = StringUtils.substringAfter(target, velocityFolderPath + FS).replace(FS, "/");
    String path = StringUtils.substringBeforeLast(StringUtils.substringAfter(source, projectFolderPath), FS)
            .replace(FS, "/").replace(project, PROJECT_ALIAS).replace("eclipse.settings", ".settings");
    path = replaceAliasWithRootFolderName(path);
    String pack = null;/*from   ww w  .  ja va  2s  .  c o m*/
    if (java || bundle) {
        String s1 = StringUtils.substringAfter(path, SRC);
        if (StringUtils.contains(s1, PROJECT_ALIAS)) {
            String s2 = StringUtils.substringBefore(s1, PROJECT_ALIAS);
            String s3 = SRC + s2;
            String s4 = StringUtils.substringBefore(path, s3) + s3;
            String s5 = StringUtils.substringAfter(s1, PROJECT_ALIAS).replace("/", ".");
            path = StringUtils.removeEnd(s4, "/");
            pack = ROOT_PACKAGE_NAME + s5;
        }
    }
    path = finalisePath(path);
    String file = StringUtils.substringAfterLast(source, FS).replace(project, PROJECT_ALIAS)
            .replace("eclipse.project", ".project");
    List<String> lines = new ArrayList<>();
    lines.add("template = " + template);
    //      lines.add("template-type = velocity");
    lines.add("path = " + path);
    if (StringUtils.isNotBlank(pack)) {
        lines.add("package = " + pack);
    }
    lines.add("file = " + file);
    if (sourceFileSimpleName.equals("eclipse") || sourceFolderSimpleName.equals("eclipse")
            || sourceFolderSimpleName.equals("nbproject")) {
        lines.add("disabled = true");
    } else if (sourceEntityName != null) {
        lines.add("disabled-when-missing = " + sourceEntityName);
    }
    if (preservable(sourceFile)) {
        lines.add("preserve = true");
    }
    lines.add("dollar.string = $");
    lines.add("pound.string = #");
    lines.add("backslash.string = \\\\");
    FilUtils.mkdirs(folder);
    if (write(properties, lines, WINDOWS_CHARSET)) {
        propertiesFilesCreated++;
    }
}

From source file:com.jaxio.celerio.model.Attribute.java

public String getColumnNameWithoutLanguage() {
    if (columnNameHasLanguageSuffix()) {
        return StringUtils.substringBeforeLast(getColumnName(), "_").toLowerCase();
    } else {/*  w  w  w.j av a 2s  .  c  o  m*/
        throw new IllegalStateException(
                "Can be invoked only if columnNameHasLanguageSuffix returns true, please write safer code");
    }
}

From source file:adalid.util.meta.sql.MetaPlatformSql.java

private void readFile(WriterContext templateWriterContext, TemplateBean templateBean) {
    File templatePropertiesFile = templateBean.getPropertiesFile();
    VelocityContext fileContext = templateWriterContext.getVelocityContextClone();
    Properties properties = mergeProperties(fileContext, templatePropertiesFile);
    putStrings(fileContext, properties);
    String userPath = pathString(USER_DIR);
    String temptype = StringUtils.defaultIfBlank(properties.getProperty(TP_TYPE), TP_TYPE_VELOCITY);
    String template = StringUtils.trimToNull(properties.getProperty(TP_TEMPLATE));
    String filePath = StringUtils.trimToNull(properties.getProperty(TP_PATH));
    String filePack = StringUtils.trimToNull(properties.getProperty(TP_PACKAGE));
    String fileName = StringUtils.trimToNull(properties.getProperty(TP_FILE));
    String preserve = StringUtils.trimToNull(properties.getProperty(TP_PRESERVE));
    String charset1 = StringUtils.trimToNull(properties.getProperty(TP_ENCODING));
    String charset2 = StringUtils.trimToNull(properties.getProperty(TP_CHARSET));
    String disabled = properties.getProperty(TP_DISABLED, Boolean.FALSE.toString());
    String disabledMissing = properties.getProperty(TP_DISABLED_MISSING);
    String executeCommand = StringUtils.trimToNull(properties.getProperty(TP_EXECUTE_COMMAND));
    String executeDirectory = StringUtils.trimToNull(properties.getProperty(TP_EXECUTE_DIRECTORY));
    String forEach = StringUtils.trimToNull(properties.getProperty(TP_FOR_EACH));
    String hint = ", check property \"{0}\" at file \"{1}\"";
    if (ArrayUtils.contains(TP_TYPE_ARRAY, temptype)) {
    } else {//from www  . ja v  a2 s.c o  m
        String pattern = "failed to obtain a valid template type" + hint;
        String message = MessageFormat.format(pattern, TP_TYPE, templatePropertiesFile);
        logger.error(message);
        errors++;
        return;
    }
    if (template == null) {
        String pattern = "failed to obtain a valid template name" + hint;
        String message = MessageFormat.format(pattern, TP_TEMPLATE, templatePropertiesFile);
        logger.error(message);
        errors++;
        return;
    }
    if (fileName == null) {
        String pattern = "failed to obtain a valid file name" + hint;
        String message = MessageFormat.format(pattern, TP_FILE, templatePropertiesFile);
        logger.error(message);
        errors++;
        return;
    }
    String templatePathString = pathString(template);
    String templatePath = StringUtils.substringBeforeLast(templatePathString, FILE_SEPARATOR);
    fileContext.put(VC_TEMPLATE, StringEscapeUtils.escapeJava(templatePathString));
    fileContext.put(VC_TEMPLATE_PATH, StringUtils.replace(templatePath, FILE_SEPARATOR, "/"));
    fileContext.put(VC_FILE, fileName);
    if (filePath == null) {
        filePath = userPath;
    } else {
        filePath = pathString(filePath);
        if (isRelativePath(filePath)) {
            if (filePath.startsWith(FILE_SEPARATOR)) {
                filePath = userPath + filePath;
            } else {
                filePath = userPath + FILE_SEPARATOR + filePath;
            }
        }
    }
    fileContext.put(VC_PATH, StringEscapeUtils.escapeJava(filePath));
    if (filePack != null) {
        filePath += FILE_SEPARATOR + pathString(StringUtils.replace(filePack, ".", "/"));
        fileContext.put(VC_PACKAGE, dottedString(filePack));
    }
    File path = new File(filePath);
    String fullname = path.getPath() + FILE_SEPARATOR + fileName;
    fileContext.put(VC_FILE_PATH, StringEscapeUtils.escapeJava(filePath));
    fileContext.put(VC_FILE_NAME, StringEscapeUtils.escapeJava(fileName));
    fileContext.put(VC_FILE_PATH_NAME, StringEscapeUtils.escapeJava(fullname));
    fileContext.put(VC_FILE_PATH_FILE, path);
    /**/
    templateBean.setPath(templatePathString);
    templateBean.setType(temptype);
    templateBean.setEncoding(charset1);
    templateBean.setForEach(forEach);
    templateBean.setTargetPath(filePath);
    templateBean.setTargetPackage(filePack);
    templateBean.setTargetFile(fileName);
    templateBean.setTargetFileEncoding(charset2);
    templateBean.setExecuteCommand(executeCommand);
    templateBean.setExecuteDirectory(executeDirectory);
    templateBean.setDisabled(BitUtils.valueOf(disabled));
    templateBean.setDisabledWhenMissing(BitUtils.valueOf(disabledMissing));
    templateBean.setPreserveExistingFile(BitUtils.valueOf(preserve));
    templateBean.setBytes(0);
    templateBean.setLines(0);
}

From source file:com.htmlhifive.tools.wizard.library.LibraryList.java

/**
 * ?????./*ww w  . j  ava  2  s.c  o  m*/
 * 
 * @param site 
 * @param folder 
 * @param existsFileList ???
 * @param noExistsFileList ?????
 * @return ????true?
 */
private boolean checkSite(Site site, IContainer folder, String installSubPath, List<String> existsFileList,
        List<String> noExistsFileList) {

    String siteUrl = site.getUrl();
    String path = H5IOUtils.getURLPath(siteUrl);
    if (path == null) {
        return false;
    }

    IContainer savedFolder = folder;
    if (StringUtils.isNotEmpty(installSubPath) && savedFolder != null) {
        savedFolder = savedFolder.getFolder(Path.fromOSString(installSubPath));
    }

    if (StringUtils.isNotEmpty(site.getExtractPath()) && savedFolder != null) {
        savedFolder = savedFolder.getFolder(Path.fromOSString(site.getExtractPath()));// .getRawLocation().toFile();
    }

    String[] fileList = null;

    String wildCardStr = site.getFilePattern();
    if (path.endsWith(".zip") || path.endsWith(".jar") || wildCardStr != null) {

        // ZIP??
        String wildCardPath = "";
        if (wildCardStr != null && wildCardStr.contains("/")) {
            // ?.
            wildCardStr = StringUtils.substringAfterLast(site.getFilePattern(), "/");

            // wildCardPath?*???????????.
            if (!wildCardStr.contains("*")) { // *?????
                wildCardPath = StringUtils.substringBeforeLast(site.getFilePattern(), "/");
                // folder = new File(folder, wildCardPath);
                if (folder != null) {
                    savedFolder = folder.getFolder(Path.fromOSString(wildCardPath));
                }
            }
        }

        if (savedFolder != null) {
            if (site.getReplaceFileName() != null) {
                fileList = savedFolder.getRawLocation().toFile()
                        .list(new WildcardFileFilter(site.getReplaceFileName()));
            } else {
                if (wildCardStr != null) {
                    fileList = savedFolder.getRawLocation().toFile().list(new WildcardFileFilter(wildCardStr));
                } else {
                    fileList = savedFolder.getRawLocation().toFile().list();
                }
            }
        }
        if (fileList != null && fileList.length > 0) {
            if (!wildCardPath.isEmpty()) {
                for (String fileName : fileList) {
                    existsFileList.add(wildCardPath + "/" + fileName);
                }
            } else {
                existsFileList.addAll(Arrays.asList(fileList));
            }
        } else if (savedFolder != null) {
            //noExistsFileList.add(savedFolder.getFullPath().toString() + "/" + wildCardStr);
            noExistsFileList.add(savedFolder.getProjectRelativePath().toString() + "/" + wildCardStr);
            if ((savedFolder.getFullPath().toString() + "/" + wildCardStr)
                    .startsWith(savedFolder.getFullPath().toString() + "/")) {
                noExistsFileList.add((savedFolder.getFullPath().toString() + "/" + wildCardStr)
                        .substring(folder.getFullPath().toString().length() + 1));
            } else {
                noExistsFileList.add(savedFolder.getFullPath().toString() + "/" + wildCardStr);
            }
            //folder
        } else {
            // ?????????????????.
            noExistsFileList.add(wildCardStr);
        }

    } else {
        // zip.
        IFile file = null;

        if (savedFolder != null) {
            if (site.getReplaceFileName() != null) {
                file = savedFolder.getFile(Path.fromOSString(site.getReplaceFileName()));
            } else {
                file = savedFolder.getFile(Path.fromOSString(StringUtils.substringAfterLast(path, "/")));
            }
            if (file.exists()) {
                fileList = new String[] { file.getName() };
                existsFileList.add(file.getName());
            } else {
                // ????
                if (file.getFullPath().toString().startsWith(folder.getFullPath().toString() + "/")) {
                    noExistsFileList.add(file.getFullPath().toString()
                            .substring(folder.getFullPath().toString().length() + 1));
                } else {
                    noExistsFileList.add(file.getFullPath().toString());
                }
            }
        } else {
            // ?????????????????.
            if (site.getReplaceFileName() != null) {
                noExistsFileList.add(site.getReplaceFileName());
            } else {
                noExistsFileList.add(StringUtils.substringAfterLast(path, "/"));
            }
        }
    }
    // ???????????
    if (fileList != null && fileList.length > 0) {
        return true;
    }
    return false;
}

From source file:info.magnolia.module.admininterface.AdminTreeMVCHandler.java

/**
 * Saves a value edited directly inside the tree. This can also be a lable
 * @return name of the view//from  ww  w.  j  ava 2  s .  c  om
 */
public String saveValue() {
    String saveName = this.getRequest().getParameter("saveName"); //$NON-NLS-1$
    Tree tree = getTree();

    // value to save is a node data's value (config admin)
    boolean isNodeDataValue = "true".equals(this.getRequest().getParameter("isNodeDataValue")); //$NON-NLS-1$ //$NON-NLS-2$

    // value to save is a node data's type (config admin)
    boolean isNodeDataType = "true".equals(this.getRequest().getParameter("isNodeDataType")); //$NON-NLS-1$ //$NON-NLS-2$

    String value = StringUtils.defaultString(this.getRequest().getParameter("saveValue")); //$NON-NLS-1$
    displayValue = StringUtils.EMPTY;
    // value to save is a content's meta information
    boolean isMeta = "true".equals(this.getRequest().getParameter("isMeta")); //$NON-NLS-1$ //$NON-NLS-2$
    // value to save is a label (name of page, content node or node data)
    boolean isLabel = "true".equals(this.getRequest().getParameter("isLabel")); //$NON-NLS-1$ //$NON-NLS-2$

    if (isNodeDataValue || isNodeDataType) {
        tree.setPath(StringUtils.substringBeforeLast(path, "/")); //$NON-NLS-1$
        saveName = StringUtils.substringAfterLast(path, "/"); //$NON-NLS-1$
    } else {
        // "/modules/templating/Templates/x"
        tree.setPath(path);
    }

    if (isLabel) {
        displayValue = rename(value);
    } else if (isNodeDataType) {
        int type = Integer.valueOf(value).intValue();
        synchronized (ExclusiveWrite.getInstance()) {
            displayValue = tree.saveNodeDataType(saveName, type);
        }
    } else {
        synchronized (ExclusiveWrite.getInstance()) {
            displayValue = tree.saveNodeData(saveName, value, isMeta);
        }
    }

    // if there was a displayValue passed show it instead of the written value
    displayValue = StringUtils.defaultString(this.getRequest().getParameter("displayValue"), value); //$NON-NLS-1$

    // @todo should be handled in a better way but, at the moment, this is better than nothing
    if (path.startsWith("/subscribers/")) { //$NON-NLS-1$
        Subscriber.reload();
    } else if (path.startsWith("/server/MIMEMapping")) { //$NON-NLS-1$
        MIMEMapping.reload();
    }

    return VIEW_VALUE;
}

From source file:info.magnolia.link.LinkUtil.java

/**
 * Creates link to the content identified by the repository and path. Link will use specified extension and will also contain the anchor and parameters if specified.
 * @param workspaceName Source repository for the content.
 * @param path Path to the content of interest.
 * @param extension Optional extension to be used in the link
 * @param anchor Optional link anchor./*from  w  w w  .j a v a2s .co  m*/
 * @param parameters Optional link parameters.
 * @return Link pointing to the content denoted by repository and path including extension, anchor and parameters if such were provided.
 * @throws LinkException
 */
public static Link createLinkInstance(String workspaceName, String path, String extension, String anchor,
        String parameters) throws LinkException {
    Node node = null;
    String fileName = null;
    String nodeDataName = null;
    Property property = null;
    try {
        Session session = MgnlContext.getJCRSession(workspaceName);

        boolean exists = false;
        try {
            PathParser.checkFormat(path);
        } catch (MalformedPathException e) {
            // we first check for path incl. the file name. While file name might not be necessarily part of the path, it might contain also non ascii chars. If that is the case, parsing exception will occur so we know that path with filename can't exist.
        }
        exists = session.itemExists(path) && !session.propertyExists(path);
        if (exists) {
            node = session.getNode(path);
        }
        if (node == null) {
            if (session.nodeExists(path)) {
                node = session.getNode(path);
            }
            if (node != null && node.isNodeType(NodeTypes.Resource.NAME) && node.hasProperty("fileName")) {
                fileName = node.getProperty("fileName").getString();
            }
            if (session.propertyExists(path)) {
                nodeDataName = StringUtils.substringAfterLast(path, "/");
                path = StringUtils.substringBeforeLast(path, "/");
                property = node.getProperty(nodeDataName);
            }
        }
        if (node == null) {
            throw new LinkException("can't find node " + path + " in repository " + workspaceName);
        }
    } catch (RepositoryException e) {
        throw new LinkException("can't get node with path " + path + " from repository " + workspaceName);
    }

    Link link = new Link(node);
    link.setAnchor(anchor);
    link.setExtension(extension);
    link.setParameters(parameters);
    link.setFileName(fileName);
    link.setPropertyName(nodeDataName);
    link.setProperty(property);
    link.setPath(path);
    return link;
}

From source file:com.iorga.webappwatcher.EventLogManager.java

private ArchiveOutputStream writeEventLogToHttpServletResponse(final HttpServletResponse httpResponse,
        String fileName, ArchiveOutputStream outputStream) throws IOException {
    if (outputStream == null) {
        // First, let's open the outputStream
        httpResponse.setStatus(HttpServletResponse.SC_OK);
        httpResponse.setContentType("application/zip");
        httpResponse.setHeader("Content-Disposition",
                "attachment; filename=\"" + generateLogFileNameWithoutExtension() + ".zip\"");

        outputStream = new ZipArchiveOutputStream(httpResponse.getOutputStream());
    }/* w w w .  j  a  v a  2s  .com*/

    final File file = new File(getLogPathDirectory(), fileName);
    InputStream inputStream = new FileInputStream(file);
    if (fileName.endsWith(".gz")) {
        // it's a GZIP, let's decompress it
        inputStream = new GZIPInputStream(inputStream);
        fileName = StringUtils.substringBeforeLast(fileName, ".gz");
    } else if (logFile != null && logFile.getName().equals(fileName)) {
        // this is the current log file, we must lock the logFile
        synchronized (objectOutputStreamLogLock) {
            // before trying to download the log, we must first flush it
            flushLog();
            writeEventLogToHttpServletResponse(outputStream, inputStream, file, fileName);
        }
        return outputStream;
    }

    writeEventLogToHttpServletResponse(outputStream, inputStream, file, fileName);

    return outputStream;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.brat.controller.ChainAdapter.java

/**
 * Create a new link annotation. Already adds the chain to the CAS.
 *///from   w  ww .jav  a  2 s . c om
private AnnotationFS newLink(JCas aJCas, int aBegin, int aEnd, AnnotationFeature aFeature, String aLabelValue) {
    String baseName = StringUtils.substringBeforeLast(getAnnotationTypeName(), CHAIN) + LINK;
    Type linkType = CasUtil.getType(aJCas.getCas(), baseName);
    AnnotationFS newLink = aJCas.getCas().createAnnotation(linkType, aBegin, aEnd);
    BratAjaxCasUtil.setFeature(newLink, aFeature, aLabelValue);
    aJCas.getCas().addFsToIndexes(newLink);
    return newLink;
}

From source file:info.magnolia.module.admininterface.SaveHandlerImpl.java

/**
 * @param value/*from w  w  w  .j a  v  a 2  s.  co m*/
 * @param tagName
 */
protected static String replacePByBr(final String value, String tagName) {

    if (StringUtils.isBlank(value)) {
        return value;
    }

    String fixedValue = value;

    String pre = "<" + tagName + ">"; //$NON-NLS-1$ //$NON-NLS-2$
    String post = "</" + tagName + ">"; //$NON-NLS-1$ //$NON-NLS-2$

    // get rid of last </p>
    if (fixedValue.endsWith(post)) {
        fixedValue = StringUtils.substringBeforeLast(fixedValue, post);
    }

    fixedValue = StringUtils.replace(fixedValue, pre + "&nbsp;" + post, "\n "); //$NON-NLS-1$ //$NON-NLS-2$
    fixedValue = StringUtils.replace(fixedValue, pre, StringUtils.EMPTY);
    fixedValue = StringUtils.replace(fixedValue, post, "\n\n "); //$NON-NLS-1$

    if (!tagName.equals(tagName.toUpperCase())) {
        fixedValue = replacePByBr(fixedValue, tagName.toUpperCase());
    }
    return fixedValue;
}