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

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

Introduction

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

Prototype

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

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

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

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

    if (StringUtils.isNotBlank(line)) {

        this.subCommand = StringUtils.substringBefore(line, " ").trim();
    }/*from   w  w  w.j a v a  2 s .co m*/

    return true;
}

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;
            }/*from  w  w w  . ja  v  a 2  s. c om*/

        } else {

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

    return null;
}

From source file:org.structr.core.entity.SchemaMethod.java

private void addType(final Queue<String> typeQueue, final AbstractSchemaNode schemaNode) {

    final String _extendsClass = schemaNode.getProperty(SchemaNode.extendsClass);
    if (_extendsClass != null) {

        typeQueue.add(StringUtils.substringBefore(_extendsClass, "<"));
    }//from w ww .  ja  v  a 2 s .c  o  m

    final String _interfaces = schemaNode.getProperty(SchemaNode.implementsInterfaces);
    if (_interfaces != null) {

        for (final String iface : _interfaces.split("[, ]+")) {

            typeQueue.add(iface);
        }
    }
}

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 {//from www  . ja  va 2s . com
            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  w w  w  .  j  ava2  s. 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;/*  w  ww  . j ava 2  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;

}

From source file:org.structr.websocket.command.WrappedRestCommand.java

@Override
public void processMessage(WebSocketMessage webSocketData) throws FrameworkException {

    final Map<String, Object> nodeData = webSocketData.getNodeData();
    final String method = (String) nodeData.get("method");

    if (method == null || !(method.equals("POST") || method.equals("PUT"))) {

        logger.log(Level.WARNING, "Method not supported: {0}", method);
        getWebSocket().send(//from   w w w .  j  a v a 2s .c om
                MessageBuilder.wrappedRest().code(422).message("Method not supported: " + method).build(),
                true);

        return;

    }

    ResourceProvider resourceProvider;
    try {

        resourceProvider = UiResourceProvider.class.newInstance();

    } catch (Throwable t) {

        logger.log(Level.SEVERE, "Couldn't establish a resource provider", t);
        getWebSocket().send(MessageBuilder.wrappedRest().code(422)
                .message("Couldn't establish a resource provider").build(), true);
        return;

    }

    final Map<Pattern, Class<? extends Resource>> resourceMap = new LinkedHashMap<>();
    resourceMap.putAll(resourceProvider.getResources());

    final StructrWebSocket socket = this.getWebSocket();
    final String url = (String) nodeData.get("url");

    // mimic HTTP request
    final HttpServletRequest wrappedRequest = new HttpServletRequestWrapper(socket.getRequest()) {

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

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

        @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(url, "?");
        }

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

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

    Resource resource;
    final StaticValue fakePropertyView = new StaticValue(PropertyView.Public);
    try {

        resource = ResourceHelper
                .applyViewTransformation(wrappedRequest, socket.getSecurityContext(),
                        ResourceHelper.optimizeNestedResourceChain(ResourceHelper.parsePath(
                                socket.getSecurityContext(), wrappedRequest, resourceMap, fakePropertyView)),
                        fakePropertyView);

    } catch (IllegalPathException | NotFoundException e) {

        logger.log(Level.WARNING, "Illegal path for REST query");
        getWebSocket().send(
                MessageBuilder.wrappedRest().code(422).message("Illegal path for REST query").build(), true);
        return;

    }

    final String data = (String) nodeData.get("data");
    final Gson gson = new GsonBuilder().create();
    final Map<String, Object> jsonData = gson.fromJson(data, Map.class);

    RestMethodResult result = null;

    switch (method) {
    case "PUT":
        // we want to update data
        result = resource.doPut(jsonData);

        break;

    case "POST":
        // we either want to create data or call a method on an object
        result = resource.doPost(jsonData);

        break;
    }

    // right now we do not send messages
    if (result != null) {
        //         getWebSocket().send(MessageBuilder.wrappedRest().code(result.getResponseCode()).message(result.jsonMessage()).build(), true);
    }

}

From source file:org.talend.daikon.exception.json.JsonErrorCode.java

/**
 * @return the error code group./*from w ww  .j  av a2  s . c om*/
 */
@Override
public String getGroup() {
    return StringUtils.substringBefore(StringUtils.substringAfter(code, "_"), "_"); //$NON-NLS-1$ //$NON-NLS-2$
}

From source file:org.wise.portal.domain.project.impl.Projectcode.java

/**
 * @return the runcode
 */
public String getRuncode() {
    return StringUtils.substringBefore(projectcode, SEPARATOR);
}

From source file:org.wrml.runtime.rest.RestUtils.java

public static final String getLastPathElement(final URI uri) {

    final String path = uri.getPath();
    if (StringUtils.isEmpty(path)) {
        return path;
    }/*from   w w w .  j  a v  a  2  s .  co m*/

    String lastPathElement = StringUtils.substringAfterLast(path, "/");
    lastPathElement = StringUtils.substringBefore(lastPathElement, "?");
    return lastPathElement;
}