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

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

Introduction

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

Prototype

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

Source Link

Document

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

A null input String returns null .

Usage

From source file:org.phenotips.integration.lims247.internal.RemoteSynchronizationEventListener.java

/**
 * Return the base URL of the specified remote PhenoTips instance.
 *
 * @param serverConfiguration the XObject holding the remote server configuration
 * @return the configured URL, in the format {@code http://remote.host.name/bin/}, or {@code null} if the
 *         configuration isn't valid//from w ww. j  a v a2s.co  m
 */
private String getBaseURL(BaseObject serverConfiguration) {
    if (serverConfiguration != null) {
        String result = serverConfiguration.getStringValue("url");
        if (StringUtils.isBlank(result)) {
            return null;
        }

        if (!result.startsWith("http")) {
            result = "http://" + result;
        }
        return StringUtils.stripEnd(result, "/") + "/bin/data/sync";
    }
    return null;
}

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 .ja v  a  2s .co  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  .j a v a 2s  .  com

        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();
        }//  w w w .  ja  va2s .c om

        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.rest.resource.ViewFilterResource.java

@Override
public String getResourceSignature() {

    StringBuilder signature = new StringBuilder();
    String signaturePart = wrappedResource.getResourceSignature();

    if (signaturePart.contains("/")) {

        String[] parts = StringUtils.split(signaturePart, "/");
        Matcher matcher = uuidPattern.matcher("");

        for (String subPart : parts) {

            // re-use pattern matcher for better performance
            matcher.reset(subPart);//from  w  w  w  .  java 2s.c  o m

            if (!matcher.matches()) {

                signature.append(subPart);
                signature.append("/");

            }

        }

    } else {

        signature.append(signaturePart);

    }

    if (propertyView != null) {

        // append view / scope part
        if (!signature.toString().endsWith("/")) {
            signature.append("/");
        }

        signature.append("_");
        signature.append(SchemaHelper.normalizeEntityName(propertyView));
    }

    return StringUtils.stripEnd(signature.toString(), "/");
}

From source file:org.structr.rest.service.HttpService.java

@Override
public void initialize(final Services services, final StructrConf additionalConfig)
        throws ClassNotFoundException, IllegalAccessException, InstantiationException {

    final StructrConf finalConfig = new StructrConf();

    // Default configuration
    finalConfig.setProperty(APPLICATION_TITLE, "structr server");
    finalConfig.setProperty(APPLICATION_HOST, "0.0.0.0");
    finalConfig.setProperty(APPLICATION_HTTP_PORT, "8082");
    finalConfig.setProperty(APPLICATION_HTTPS_ENABLED, "false");
    finalConfig.setProperty(APPLICATION_HTTPS_PORT, "8083");
    finalConfig.setProperty(ASYNC, "true");
    finalConfig.setProperty(SERVLETS, "JsonRestServlet");

    finalConfig.setProperty("JsonRestServlet.class", JsonRestServlet.class.getName());
    finalConfig.setProperty("JsonRestServlet.path", "/structr/rest/*");
    finalConfig.setProperty("JsonRestServlet.resourceprovider", DefaultResourceProvider.class.getName());
    finalConfig.setProperty("JsonRestServlet.authenticator", SuperUserAuthenticator.class.getName());
    finalConfig.setProperty("JsonRestServlet.user.class", "org.structr.dynamic.User");
    finalConfig.setProperty("JsonRestServlet.user.autocreate", "false");
    finalConfig.setProperty("JsonRestServlet.defaultview", PropertyView.Public);
    finalConfig.setProperty("JsonRestServlet.outputdepth", "3");

    Services.mergeConfiguration(finalConfig, additionalConfig);

    final String mainClassName = (String) finalConfig.get(MAIN_CLASS);

    Class mainClass = null;//from w ww  . j  ava 2  s .  c  o m
    if (mainClassName != null) {

        logger.log(Level.INFO, "Running main class {0}", new Object[] { mainClassName });

        try {
            mainClass = Class.forName(mainClassName);
        } catch (ClassNotFoundException ex) {
            logger.log(Level.WARNING, "Did not find class for main class from config " + mainClassName, ex);
        }

    }

    String sourceJarName = (mainClass != null ? mainClass : getClass()).getProtectionDomain().getCodeSource()
            .getLocation().toString();
    final boolean isTest = Boolean.parseBoolean(finalConfig.getProperty(Services.TESTING, "false"));

    if (!isTest
            && StringUtils.stripEnd(sourceJarName, System.getProperty("file.separator")).endsWith("classes")) {

        String jarFile = System.getProperty("jarFile");
        if (StringUtils.isEmpty(jarFile)) {
            throw new IllegalArgumentException(getClass().getName()
                    + " was started in an environment where the classloader cannot determine the JAR file containing the main class.\n"
                    + "Please specify the path to the JAR file in the parameter -DjarFile.\n"
                    + "Example: -DjarFile=${project.build.directory}/${project.artifactId}-${project.version}.jar");
        }
        sourceJarName = jarFile;
    }

    // load configuration from properties file
    applicationName = finalConfig.getProperty(APPLICATION_TITLE);
    host = finalConfig.getProperty(APPLICATION_HOST);
    basePath = finalConfig.getProperty(Services.BASE_PATH);
    httpPort = Services.parseInt(finalConfig.getProperty(APPLICATION_HTTP_PORT), 8082);
    maxIdleTime = Services.parseInt(System.getProperty("maxIdleTime"), 30000);
    requestHeaderSize = Services.parseInt(System.getProperty("requestHeaderSize"), 8192);
    async = Services.parseBoolean(finalConfig.getProperty(ASYNC), true);

    if (async) {
        logger.log(Level.INFO, "Running in asynchronous mode");
    }

    // other properties
    final String keyStorePath = finalConfig.getProperty(APPLICATION_KEYSTORE_PATH);
    final String keyStorePassword = finalConfig.getProperty(APPLICATION_KEYSTORE_PASSWORD);
    final String contextPath = System.getProperty("contextPath", "/");
    final String logPrefix = "structr";
    final boolean enableRewriteFilter = true; // configurationFile.getProperty(Services.
    final boolean enableHttps = Services.parseBoolean(finalConfig.getProperty(APPLICATION_HTTPS_ENABLED),
            false);
    final boolean enableGzipCompression = true; //
    final boolean logRequests = false; //
    final int httpsPort = Services.parseInt(finalConfig.getProperty(APPLICATION_HTTPS_PORT), 8083);

    // get current base path
    basePath = System.getProperty("home", basePath);
    if (basePath.isEmpty()) {

        // use cwd and, if that fails, /tmp as a fallback
        basePath = System.getProperty("user.dir", "/tmp");
    }

    // create base directory if it does not exist
    final File baseDir = new File(basePath);
    if (!baseDir.exists()) {
        baseDir.mkdirs();
    }

    server = new Server(httpPort);
    final ContextHandlerCollection contexts = new ContextHandlerCollection();

    contexts.addHandler(new DefaultHandler());

    final ServletContextHandler servletContext = new ServletContextHandler(server, contextPath, true, true);
    final List<Connector> connectors = new LinkedList<>();

    // create resource collection from base path & source JAR
    try {
        servletContext.setBaseResource(new ResourceCollection(Resource.newResource(basePath),
                JarResource.newJarResource(Resource.newResource(sourceJarName))));

    } catch (Throwable t) {

        logger.log(Level.WARNING, "Base resource {0} not usable: {1}",
                new Object[] { basePath, t.getMessage() });
    }

    // this is needed for the filters to work on the root context "/"
    servletContext.addServlet("org.eclipse.jetty.servlet.DefaultServlet", "/");
    servletContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");

    try {

        // CMIS setup
        servletContext.addEventListener(new CmisRepositoryContextListener());

        final ServletHolder cmisAtomHolder = servletContext.addServlet(CmisAtomPubServlet.class.getName(),
                "/structr/cmis/atom/*");
        cmisAtomHolder.setInitParameter("callContextHandler", BasicAuthCallContextHandler.class.getName());
        cmisAtomHolder.setInitParameter("cmisVersion", "1.1");

        final ServletHolder cmisBrowserHolder = servletContext
                .addServlet(CmisBrowserBindingServlet.class.getName(), "/structr/cmis/browser/*");
        cmisBrowserHolder.setInitParameter("callContextHandler", BasicAuthCallContextHandler.class.getName());
        cmisBrowserHolder.setInitParameter("cmisVersion", "1.1");

    } catch (Throwable t) {
        t.printStackTrace();
    }

    hashSessionManager = new HashSessionManager();
    try {
        hashSessionManager.setStoreDirectory(new File(baseDir + "/sessions"));
    } catch (IOException ex) {
        logger.log(Level.WARNING,
                "Could not set custom session manager with session store directory {0}/sessions", baseDir);
    }

    servletContext.getSessionHandler().setSessionManager(hashSessionManager);

    if (enableRewriteFilter) {

        final FilterHolder rewriteFilter = new FilterHolder(UrlRewriteFilter.class);
        rewriteFilter.setInitParameter("confPath", "urlrewrite.xml");
        servletContext.addFilter(rewriteFilter, "/*",
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC));
    }

    if (enableGzipCompression) {

        final FilterHolder gzipFilter = async ? new FilterHolder(AsyncGzipFilter.class)
                : new FilterHolder(GzipFilter.class);
        gzipFilter.setInitParameter("mimeTypes",
                "text/html,text/plain,text/css,text/javascript,application/json");
        gzipFilter.setInitParameter("bufferSize", "32768");
        gzipFilter.setInitParameter("minGzipSize", "256");
        gzipFilter.setInitParameter("deflateCompressionLevel", "9");
        gzipFilter.setInitParameter("methods", "GET,POST,PUT,HEAD,DELETE");
        servletContext.addFilter(gzipFilter, "/*",
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC));

    }

    contexts.addHandler(servletContext);

    // enable request logging
    if (logRequests || "true".equals(finalConfig.getProperty("log.requests", "false"))) {

        final String etcPath = basePath + "/etc";
        final File etcDir = new File(etcPath);

        if (!etcDir.exists()) {

            etcDir.mkdir();
        }

        final String logbackConfFilePath = basePath + "/etc/logback-access.xml";
        final File logbackConfFile = new File(logbackConfFilePath);

        if (!logbackConfFile.exists()) {

            // synthesize a logback accees log config file
            List<String> config = new LinkedList<>();

            config.add("<configuration>");
            config.add("  <appender name=\"FILE\" class=\"ch.qos.logback.core.rolling.RollingFileAppender\">");
            config.add("    <rollingPolicy class=\"ch.qos.logback.core.rolling.TimeBasedRollingPolicy\">");
            config.add("      <fileNamePattern>logs/" + logPrefix
                    + "-%d{yyyy_MM_dd}.request.log.zip</fileNamePattern>");
            config.add("    </rollingPolicy>");
            config.add("    <encoder>");
            config.add("      <charset>UTF-8</charset>");
            config.add("      <pattern>%h %l %u %t \"%r\" %s %b %n%fullRequest%n%n%fullResponse</pattern>");
            config.add("    </encoder>");
            config.add("  </appender>");
            config.add("  <appender-ref ref=\"FILE\" />");
            config.add("</configuration>");

            try {
                logbackConfFile.createNewFile();
                FileUtils.writeLines(logbackConfFile, "UTF-8", config);

            } catch (IOException ioex) {

                logger.log(Level.WARNING, "Unable to write logback configuration.", ioex);
            }
        }

        final FilterHolder loggingFilter = new FilterHolder(TeeFilter.class);
        servletContext.addFilter(loggingFilter, "/*",
                EnumSet.of(DispatcherType.REQUEST, async ? DispatcherType.ASYNC : DispatcherType.FORWARD));
        loggingFilter.setInitParameter("includes", "");

        final RequestLogHandler requestLogHandler = new RequestLogHandler();
        final String logPath = basePath + "/logs";
        final File logDir = new File(logPath);

        // Create logs directory if not existing
        if (!logDir.exists()) {

            logDir.mkdir();

        }

        final RequestLogImpl requestLog = new RequestLogImpl();
        requestLog.setName("REQUESTLOG");
        requestLogHandler.setRequestLog(requestLog);

        final HandlerCollection handlers = new HandlerCollection();

        handlers.setHandlers(new Handler[] { contexts, requestLogHandler });

        server.setHandler(handlers);

    } else {

        server.setHandler(contexts);

    }

    final List<ContextHandler> resourceHandler = collectResourceHandlers(finalConfig);
    for (ContextHandler contextHandler : resourceHandler) {
        contexts.addHandler(contextHandler);
    }

    final Map<String, ServletHolder> servlets = collectServlets(finalConfig);

    // add servlet elements
    int position = 1;
    for (Map.Entry<String, ServletHolder> servlet : servlets.entrySet()) {

        final ServletHolder servletHolder = servlet.getValue();
        final String path = servlet.getKey();

        servletHolder.setInitOrder(position++);

        logger.log(Level.INFO, "Adding servlet {0} for {1}", new Object[] { servletHolder, path });

        servletContext.addServlet(servletHolder, path);
    }

    contexts.addHandler(servletContext);

    if (host != null && !host.isEmpty() && httpPort > -1) {

        httpConfig = new HttpConfiguration();
        httpConfig.setSecureScheme("https");
        httpConfig.setSecurePort(httpsPort);
        //httpConfig.setOutputBufferSize(8192);
        httpConfig.setRequestHeaderSize(requestHeaderSize);

        final ServerConnector httpConnector = new ServerConnector(server,
                new HttpConnectionFactory(httpConfig));

        httpConnector.setHost(host);
        httpConnector.setPort(httpPort);

        connectors.add(httpConnector);

    } else {

        logger.log(Level.WARNING,
                "Unable to configure HTTP server port, please make sure that {0} and {1} are set correctly in structr.conf.",
                new Object[] { APPLICATION_HOST, APPLICATION_HTTP_PORT });
    }

    if (enableHttps) {

        if (httpsPort > -1 && keyStorePath != null && !keyStorePath.isEmpty() && keyStorePassword != null) {

            httpsConfig = new HttpConfiguration(httpConfig);
            httpsConfig.addCustomizer(new SecureRequestCustomizer());

            final SslContextFactory sslContextFactory = new SslContextFactory();
            sslContextFactory.setKeyStorePath(keyStorePath);
            sslContextFactory.setKeyStorePassword(keyStorePassword);

            final ServerConnector https = new ServerConnector(server,
                    new SslConnectionFactory(sslContextFactory, "http/1.1"),
                    new HttpConnectionFactory(httpsConfig));

            https.setPort(httpsPort);
            https.setIdleTimeout(500000);

            https.setHost(host);
            https.setPort(httpsPort);

            connectors.add(https);

        } else {

            logger.log(Level.WARNING,
                    "Unable to configure SSL, please make sure that {0}, {1} and {2} are set correctly in structr.conf.",
                    new Object[] { APPLICATION_HTTPS_PORT, APPLICATION_KEYSTORE_PATH,
                            APPLICATION_KEYSTORE_PASSWORD });
        }
    }

    if (!connectors.isEmpty()) {

        server.setConnectors(connectors.toArray(new Connector[0]));

    } else {

        logger.log(Level.SEVERE, "No connectors configured, aborting.");
        System.exit(0);
    }

    server.setStopTimeout(1000);
    server.setStopAtShutdown(true);
}

From source file:org.structr.rest.service.HttpService.java

private void removeDir(final String basePath, final String directoryName) {

    final String strippedBasePath = StringUtils.stripEnd(basePath, "/");
    final File file = new File(strippedBasePath + "/" + directoryName);

    if (file.isDirectory()) {

        try {//from w  ww. j  av  a2s  .c om

            FileUtils.deleteDirectory(file);

        } catch (IOException ex) {

            logger.log(Level.SEVERE, "Unable to delete directory {0}: {1}",
                    new Object[] { directoryName, ex.getMessage() });
        }

    } else {

        file.delete();
    }
}

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;

    }//from w w w .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.entity.Image.java

/**
 * @return the name of the original image
 *//*from  w w w . j a v  a 2s .  co  m*/
public static String getOriginalImageName(final Image thisImage) {

    final Integer tnWidth = thisImage.getWidth();
    final Integer tnHeight = thisImage.getHeight();

    return StringUtils.stripEnd(thisImage.getName(), "_thumb_" + tnWidth + "x" + tnHeight);
}

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());
    }//  w w  w.j a v  a 2s.  c  o m

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

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