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:info.magnolia.cms.filters.InterceptFilter.java

/**
 * Request and Response here is same as received by the original page so it includes all post/get data. Sub action
 * could be called from here once this action finishes, it will continue loading the requested page.
 * @throws RepositoryException//from   www.  java 2 s  . com
 * @throws LoginException
 */
public void intercept(HttpServletRequest request, HttpServletResponse response)
        throws LoginException, RepositoryException {
    final AggregationState aggregationState = MgnlContext.getAggregationState();
    String action = request.getParameter(INTERCEPT);
    String repository = request.getParameter(PARAM_REPOSITORY);
    String nodePath = request.getParameter(PARAM_PATH);
    String handle = aggregationState.getHandle();
    String channel = aggregationState.getChannel().getName();

    if (repository == null) {
        repository = aggregationState.getRepository();
    }

    if (repository == null) {
        repository = RepositoryConstants.WEBSITE;
    }

    final Session session = MgnlContext.getJCRSession(repository);

    if (ACTION_PREVIEW.equals(action)) {
        // preview mode (button in main bar)
        String preview = request.getParameter(MGNL_PREVIEW_ATTRIBUTE);
        log.debug("preview request parameter value is {} ", preview);
        if (preview != null) {
            if (Boolean.parseBoolean(preview)) {
                MgnlContext.setAttribute(MGNL_PREVIEW_ATTRIBUTE, Boolean.TRUE, Context.SESSION_SCOPE);
                MgnlContext.setAttribute(MultiChannelFilter.ENFORCE_CHANNEL_PARAMETER, channel,
                        Context.SESSION_SCOPE);
            } else {
                MgnlContext.removeAttribute(MGNL_PREVIEW_ATTRIBUTE, Context.SESSION_SCOPE);
                MgnlContext.removeAttribute(MultiChannelFilter.ENFORCE_CHANNEL_PARAMETER,
                        Context.SESSION_SCOPE);
            }
        } else {
            MgnlContext.removeAttribute(MGNL_PREVIEW_ATTRIBUTE, Context.SESSION_SCOPE);
            MgnlContext.removeAttribute(MultiChannelFilter.ENFORCE_CHANNEL_PARAMETER, Context.SESSION_SCOPE);
        }
    } else if (ACTION_NODE_DELETE.equals(action)) {
        // delete paragraph
        try {
            Node page = session.getNode(handle);
            session.removeItem(nodePath);
            MetaDataUtil.updateMetaData(page);
            session.save();
        } catch (RepositoryException e) {
            log.error("Exception caught: {}", e.getMessage(), e);
        }
    } else if (ACTION_NODE_SORT.equals(action)) {
        // sort paragraphs
        try {
            String pathSelected = request.getParameter(PARAM_PATH_SELECTED);
            String pathTarget = request.getParameter(PARAM_PATH_TARGET);
            String pathParent = StringUtils.substringBeforeLast(pathSelected, "/");
            String srcName = StringUtils.substringAfterLast(pathSelected, "/");
            String destName = StringUtils.substringAfterLast(pathTarget, "/");
            String order = StringUtils.defaultIfEmpty(request.getParameter("order"), "before");
            if (StringUtils.equalsIgnoreCase(destName, "mgnlNew")) {
                destName = null;
            }
            Node parent = session.getNode(pathParent + srcName);

            if ("before".equals(order)) {
                NodeUtil.orderBefore(parent, destName);
            } else {
                NodeUtil.orderAfter(parent, destName);
            }

            Node page = session.getNode(handle);
            MetaDataUtil.updateMetaData(page);
            session.save();
        } catch (RepositoryException e) {
            log.error("Exception caught: {}", e.getMessage(), e);
        }
    } else {
        log.warn("Unknown action {}", action);
    }
}

From source file:com.echosource.ada.core.AdaFile.java

/**
 * Match file pattern./* w ww  . j  a  va  2s.  c o  m*/
 * 
 * @param antPattern
 *          the ant pattern
 * @return true, if match file pattern
 * @see org.sonar.api.resources.Resource#matchFilePattern(java.lang.String)
 */
@Override
public boolean matchFilePattern(String antPattern) {
    String patternWithoutFileSuffix = StringUtils.substringBeforeLast(antPattern, PACKAGE_SEPARATOR);
    WildcardPattern matcher = WildcardPattern.create(patternWithoutFileSuffix, PACKAGE_SEPARATOR);
    return matcher.match(getKey());
}

From source file:info.magnolia.importexport.DataTransporter.java

/**
 * Deprecated.//from  ww  w  . j  a va 2 s . com
 * @param properties
 * @param repositoryName
 * @deprecated since 4.0 - use the PropertiesImportExport class instead.
 */
public static void importProperties(Properties properties, String repositoryName) {
    for (Iterator iter = properties.keySet().iterator(); iter.hasNext();) {
        String key = (String) iter.next();
        String value = (String) properties.get(key);

        String name = StringUtils.substringAfterLast(key, ".");
        String path = StringUtils.substringBeforeLast(key, ".").replace('.', '/');
        Content node = ContentUtil.getContent(repositoryName, path);
        if (node != null) {
            try {
                NodeDataUtil.getOrCreate(node, name).setValue(value);
                node.save();
            } catch (RepositoryException e) {
                log.error("can't set property " + key, e);
            }
        }
    }

}

From source file:com.b2international.snowowl.snomed.importer.rf2.util.SnomedRefSetNameCollector.java

private void readDescriptionFiles(final Set<String> unlabeledRefSetIds, final IProgressMonitor monitor) {

    RecordParserCallback<String> descriptionParserCallback = new RecordParserCallback<String>() {

        @Override/*from   w w  w . ja  v  a 2s . c o m*/
        public void handleRecord(int recordCount, List<String> record) {

            if (!unlabeledRefSetIds.isEmpty()) {

                String refSetId = record.get(DESCRIPTION_CONCEPT_ID_COLUMN);
                String descriptionType = record.get(DESCRIPTION_TYPE_COLUMN);
                String status = record.get(STATUS_COLUMN);

                if (unlabeledRefSetIds.contains(refSetId)
                        && descriptionType.equals(SnomedConstants.Concepts.FULLY_SPECIFIED_NAME)
                        && status.equals(ACTIVE_STATUS)) {

                    // Remove the part in parentheses for the fully specified term
                    String term = record.get(DESCRIPTION_TERM_COLUMN);
                    String trimmedTerm = StringUtils.substringBeforeLast(term, "(");
                    refsetIdToLabelMap.put(refSetId, trimmedTerm);
                    unlabeledRefSetIds.remove(refSetId);

                }

            }

        }
    };

    if (!configuration.getDescriptionFiles().isEmpty()) {

        SubMonitor subMonitor = SubMonitor.convert(monitor, configuration.getDescriptionFiles().size());
        subMonitor.setTaskName("Parsing description files for reference set labels...");

        for (File descFile : configuration.getDescriptionFiles()) {

            if (!unlabeledRefSetIds.isEmpty()) {

                try {

                    final URL url = configuration.toURL(descFile);

                    try (InputStreamReader descriptionReader = new InputStreamReader(url.openStream())) {
                        final CsvParser parser = new CsvParser(descriptionReader, getFileName(url),
                                CSV_SETTINGS, descriptionParserCallback, DESCRIPTION_FIELD_COUNT);
                        parser.parse();
                    }

                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }

            subMonitor.worked(1);
        }

    }

    monitor.done();
}

From source file:com.dp2345.service.impl.FileServiceImpl.java

public List<FileInfo> browser(String path, FileType fileType, OrderType orderType) {
    if (path != null) {
        if (!path.startsWith("/")) {
            path = "/" + path;
        }//from   w  w  w  .j a  v a2 s  . c om
        if (!path.endsWith("/")) {
            path += "/";
        }
    } else {
        path = "/";
    }
    Setting setting = SettingUtils.get();
    String uploadPath;
    if (fileType == FileType.flash) {
        uploadPath = setting.getFlashUploadPath();
    } else if (fileType == FileType.media) {
        uploadPath = setting.getMediaUploadPath();
    } else if (fileType == FileType.file) {
        uploadPath = setting.getFileUploadPath();
    } else {
        uploadPath = setting.getImageUploadPath();
    }
    String browsePath = StringUtils.substringBefore(uploadPath, "${");
    browsePath = StringUtils.substringBeforeLast(browsePath, "/") + path;

    List<FileInfo> fileInfos = new ArrayList<FileInfo>();
    if (browsePath.indexOf("..") >= 0) {
        return fileInfos;
    }
    for (StoragePlugin storagePlugin : pluginService.getStoragePlugins(true)) {
        fileInfos = storagePlugin.browser(browsePath);
        break;
    }
    if (orderType == OrderType.size) {
        Collections.sort(fileInfos, new SizeComparator());
    } else if (orderType == OrderType.type) {
        Collections.sort(fileInfos, new TypeComparator());
    } else {
        Collections.sort(fileInfos, new NameComparator());
    }
    return fileInfos;
}

From source file:br.usp.ime.lapessc.xflow2.core.VCSMiner.java

private void fixFolder(Resource resource, Commit commit) {

    try {/*from  ww  w.  ja  va2  s. co  m*/
        String path = resource.getPath();
        final int lastSlash = path.lastIndexOf("/");

        //Fim da recurso
        if (lastSlash != 0) {
            String parentFolderPath = StringUtils.substringBeforeLast(path, "/");

            Folder parentFolder = new FolderDAO().findFolderByPath(commit.getVcsMiningProject(),
                    parentFolderPath);

            if (parentFolder != null) {
                resource.setParentFolder(parentFolder);
            } else {
                parentFolder = new Folder();
                parentFolder.setPath(parentFolderPath);
                parentFolder.setName(StringUtils.substringAfterLast(parentFolder.getPath(), "/"));
                parentFolder.setOperationType('A');
                parentFolder.setCommit(commit);
                resource.setParentFolder(parentFolder);

                new FolderDAO().insert(parentFolder);

                fixFolder(parentFolder, commit);
            }
        }
    } catch (DatabaseException e) {
        e.printStackTrace();
    }
}

From source file:mediathekplugin.Database.java

public ArrayList<MediathekProgramItem> getMediathekPrograms(final Program program) {
    ArrayList<MediathekProgramItem> result = new ArrayList<MediathekProgramItem>();
    String channelName = unifyChannelName(program.getChannel().getName());
    HashMap<Long, ArrayList<Integer>> programsMap = mChannelItems.get(channelName);
    // search parts in brackets like for ARD
    if (programsMap == null && channelName.contains("(")) {
        String bracketPart = StringUtils.substringBetween(channelName, "(", ")");
        programsMap = mChannelItems.get(bracketPart);
    }// w ww.  j av  a 2  s. c  o  m
    // search for partial name, if full name is not found
    if (programsMap == null && channelName.contains(" ")) {
        String firstPart = StringUtils.substringBefore(channelName, " ");
        programsMap = mChannelItems.get(firstPart);
    }
    if (programsMap == null) {
        for (Entry<String, HashMap<Long, ArrayList<Integer>>> entry : mChannelItems.entrySet()) {
            if (StringUtils.startsWithIgnoreCase(channelName, entry.getKey())) {
                programsMap = entry.getValue();
                break;
            }
        }
    }
    if (programsMap == null) {
        return result;
    }
    String title = program.getTitle();
    ArrayList<Integer> programs = programsMap.get(getKey(title));
    if (programs == null && title.endsWith(")") && title.contains("(")) {
        String newTitle = StringUtils.substringBeforeLast(title, "(").trim();
        programs = programsMap.get(getKey(newTitle));
    }
    if (programs == null && title.endsWith("...")) {
        String newTitle = title.substring(0, title.length() - 3).trim();
        programs = programsMap.get(getKey(newTitle));
    }
    if (programs == null) {
        return result;
    }
    try {
        RandomAccessFile file = new RandomAccessFile(new File(mFileName), "r");
        for (Integer byteOffset : programs) {
            file.seek(byteOffset);
            String lineEncoded = file.readLine();
            String line = new String(lineEncoded.getBytes(), "UTF-8");
            Matcher itemMatcher = ITEM_PATTERN.matcher(line);
            if (itemMatcher.find()) {
                String itemTitle = itemMatcher.group(3).trim();
                String itemUrl = itemMatcher.group(4).trim();
                result.add(new MediathekProgramItem(itemTitle, itemUrl, null));
            }
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return result;
}

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

private void createBinaryFilePropertiesFile(String source, String target) {
    List<String> lines = new ArrayList<>();
    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);
    path = replaceAliasWithRootFolderName(path);
    path = finalisePath(path);//  w  w  w.j  a v  a  2s . co  m
    String file = StringUtils.substringAfterLast(source, FS).replace(project, PROJECT_ALIAS);
    lines.add("template = " + template);
    lines.add("template-type = document");
    lines.add("path = " + path);
    lines.add("file = " + file);
    lines.add("preserve = true");
    FilUtils.mkdirs(folder);
    if (write(properties, lines, WINDOWS_CHARSET)) {
        propertiesFilesCreated++;
    }
}

From source file:com.cloudera.flume.handlers.hdfs.CustomDfsSink.java

@Override
public void close() {
    try {/* w  w w .  j  a v  a2  s .  c  om*/
        LOG.info("Closing HDFS file: " + dstPath);
        writer.flush();
        LOG.info("done writing raw file to hdfs");
        writer.close();

        if (StringUtils.isNotBlank(elasticSearchUrl) && StringUtils.isNotBlank(elasticIndex)
                && StringUtils.isNotBlank(elasticType)) {
            hup.sendESQuery(elasticSearchUrl, sb.toString());
        }

        if (!deleteEmptyFile(dstPath)) {
            if (localEvent != null && hiveOutput) {
                String dataFolder = StringUtils.substringBeforeLast(dstPath.toString(), "/");

                //String hqlQuery = "ALTER TABLE " + hiveTableName + " ADD IF NOT EXISTS PARTITION (ds='" + dateFormatDay.format(cal.getTime()) + "', ts='" + dateFormatHour.format(cal.getTime()) + "') LOCATION '" + dataFolder + "'";
                String hqlQuery = "ALTER TABLE " + hiveTableName + " ADD IF NOT EXISTS PARTITION (ds='"
                        + dateFormatDay.format(localEvent.getTimestamp()) + "', ts='"
                        + dateFormatHour.format(localEvent.getTimestamp()) + "') LOCATION '" + dataFolder + "'";

                LOG.info("HQL Query: " + hqlQuery + "\n\n\n\n\n");

                hiveMarkerPath = hiveMarkerFolder + "/" + machineHostName + "-" + localEvent.getTimestamp()
                        + ".marker";

                if (!hup.runHiveQuery(hqlQuery)) {
                    writeHiveMarker(hqlQuery, dstPath.toString(), hiveMarkerFolder, hiveMarkerPath);
                }
                //      boolean hiveMarkerStatus = writeHiveMarker(hqlQuery, dstPath.toString(), hiveMarkerFolder, hiveMarkerPath);
                //
                //      if (hiveMarkerStatus) {
                //        if (hup.runHiveQuery(hqlQuery)) {
                //          hup.cleanHiveMarker(hiveMarkerPath);
                //        }
                //      }
            }
        } else {
            LOG.info("deleted empty file: " + dstPath);
        }
        localEvent = null;
        cal = null;

        writer = null;
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:de.awtools.basic.file.AWToolsFileUtils.java

/**
 * Siehe die Beschreibung in Methode/*from  w  w w  .  j  a  v a  2s .c om*/
 * {@link #findFiles(java.io.File, java.lang.String, java.lang.String)}.
 *
 * @param basePath Basisverzeichnis.
 * @param fileName Die gesuchte Datei.
 * @return Eine Liste der gefundenen Dateien.
 *
 * @see #findFiles(java.io.File, java.lang.String, java.lang.String)
 */
public static List<File> findFiles(final File basePath, final String fileName) {

    String relativePath = "";
    String realFileName = fileName;

    if ((StringUtils.contains(fileName, "/"))) {
        relativePath = StringUtils.substringBeforeLast(fileName, "/");
        realFileName = StringUtils.substringAfterLast(fileName, "/");
    }

    if (log.isDebugEnabled()) {
        log.debug("basePath ......: " + basePath);
        log.debug("relativePath ..: " + relativePath);
        log.debug("realFileName ..: " + realFileName);
    }

    return AWToolsFileUtils.findFiles(basePath, relativePath, realFileName);
}