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

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

Introduction

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

Prototype

public static String stripStart(final String str, final String stripChars) 

Source Link

Document

Strips any of a set of characters from the start of a String.

A null input String returns null .

Usage

From source file:org.sleuthkit.autopsy.imagegallery.gui.navpanel.NavPanel.java

private static List<String> groupingToPath(DrawableGroup g) {

    if (g.groupKey.getAttribute() == DrawableAttribute.PATH) {
        String path = g.groupKey.getValueDisplayName();

        String cleanPath = StringUtils.stripStart(path, "/");
        String[] tokens = cleanPath.split("/");

        return Arrays.asList(tokens);
    } else {//w w w .  java2  s .  c  o m
        return Arrays.asList(g.groupKey.getValueDisplayName());
    }
}

From source file:org.structr.core.graph.search.PropertySearchAttribute.java

@Override
public Query getQuery() {

    if (isExactMatch) {

        String value = getStringValue();

        if (StringUtils.isEmpty(value)) {

            value = getValueForEmptyField();
        }/*from ww w.j  a v  a2 s .  c o  m*/

        if (value.matches("[\\s]+")) {

            value = "\"" + value + "\"";
        }

        return new TermQuery(new Term(getKey().dbName(), value));

    } else {

        String value = getInexactValue();

        // If there are double quotes around the search value treat as phrase
        if (value.startsWith("\"") && value.endsWith("\"")) {

            value = StringUtils.stripStart(StringUtils.stripEnd(value, "\""), "\"");

            // Split string into words
            String[] words = StringUtils.split(value, " ");

            PhraseQuery query = new PhraseQuery();

            for (String word : words) {

                query.add(new Term(getKey().dbName(), word));

            }

            return query;

        }

        BooleanQuery query = new BooleanQuery();

        // Split string into words
        String[] words = StringUtils.split(value, " ");

        for (String word : words) {

            query.add(new WildcardQuery(new Term(getKey().dbName(), word)), Occur.SHOULD);

            word = "*" + SearchCommand.escapeForLucene(word) + "*";

            query.add(new WildcardQuery(new Term(getKey().dbName(), word)), Occur.SHOULD);
        }

        return query;
    }
}

From source file:org.structr.files.ftp.StructrFileSystemView.java

@Override
public FtpFile getFile(String requestedPath) throws FtpException {

    logger.log(Level.INFO, "Requested path: {0}", requestedPath);

    try (Tx tx = StructrApp.getInstance().tx()) {

        if (StringUtils.isBlank(requestedPath) || "/".equals(requestedPath)) {
            return getHomeDirectory();
        }//from w  ww .  ja  v a 2  s . c  om

        StructrFtpFolder cur = (StructrFtpFolder) getWorkingDirectory();

        if (".".equals(requestedPath) || "./".equals(requestedPath)) {
            return cur;
        }

        if ("..".equals(requestedPath) || "../".equals(requestedPath)) {
            return new StructrFtpFolder(cur.getStructrFile().getProperty(AbstractFile.parent));
        }

        // If relative path requested, prepend base path
        if (!requestedPath.startsWith("/")) {

            String basePath = cur.getAbsolutePath();

            logger.log(Level.INFO, "Base path: {0}", basePath);

            while (requestedPath.startsWith("..")) {
                requestedPath = StringUtils.stripStart(StringUtils.stripStart(requestedPath, ".."), "/");
                basePath = StringUtils.substringBeforeLast(basePath, "/");
            }

            requestedPath = StringUtils.stripEnd(basePath.equals("/") ? "/".concat(requestedPath)
                    : basePath.concat("/").concat(requestedPath), "/");

            logger.log(Level.INFO, "Base path: {0}, requestedPath: {1}",
                    new Object[] { basePath, requestedPath });

        }

        AbstractFile file = FileHelper.getFileByAbsolutePath(SecurityContext.getSuperUserInstance(),
                requestedPath);

        if (file != null) {

            if (file instanceof Folder) {
                tx.success();
                return new StructrFtpFolder((Folder) file);
            } else {
                tx.success();
                return new StructrFtpFile((File) file);
            }
        }

        // Look up a page by its name
        Page page = StructrApp.getInstance().nodeQuery(Page.class).andName(PathHelper.getName(requestedPath))
                .getFirst();
        if (page != null) {
            tx.success();
            return page;
        }

        logger.log(Level.WARNING, "No existing file found: {0}", requestedPath);

        tx.success();
        return new FileOrFolder(requestedPath, user);

    } catch (FrameworkException fex) {
        logger.log(Level.SEVERE, "Error in getFile()", fex);
    }

    return null;

}

From source file:org.structr.neo4j.index.lucene.factory.FulltextQueryFactory.java

@Override
public Query getQuery(final QueryFactory<Query> parent, final QueryPredicate predicate) {

    final boolean isExactMatch = predicate.isExactMatch();
    if (isExactMatch) {

        String value = getReadValue(predicate).toString();

        if (StringUtils.isEmpty(value)) {

            value = getReadValue(null).toString();
        }/*from  w ww .j a v a 2s . co  m*/

        if (value.matches("[\\s]+")) {

            value = "\"" + value + "\"";
        }

        return new TermQuery(new Term(predicate.getName(), value));

    } else {

        String value = getInexactValue(predicate).toString();

        // If there are double quotes around the search value treat as phrase
        if (value.startsWith("\"") && value.endsWith("\"")) {

            value = StringUtils.stripStart(StringUtils.stripEnd(value, "\""), "\"");

            // Split string into words
            String[] words = StringUtils.split(value, " ");

            PhraseQuery query = new PhraseQuery();

            for (String word : words) {

                query.add(new Term(predicate.getName(), word));

            }

            return query;

        }

        BooleanQuery query = new BooleanQuery();

        // Split string into words
        String[] words = StringUtils.split(value, " ");

        for (String word : words) {

            query.add(new WildcardQuery(new Term(predicate.getName(), word)), Occur.SHOULD);
            query.add(new WildcardQuery(new Term(predicate.getName(), "*" + escape(word) + "*")), Occur.SHOULD);
        }

        return query;
    }
}

From source file:org.structr.web.auth.GitHubAuthClient.java

@Override
public String getCredential(final HttpServletRequest request) {

    OAuthResourceResponse userResponse = getUserResponse(request);

    if (userResponse == null) {

        return null;

    }// www .  j av a 2 s .co m

    String body = userResponse.getBody();
    logger.log(Level.FINE, "User response body: {0}", body);

    String[] addresses = StringUtils.stripAll(
            StringUtils.stripAll(StringUtils.stripEnd(StringUtils.stripStart(body, "["), "]").split(",")),
            "\"");

    return addresses.length > 0 ? addresses[0] : null;

}

From source file:org.structr.web.maintenance.BulkMoveUnusedFilesCommand.java

@Override
public void execute(final Map<String, Object> properties) throws FrameworkException {

    String mode = (String) properties.get("mode");
    String targetDir = (String) properties.get("target");

    if (StringUtils.isBlank(mode)) {
        // default
        mode = "log";
    }/*from   w  w  w. ja v  a 2  s.  c  o  m*/

    if (StringUtils.isBlank(targetDir)) {
        // default
        targetDir = "unused";
    }

    logger.log(Level.INFO, "Starting moving of unused files...");

    final DatabaseService graphDb = (DatabaseService) arguments.get("graphDb");
    final App app = StructrApp.getInstance();

    final String filesLocation = StructrApp.getConfigurationValue(Services.FILES_PATH);

    final Set<String> filePaths = new TreeSet<>();

    if (graphDb != null) {

        List<FileBase> fileNodes = null;

        try (final Tx tx = StructrApp.getInstance().tx()) {

            fileNodes = app.nodeQuery(FileBase.class, false).getAsList();

            for (final FileBase fileNode : fileNodes) {

                final String relativeFilePath = fileNode.getProperty(FileBase.relativeFilePath);

                if (relativeFilePath != null) {
                    filePaths.add(relativeFilePath);
                }
            }

            tx.success();
        }

        final List<Path> files = new LinkedList<>();

        try {

            Files.walk(Paths.get(filesLocation), FileVisitOption.FOLLOW_LINKS).filter(Files::isRegularFile)
                    .forEach((Path file) -> {
                        files.add(file);
                    });

        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        }

        Path targetDirPath = null;

        if (targetDir.startsWith("/")) {
            targetDirPath = Paths.get(targetDir);
        } else {
            targetDirPath = Paths.get(filesLocation, targetDir);

        }

        if (mode.equals("move") && !Files.exists(targetDirPath)) {

            try {
                targetDirPath = Files.createDirectory(targetDirPath);

            } catch (IOException ex) {
                logger.log(Level.INFO, "Could not create target directory {0}: {1}",
                        new Object[] { targetDir, ex });
                return;
            }
        }

        for (final Path file : files) {

            final String filePath = file.toString();
            final String relPath = StringUtils.stripStart(filePath.substring(filesLocation.length()), "/");

            //System.out.println("files location: " + filesLocation + ", file path: " + filePath + ", rel path: " + relPath);
            if (!filePaths.contains(relPath)) {

                if (mode.equals("log")) {

                    System.out
                            .println("File " + file + " doesn't exist in database (rel path: " + relPath + ")");

                } else if (mode.equals("move")) {

                    try {
                        final Path targetPath = Paths.get(targetDirPath.toString(),
                                file.getFileName().toString());

                        Files.move(file, targetPath);

                        System.out.println("File " + file.getFileName() + " moved to " + targetPath);

                    } catch (IOException ex) {
                        logger.log(Level.INFO, "Could not move file {0} to target directory {1}: {2}",
                                new Object[] { file, targetDir, ex });
                    }

                }
            }

        }

    }

    logger.log(Level.INFO, "Done");
}

From source file:org.voltdb.types.QueryType.java

/**
 * Determine what kind of SQL statement the given text represents.
 * Don't use rocket science or anything, use the first word mostly.
 * Code moved from deeper in the planner to here to be more general.
 * @param stmt String of SQL//from   ww  w  .j  a v a  2 s. c o m
 * @return Type of query
 */
public static QueryType getFromSQL(String stmt) {
    // trim the front whitespace, substring to the first word and normalize
    stmt = StringUtils.stripStart(stmt, null).substring(0, 6).toLowerCase();

    // determine the type of the query
    if (stmt.startsWith("insert")) {
        return QueryType.INSERT;
    } else if (stmt.startsWith("update")) {
        return QueryType.UPDATE;
    } else if (stmt.startsWith("delete") || stmt.startsWith("trunca")) {
        return QueryType.DELETE;
    } else if (stmt.startsWith("select")) {
        // This covers simple select statements as well as UNIONs and other set operations that are being used with default precedence
        // as in "select ... from ... UNION select ... from ...;"
        // Even if set operations are not currently supported, let them pass as "select" statements to let the parser sort them out.
        return QueryType.SELECT;
    } else if (stmt.startsWith("upsert")) {
        return QueryType.UPSERT;
    } else if (stmt.startsWith("(")) {
        // There does not seem to be a need to support parenthesized DML statements, so assume a read-only statement.
        // If that assumption is wrong, then it has probably gotten to the point that we want to drop this up-front
        // logic in favor of relying on the full parser/planner to determine the cataloged query type and read-only-ness.
        // Parenthesized query statements are typically complex set operations (UNIONS, etc.)
        // requiring parenthesis to explicitly determine precedence,
        // but they MAY be as simple as a needlessly parenthesized single select statement:
        // "( select * from table );" is valid SQL.
        // So, assume QueryType.SELECT.
        // If set operations require their own QueryType in the future, that's probably another case
        // motivating diving right in to the full parser/planner without this pre-check.
        // We don't want to be re-implementing the parser here -- this has already gone far enough.
        return QueryType.SELECT;
    }
    // else:
    // All the known statements are handled above, so default to cataloging an invalid read-only statement
    // and leave it to the parser/planner to more intelligently reject the statement as unsupported.
    return QueryType.INVALID;
}

From source file:org.wrml.runtime.format.application.schema.json.JsonSchema.java

public static UniqueName createJsonSchemaUniqueName(final URI schemaUri) {

    String uniqueNameString = schemaUri.getPath();
    uniqueNameString = StringUtils.stripStart(uniqueNameString, "/");
    uniqueNameString = StringUtils.stripEnd(uniqueNameString, "#");
    if (uniqueNameString.endsWith(".json")) {
        uniqueNameString = uniqueNameString.substring(0, uniqueNameString.length() - ".json".length());
    }/*from  w  w  w . j  a  va 2  s  .  c  o  m*/

    if (!uniqueNameString.contains("/")) {
        uniqueNameString = "schemas/" + uniqueNameString;
    }

    final UniqueName literalUniqueName = new UniqueName(uniqueNameString);
    return literalUniqueName;
}

From source file:org.wrml.runtime.schema.ProtoValueSource.java

/**
 * Convert the specified string value into a value that is compatible with the reference slot's type.
 *
 * @param stringValue The {@link String} value to coerce into a compatible value.
 * @param <T>         The generic return type that enables the caller to omit the cast operator.
 * @return The converted value of the specified string value.
 *//* w w w  . j ava  2 s. c  o  m*/
private <T> T coerceStringValue(final String stringValue) {

    if (stringValue == null || _ReferenceProtoSlot == null) {
        return (T) stringValue;
    }

    final Context context = _ReferenceProtoSlot.getContext();
    final SyntaxLoader syntaxLoader = context.getSyntaxLoader();
    final Type referenceSlotType = _ReferenceProtoSlot.getHeapValueType();

    if (ValueType.isListType(referenceSlotType)) {
        // [a, b, c]

        String listString = stringValue.trim();
        listString = StringUtils.stripStart(listString, "[");
        listString = StringUtils.stripEnd(listString, "]");
        if (listString.isEmpty()) {
            return (T) Collections.EMPTY_LIST;
        }

        final Type elementType = ValueType.getListElementType(referenceSlotType);

        final String[] listElementsStringArray = StringUtils.split(listString, ",");
        final List<Object> listValue = new ArrayList<>(listElementsStringArray.length);
        for (final String elementString : listElementsStringArray) {
            final Object element = syntaxLoader.parseSyntacticText(elementString.trim(), elementType);
            listValue.add(element);
        }

        return (T) listValue;
    } else {

        final Object value = syntaxLoader.parseSyntacticText(stringValue, referenceSlotType);
        return (T) value;
    }
}

From source file:org.wrml.runtime.service.file.FileSystemService.java

private Path getKeyLinkPath(final URI keyedSchemaUri, final Object keyValue) {

    final Path rootDirectoryPath = getRootDirectoryPath();
    Path path = rootDirectoryPath.resolve(StringUtils.stripStart(keyedSchemaUri.getPath(), "/"));
    path = path.resolve(STATIC_PATH_SEGMENT_KEYS);

    String keyValueString = null;

    if (keyValue instanceof URI) {
        final URI uri = (URI) keyValue;
        final String host = uri.getHost();
        if (host == null || host.trim().isEmpty()) {
            return null;
        }/*from  w  ww  . ja va  2  s.co  m*/

        path = path.resolve(host);
        final int port = (uri.getPort() == -1) ? 80 : uri.getPort();
        path = path.resolve(String.valueOf(port));
        keyValueString = StringUtils.stripStart(uri.getPath(), "/");
    } else {
        final Context context = getContext();
        keyValueString = context.getSyntaxLoader().formatSyntaxValue(keyValue);
    }

    if (keyValueString == null || keyValueString.equals("null")) {
        return null;
    }

    if (keyValueString.trim().isEmpty() || keyValueString.endsWith("/")) {
        keyValueString = "index";
    }

    if (!keyValueString.endsWith(getFileExtension())) {
        keyValueString += getFileExtension();
    }

    path = path.resolve(keyValueString);
    return path.normalize();
}