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

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

Introduction

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

Prototype

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

Source Link

Document

Gets the substring after the first occurrence of a separator.

Usage

From source file:org.sleuthkit.autopsy.timeline.ui.detailview.tree.DescriptionTreeItem.java

@Override
public void insert(List<TimeLineEvent> path) {
    TimeLineEvent head = path.remove(0);

    //strip off parent description
    String substringAfter = StringUtils.substringAfter(head.getDescription(),
            head.getParentStripe().map(EventStripe::getDescription).orElse(""));

    //create or get existing tree item for the description
    DescriptionTreeItem treeItem = childMap.computeIfAbsent(substringAfter,
            description -> configureNewTreeItem(new DescriptionTreeItem(head, getComparator())));

    //insert rest of path in to tree item
    if (path.isEmpty() == false) {
        treeItem.insert(path);//from   ww w . j  a  v a  2  s .c o  m
    }
}

From source file:org.sleuthkit.autopsy.timeline.ui.detailview.tree.DescriptionTreeItem.java

@Override
void remove(List<TimeLineEvent> path) {
    TimeLineEvent head = path.remove(0);
    //strip off parent description
    String substringAfter = StringUtils.substringAfter(head.getDescription(),
            head.getParentStripe().map(EventStripe::getDescription).orElse(""));

    DescriptionTreeItem descTreeItem = childMap.get(substringAfter);

    //remove path from child too 
    if (descTreeItem != null) {
        if (path.isEmpty() == false) {
            descTreeItem.remove(path);//  w  ww.  j  ava 2s  . c o m
        }
        //if child item has no children, remove it also.
        if (descTreeItem.getChildren().isEmpty()) {
            childMap.remove(substringAfter);
            getChildren().remove(descTreeItem);
        }
    }
}

From source file:org.sleuthkit.autopsy.timeline.ui.detailview.tree.DescriptionTreeItem.java

@Override
String getDisplayText() {/* w  ww  .  j  a  v  a  2  s .  com*/

    String text = getValue().getDescription() + " (" + getValue().getSize() + ")"; // NON-NLS

    TreeItem<TimeLineEvent> parent = getParent();
    if (parent != null && parent.getValue() != null && (parent instanceof DescriptionTreeItem)) {
        //strip off parent description
        text = StringUtils.substringAfter(text, parent.getValue().getDescription());
    }
    return text;
}

From source file:org.spdx.rdfparser.license.TestListedLicenses.java

@Test
public void testLicenseListVersionFormat() {
    String licenseListversion = ListedLicenses.getListedLicenses().getLicenseListVersion();

    Assert.assertEquals("Expected one point in license list version. ", 1,
            StringUtils.countMatches(licenseListversion, "."));
    Assert.assertTrue("Number expected before the point in license list version (" + licenseListversion + ")",
            StringUtils.isNumeric(StringUtils.substringBefore(licenseListversion, ".")));
    Assert.assertTrue("Number expected after the point in license list version (" + licenseListversion + ")",
            StringUtils.isNumeric(StringUtils.substringAfter(licenseListversion, ".")));
}

From source file:org.spicyurl.UrlParser.java

private void parseLogin(String login) {
    if (StringUtils.contains(login, USER_PASS_SEP)) {
        url.setUsername(StringUtils.substringBefore(login, USER_PASS_SEP));
        url.setPassword(StringUtils.substringAfter(login, USER_PASS_SEP));
    } else {//from  w w w. j av a 2s .c  o  m
        url.setUsername(login);
    }
}

From source file:org.structr.console.rest.AsRestCommand.java

@Override
public boolean parseNext(final String line, final Writable writable) throws IOException {

    final String trimmed = line.trim();
    final String userString = StringUtils.substringBefore(trimmed, " ");
    final String remaining = StringUtils.substringAfter(trimmed, " ");

    if (StringUtils.isNoneBlank(userString, remaining)) {

        command = RestCommand.parse(remaining, writable);
        if (command != null) {

            final String[] parts = userString.split("[:]+");
            if (parts.length == 2) {

                command.authenticate(parts[0], parts[1]);

                // success
                return true;

            } else {

                writable.println("Syntax error, user string must be <username>:<password>.");
            }//w  w w .j  a v a  2  s  .  c o m
        }

    } else {

        writable.println("Syntax error, user string must be <username>:<password>.");
    }

    return false;
}

From source file:org.structr.console.rest.RestCommand.java

public static RestCommand parse(final String line, final Writable writable) throws IOException {

    // first (root) command will always be a single word
    final String trimmed = line.trim();
    final String firstWord = StringUtils.substringBefore(trimmed, " ");
    final String remaining = StringUtils.substringAfter(trimmed, " ");

    if (StringUtils.isNotBlank(firstWord)) {

        final RestCommand cmd = getCommand(firstWord);
        if (cmd != null) {

            if (StringUtils.isBlank(remaining) || cmd.parseNext(remaining, writable)) {

                return cmd;
            }/*w w  w. ja va  2s .com*/

        } else {

            writable.println("Unknown command '" + firstWord + "'.");
        }
    }

    return null;
}

From source file:org.structr.web.datasource.RestDataSource.java

public List<GraphObject> getData(final RenderContext renderContext, final String restQuery)
        throws FrameworkException {

    final Map<Pattern, Class<? extends Resource>> resourceMap = new LinkedHashMap<>();
    final SecurityContext securityContext = renderContext.getSecurityContext();

    ResourceProvider resourceProvider = renderContext.getResourceProvider();
    if (resourceProvider == null) {
        try {/*  w  w w . ja v  a 2  s .c  o  m*/
            resourceProvider = UiResourceProvider.class.newInstance();
        } catch (Throwable t) {
            logger.log(Level.SEVERE, "Couldn't establish a resource provider", t);
            return Collections.EMPTY_LIST;
        }
    }

    // inject resources
    resourceMap.putAll(resourceProvider.getResources());

    Value<String> propertyView = new ThreadLocalPropertyView();
    propertyView.set(securityContext, PropertyView.Ui);

    HttpServletRequest request = securityContext.getRequest();
    if (request == null) {
        request = renderContext.getRequest();
    }

    // initialize variables
    // mimic HTTP request
    final HttpServletRequest wrappedRequest = new HttpServletRequestWrapper(request) {

        @Override
        public Enumeration<String> getParameterNames() {
            return new IteratorEnumeration(getParameterMap().keySet().iterator());
        }

        @Override
        public String getParameter(final String key) {
            String[] p = getParameterMap().get(key);
            return p != null ? p[0] : null;
        }

        @Override
        public String[] getParameterValues(final String key) {
            return getParameterMap().get(key);
        }

        @Override
        public Map<String, String[]> getParameterMap() {
            String[] parts = StringUtils.split(getQueryString(), "&");
            Map<String, String[]> parameterMap = new HashMap();
            for (String p : parts) {
                String[] kv = StringUtils.split(p, "=");
                if (kv.length > 1) {
                    parameterMap.put(kv[0], new String[] { kv[1] });
                }
            }
            return parameterMap;
        }

        @Override
        public String getQueryString() {
            return StringUtils.substringAfter(restQuery, "?");
        }

        @Override
        public String getPathInfo() {
            return StringUtils.substringBefore(restQuery, "?");
        }

        @Override
        public StringBuffer getRequestURL() {
            return new StringBuffer(restQuery);
        }
    };

    // store original request
    final HttpServletRequest origRequest = securityContext.getRequest();

    // update request in security context
    securityContext.setRequest(wrappedRequest);

    //HttpServletResponse response = renderContext.getResponse();
    Resource resource = null;
    try {

        resource = ResourceHelper.applyViewTransformation(wrappedRequest, securityContext,
                ResourceHelper.optimizeNestedResourceChain(
                        ResourceHelper.parsePath(securityContext, wrappedRequest, resourceMap, propertyView)),
                propertyView);

    } catch (IllegalPathException | NotFoundException e) {

        logger.log(Level.WARNING, "Illegal path for REST query: {0}", restQuery);

    }

    // reset request to old context
    securityContext.setRequest(origRequest);

    if (resource == null) {

        return Collections.EMPTY_LIST;

    }

    // TODO: decide if we need to rest the REST request here
    //securityContext.checkResourceAccess(request, resource.getResourceSignature(), resource.getGrant(request, response), PropertyView.Ui);
    // add sorting & paging
    String pageSizeParameter = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_PAGE_SIZE);
    String pageParameter = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_PAGE_NUMBER);
    String offsetId = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_OFFSET_ID);
    String sortOrder = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_SORT_ORDER);
    String sortKeyName = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_SORT_KEY);
    boolean sortDescending = (sortOrder != null && "desc".equals(sortOrder.toLowerCase()));
    int pageSize = parseInt(pageSizeParameter, NodeFactory.DEFAULT_PAGE_SIZE);
    int page = parseInt(pageParameter, NodeFactory.DEFAULT_PAGE);
    PropertyKey sortKey = null;

    // set sort key
    if (sortKeyName != null) {

        Class<? extends GraphObject> type = resource.getEntityClass();
        if (type == null) {

            // fallback to default implementation
            // if no type can be determined
            type = AbstractNode.class;

        }
        sortKey = StructrApp.getConfiguration().getPropertyKeyForDatabaseName(type, sortKeyName, false);
    }

    // do action
    Result result = Result.EMPTY_RESULT;

    try {
        result = resource.doGet(sortKey, sortDescending, pageSize, page, offsetId);

    } catch (NotFoundException nfe) {
        logger.log(Level.WARNING, "No result from internal REST query: {0}", restQuery);
    }

    result.setIsCollection(resource.isCollectionResource());
    result.setIsPrimitiveArray(resource.isPrimitiveArray());

    //Integer rawResultCount = (Integer) Services.getAttribute(NodeFactory.RAW_RESULT_COUNT + Thread.currentThread().getId());
    PagingHelper.addPagingParameter(result, pageSize, page);

    List<GraphObject> res = result.getResults();

    if (renderContext != null) {
        renderContext.setResult(result);
    }

    return res != null ? res : Collections.EMPTY_LIST;

}

From source file:org.structr.web.importer.Importer.java

private Linkable downloadFile(final String downloadAddress, final URL base) {

    URL downloadUrl = null;/*from   www  .ja  v a 2s.c  o m*/

    try {

        downloadUrl = new URL(base, downloadAddress);

    } catch (MalformedURLException ex) {

        logger.error("Could not resolve address {}", address != null ? address.concat("/") : "");
        return null;
    }

    final String alreadyDownloadedKey = downloadUrl.getPath();

    // Don't download the same file twice
    if (alreadyDownloaded.containsKey(alreadyDownloadedKey)) {
        return alreadyDownloaded.get(alreadyDownloadedKey);
    }

    long size;
    long checksum;
    String contentType;
    java.io.File tmpFile;

    try {
        // create temporary file on disk
        final Path tmpFilePath = Files.createTempFile("structr", "download");
        tmpFile = tmpFilePath.toFile();

    } catch (IOException ioex) {

        logger.error("Unable to create temporary file for download, aborting.");
        return null;
    }

    try {

        logger.info("Starting download from {}", downloadUrl);

        copyURLToFile(downloadUrl.toString(), tmpFile);

    } catch (IOException ioe) {

        if (originalUrl == null || address == null) {

            logger.info("Cannot download from {} without base address", downloadAddress);
            return null;

        }

        logger.warn("Unable to download from {} {}", new Object[] { originalUrl, downloadAddress });

        try {
            // Try alternative baseUrl with trailing "/"
            if (address.endsWith("/")) {

                // don't append a second slash!
                logger.info("Starting download from alternative URL {} {} {}",
                        new Object[] { originalUrl, address, downloadAddress });
                downloadUrl = new URL(new URL(originalUrl, address), downloadAddress);

            } else {

                // append a slash
                logger.info("Starting download from alternative URL {} {} {}",
                        new Object[] { originalUrl, address.concat("/"), downloadAddress });
                downloadUrl = new URL(new URL(originalUrl, address.concat("/")), downloadAddress);
            }

            copyURLToFile(downloadUrl.toString(), tmpFile);

        } catch (MalformedURLException ex) {
            logger.error("Could not resolve address {}", address.concat("/"));
            return null;
        } catch (IOException ex) {
            logger.warn("Unable to download from {}", address.concat("/"));
            return null;
        }

        logger.info("Starting download from alternative URL {}", downloadUrl);

    }

    //downloadAddress = StringUtils.substringBefore(downloadAddress, "?");
    final String downloadName = cleanFileName(downloadUrl.getFile());
    final String fileName = PathHelper.getName(downloadName);

    if (StringUtils.isBlank(fileName)) {

        logger.warn("Can't figure out filename from download address {}, aborting.", downloadAddress);

        return null;
    }

    // TODO: Add security features like null/integrity/virus checking before copying it to
    // the files repo
    try {

        contentType = FileHelper.getContentMimeType(tmpFile, fileName);
        checksum = FileHelper.getChecksum(tmpFile);
        size = tmpFile.length();

    } catch (IOException ioe) {

        logger.warn("Unable to determine MIME type, size or checksum of {}", tmpFile);
        return null;
    }

    logger.info("Download URL: {}, address: {}, cleaned address: {}, filename: {}",
            new Object[] { downloadUrl, address, StringUtils.substringBeforeLast(address, "/"), fileName });

    String relativePath = StringUtils.substringAfter(downloadUrl.toString(),
            StringUtils.substringBeforeLast(address, "/"));
    if (StringUtils.isBlank(relativePath)) {

        relativePath = downloadAddress;
    }

    final String path;
    final String httpPrefix = "http://";
    final String httpsPrefix = "https://";
    final String flexiblePrefix = "//";

    if (downloadAddress.startsWith(httpsPrefix)) {

        path = StringUtils.substringBefore((StringUtils.substringAfter(downloadAddress, httpsPrefix)), "/");

    } else if (downloadAddress.startsWith(httpPrefix)) {

        path = StringUtils.substringBefore((StringUtils.substringAfter(downloadAddress, httpPrefix)), "/");

    } else if (downloadAddress.startsWith(flexiblePrefix)) {

        path = StringUtils.substringBefore((StringUtils.substringAfter(downloadAddress, flexiblePrefix)), "/");

    } else {

        path = StringUtils.substringBeforeLast(relativePath, "/");
    }

    logger.info("Relative path: {}, final path: {}", relativePath, path);

    if (contentType.equals("text/plain")) {

        contentType = StringUtils.defaultIfBlank(
                contentTypeForExtension.get(StringUtils.substringAfterLast(fileName, ".")), "text/plain");
    }

    try {

        final String fullPath = path + "/" + fileName;

        File fileNode = fileExists(fullPath, checksum);
        if (fileNode == null) {

            if (ImageHelper.isImageType(fileName)) {

                fileNode = createImageNode(fullPath, contentType, size, checksum);

            } else {

                fileNode = createFileNode(fullPath, contentType, size, checksum);
            }

            final java.io.File imageFile = fileNode.getFileOnDisk(false);
            final Path imagePath = imageFile.toPath();

            // rename / move file to final location
            Files.move(tmpFile.toPath(), imagePath);

            if (contentType.equals("text/css")) {

                processCssFileNode(fileNode, downloadUrl);
            }

            // set export flag according to user preference
            fileNode.setProperty(StructrApp.key(File.class, "includeInFrontendExport"), includeInExport);

        } else {

            tmpFile.delete();
        }

        alreadyDownloaded.put(alreadyDownloadedKey, fileNode);
        return fileNode;

    } catch (final FrameworkException | IOException ex) {

        logger.warn("Could not create file node.", ex);

    }

    return null;

}

From source file:org.structr.web.Importer.java

private Linkable downloadFile(String downloadAddress, final URL base) {

    final String uuid = UUID.randomUUID().toString().replaceAll("[\\-]+", "");
    String contentType;//from ww  w . j  a v  a2 s .  c  o  m

    // Create temporary file with new uuid
    // FIXME: This is much too dangerous!
    final String relativeFilePath = File.getDirectoryPath(uuid) + "/" + uuid;
    final String filePath = FileHelper.getFilePath(relativeFilePath);
    final java.io.File fileOnDisk = new java.io.File(filePath);

    fileOnDisk.getParentFile().mkdirs();

    long size;
    long checksum;
    URL downloadUrl;

    try {

        downloadUrl = new URL(base, downloadAddress);

        logger.log(Level.INFO, "Starting download from {0}", downloadUrl);

        copyURLToFile(downloadUrl.toString(), fileOnDisk);

    } catch (IOException ioe) {

        if (originalUrl == null || address == null) {

            logger.log(Level.INFO, "Cannot download from {0} without base address", downloadAddress);
            return null;

        }

        logger.log(Level.WARNING, "Unable to download from {0} {1}",
                new Object[] { originalUrl, downloadAddress });
        ioe.printStackTrace();

        try {
            // Try alternative baseUrl with trailing "/"
            if (address.endsWith("/")) {

                // don't append a second slash!
                logger.log(Level.INFO, "Starting download from alternative URL {0} {1} {2}",
                        new Object[] { originalUrl, address, downloadAddress });
                downloadUrl = new URL(new URL(originalUrl, address), downloadAddress);

            } else {

                // append a slash
                logger.log(Level.INFO, "Starting download from alternative URL {0} {1} {2}",
                        new Object[] { originalUrl, address.concat("/"), downloadAddress });
                downloadUrl = new URL(new URL(originalUrl, address.concat("/")), downloadAddress);
            }

            copyURLToFile(downloadUrl.toString(), fileOnDisk);

        } catch (MalformedURLException ex) {
            ex.printStackTrace();
            logger.log(Level.SEVERE, "Could not resolve address {0}", address.concat("/"));
            return null;
        } catch (IOException ex) {
            ex.printStackTrace();
            logger.log(Level.WARNING, "Unable to download from {0}", address.concat("/"));
            return null;
        }

        logger.log(Level.INFO, "Starting download from alternative URL {0}", downloadUrl);

    }

    downloadAddress = StringUtils.substringBefore(downloadAddress, "?");
    final String fileName = PathHelper.getName(downloadAddress);

    if (StringUtils.isBlank(fileName)) {

        logger.log(Level.WARNING, "Can't figure out filename from download address {0}, aborting.",
                downloadAddress);

        return null;
    }

    // TODO: Add security features like null/integrity/virus checking before copying it to
    // the files repo
    try {

        contentType = FileHelper.getContentMimeType(fileOnDisk, fileName);
        size = fileOnDisk.length();
        checksum = FileUtils.checksumCRC32(fileOnDisk);

    } catch (IOException ioe) {

        logger.log(Level.WARNING, "Unable to determine MIME type, size or checksum of {0}", fileOnDisk);
        return null;
    }

    String httpPrefix = "http://";

    logger.log(Level.INFO, "Download URL: {0}, address: {1}, cleaned address: {2}, filename: {3}",
            new Object[] { downloadUrl, address, StringUtils.substringBeforeLast(address, "/"), fileName });

    String relativePath = StringUtils.substringAfter(downloadUrl.toString(),
            StringUtils.substringBeforeLast(address, "/"));
    if (StringUtils.isBlank(relativePath)) {
        relativePath = downloadAddress;
    }

    final String path = StringUtils.substringBefore(
            ((downloadAddress.contains(httpPrefix)) ? StringUtils.substringAfter(downloadAddress, "http://")
                    : relativePath),
            fileName);

    logger.log(Level.INFO, "Relative path: {0}, final path: {1}", new Object[] { relativePath, path });

    if (contentType.equals("text/plain")) {

        contentType = StringUtils.defaultIfBlank(
                contentTypeForExtension.get(StringUtils.substringAfterLast(fileName, ".")), "text/plain");
    }

    final String ct = contentType;

    try {

        FileBase fileNode = fileExists(fileName, checksum);
        if (fileNode == null) {

            if (ImageHelper.isImageType(fileName)) {

                fileNode = createImageNode(uuid, fileName, ct, size, checksum);
            } else {

                fileNode = createFileNode(uuid, fileName, ct, size, checksum);
            }

            if (fileNode != null) {

                Folder parent = FileHelper.createFolderPath(securityContext, path);

                if (parent != null) {

                    fileNode.setProperty(File.parent, parent);

                }

                if (contentType.equals("text/css")) {

                    processCssFileNode(fileNode, downloadUrl);
                }

                if (!fileNode.validatePath(securityContext, null)) {
                    fileNode.setProperty(AbstractNode.name,
                            fileName.concat("_").concat(FileHelper.getDateString()));
                }

            }

            return fileNode;

        } else {

            fileOnDisk.delete();
            return fileNode;
        }

    } catch (FrameworkException | IOException fex) {

        logger.log(Level.WARNING, "Could not create file node.", fex);

    }

    return null;

}