Example usage for org.springframework.util StringUtils cleanPath

List of usage examples for org.springframework.util StringUtils cleanPath

Introduction

In this page you can find the example usage for org.springframework.util StringUtils cleanPath.

Prototype

public static String cleanPath(String path) 

Source Link

Document

Normalize the path by suppressing sequences like "path/.."

Usage

From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java

private CloseableHttpResponse forward(CloseableHttpClient httpclient, String verb, String uri,
        HttpServletRequest request, MultiValueMap<String, String> headers, MultiValueMap<String, String> params,
        InputStream requestEntity) throws Exception {
    Map<String, Object> info = this.helper.debug(verb, uri, headers, params, requestEntity);
    URL host = RequestContext.getCurrentContext().getRouteHost();
    HttpHost httpHost = getHttpHost(host);
    uri = StringUtils.cleanPath((host.getPath() + uri).replaceAll("/{2,}", "/"));
    HttpRequest httpRequest;/*  ww  w .j  av  a  2  s . c  o  m*/
    int contentLength = request.getContentLength();
    InputStreamEntity entity = new InputStreamEntity(requestEntity, contentLength,
            request.getContentType() != null ? ContentType.create(request.getContentType()) : null);
    switch (verb.toUpperCase()) {
    case "POST":
        HttpPost httpPost = new HttpPost(uri + this.helper.getQueryString(params));
        httpRequest = httpPost;
        httpPost.setEntity(entity);
        break;
    case "PUT":
        HttpPut httpPut = new HttpPut(uri + this.helper.getQueryString(params));
        httpRequest = httpPut;
        httpPut.setEntity(entity);
        break;
    case "PATCH":
        HttpPatch httpPatch = new HttpPatch(uri + this.helper.getQueryString(params));
        httpRequest = httpPatch;
        httpPatch.setEntity(entity);
        break;
    default:
        httpRequest = new BasicHttpRequest(verb, uri + this.helper.getQueryString(params));
        log.debug(uri + this.helper.getQueryString(params));
    }
    try {
        httpRequest.setHeaders(convertHeaders(headers));
        log.debug(httpHost.getHostName() + " " + httpHost.getPort() + " " + httpHost.getSchemeName());
        CloseableHttpResponse zuulResponse = forwardRequest(httpclient, httpHost, httpRequest);
        RequestContext.getCurrentContext().set("zuulResponse", zuulResponse);
        this.helper.appendDebug(info, zuulResponse.getStatusLine().getStatusCode(),
                revertHeaders(zuulResponse.getAllHeaders()));
        return zuulResponse;
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        // httpclient.getConnectionManager().shutdown();
    }
}

From source file:spring.osgi.io.OsgiBundleResource.java

/**
 * Used internally to get all the URLs matching a certain location. The
 * method is required to extract the folder from the given location as well
 * the file.//from   w w w .  ja  va  2  s . c  o  m
 *
 * @param location location to look for
 * @return an array of URLs
 * @throws java.io.IOException
 */
ContextResource[] getAllUrlsFromBundleSpace(String location) throws IOException {
    if (bundle == null)
        throw new IllegalArgumentException(
                "cannot locate items in bundle-space w/o a bundle; specify one when creating this resolver");

    Assert.notNull(location);
    Set<ContextResource> resources = new LinkedHashSet<>(5);

    location = StringUtils.cleanPath(location);
    location = OsgiResourceUtils.stripPrefix(location);

    if (!StringUtils.hasText(location))
        location = OsgiResourceUtils.FOLDER_DELIMITER;

    // the root folder is requested (special case)
    if (OsgiResourceUtils.FOLDER_DELIMITER.equals(location)) {
        // there is no way to determine the URL to the root directly
        // through findEntries so we'll have to use another way

        // getEntry can't be used since it doesn't consider fragments
        // so we have to rely on findEntries

        // we could ask for a known entry (such as META-INF)
        // but not all jars have a dedicated entry for it
        // so we'll just ask for whatever is present in the root
        Enumeration candidates = bundle.findEntries("/", null, false);

        // since there can be multiple root paths (when fragments are present)
        // iterate on all candidates
        while (candidates != null && candidates.hasMoreElements()) {

            URL url = (URL) candidates.nextElement();

            // determined the root path
            // we'll have to parse the string since some implementations
            // do not normalize the resulting URL resulting in mismatches
            String rootPath = OsgiResourceUtils.findUpperFolder(url.toExternalForm());
            resources.add(new UrlContextResource(rootPath));
        }
    } else {
        // remove leading and trailing / if any
        if (location.startsWith(OsgiResourceUtils.FOLDER_DELIMITER))
            location = location.substring(1);

        if (location.endsWith(OsgiResourceUtils.FOLDER_DELIMITER))
            location = location.substring(0, location.length() - 1);

        // do we have at least on folder or is this just a file
        boolean hasFolder = (location.contains(OsgiResourceUtils.FOLDER_DELIMITER));

        String path = (hasFolder ? location : OsgiResourceUtils.FOLDER_DELIMITER);
        String file = (hasFolder ? null : location);

        // find the file and path
        int separatorIndex = location.lastIndexOf(OsgiResourceUtils.FOLDER_DELIMITER);

        if (separatorIndex > -1 && separatorIndex + 1 < location.length()) {
            // update the path
            path = location.substring(0, separatorIndex);

            // determine file (if there is any)
            if (separatorIndex + 1 < location.length())
                file = location.substring(separatorIndex + 1);
        }

        Enumeration candidates = bundle.findEntries(path, file, false);
        // add the leading / to be consistent
        String contextPath = OsgiResourceUtils.FOLDER_DELIMITER + location;

        while (candidates != null && candidates.hasMoreElements()) {
            resources.add(new UrlContextResource((URL) candidates.nextElement(), contextPath));
        }
    }

    return resources.toArray(new ContextResource[resources.size()]);
}

From source file:com.wavemaker.tools.project.LocalStudioFileSystem.java

@Override
public String getPath(Resource resource) {
    try {//from   w ww.j av a 2 s . c om
        String path = StringUtils.cleanPath(resource.getFile().getPath());
        if (resource.getFile().isDirectory() && !path.endsWith("/")) {
            path += "/";
        }
        return path;
    } catch (IOException ex) {
        throw new WMRuntimeException(ex);
    }
}

From source file:org.springframework.amqp.rabbit.admin.RabbitBrokerAdmin.java

@ManagedOperation
public void startNode() {

    RabbitStatus status = getStatus();//from   www  .  j  a va 2 s.  c o  m
    if (status.isAlive()) {
        logger.info("Rabbit Process already running.");
        startBrokerApplication();
        return;
    }

    if (!status.isRunning() && status.isReady()) {
        logger.info("Rabbit Process not running but status is ready.  Restarting.");
        stopNode();
    }

    logger.info("Starting RabbitMQ node by shelling out command line.");
    final Execute execute = new Execute();

    String rabbitStartScript = null;
    String hint = "";
    if (Os.isFamily("windows") || Os.isFamily("dos")) {
        rabbitStartScript = "sbin/rabbitmq-server.bat";
    } else if (Os.isFamily("unix") || Os.isFamily("mac")) {
        rabbitStartScript = "bin/rabbitmq-server";
        hint = "Depending on your platform it might help to set RABBITMQ_LOG_BASE and RABBITMQ_MNESIA_BASE System properties to an empty directory.";
    }
    Assert.notNull(rabbitStartScript, "unsupported OS family");

    String rabbitHome = System.getProperty("RABBITMQ_HOME", System.getenv("RABBITMQ_HOME"));
    if (rabbitHome == null) {
        if (Os.isFamily("windows") || Os.isFamily("dos")) {
            rabbitHome = findDirectoryName("c:/Program Files", "rabbitmq");
        } else if (Os.isFamily("unix") || Os.isFamily("mac")) {
            rabbitHome = "/usr/lib/rabbitmq";
        }
    }
    Assert.notNull(rabbitHome, "RABBITMQ_HOME system property (or environment variable) not set.");

    rabbitHome = StringUtils.cleanPath(rabbitHome);
    String rabbitStartCommand = rabbitHome + "/" + rabbitStartScript;
    String[] commandline = new String[] { rabbitStartCommand };

    List<String> env = new ArrayList<String>();

    if (rabbitLogBaseDirectory != null) {
        env.add("RABBITMQ_LOG_BASE=" + rabbitLogBaseDirectory);
    } else {
        addEnvironment(env, "RABBITMQ_LOG_BASE");
    }
    if (rabbitMnesiaBaseDirectory != null) {
        env.add("RABBITMQ_MNESIA_BASE=" + rabbitMnesiaBaseDirectory);
    } else {
        addEnvironment(env, "RABBITMQ_MNESIA_BASE");
    }
    addEnvironment(env, "ERLANG_HOME");

    // Make the nodename explicitly the same so the erl process knows who we are
    env.add("RABBITMQ_NODENAME=" + nodeName);

    // Set the port number for the new process
    env.add("RABBITMQ_NODE_PORT=" + port);

    // Ask for a detached erl process so stdout doesn't get diverted to a black hole when the JVM dies (without this
    // you can start the Rabbit broker form Java but if you forget to stop it, the erl process is hosed).
    env.add("RABBITMQ_SERVER_ERL_ARGS=-detached");

    execute.setCommandline(commandline);
    execute.setEnvironment(env.toArray(new String[0]));

    final CountDownLatch running = new CountDownLatch(1);
    final AtomicBoolean finished = new AtomicBoolean(false);
    final String errorHint = hint;

    executor.execute(new Runnable() {
        public void run() {
            try {
                running.countDown();
                int exit = execute.execute();
                finished.set(true);
                logger.info("Finished broker launcher process with exit code=" + exit);
                if (exit != 0) {
                    throw new IllegalStateException("Could not start process." + errorHint);
                }
            } catch (Exception e) {
                logger.error("Failed to start node", e);
            }
        }
    });

    try {
        logger.info("Waiting for Rabbit process to be started");
        Assert.state(running.await(1000L, TimeUnit.MILLISECONDS),
                "Timed out waiting for thread to start Rabbit process.");
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }

    if (finished.get()) {
        // throw new
        // IllegalStateException("Expected broker process to start in background, but it has exited early.");
    }

    if (timeout > 0) {
        waitForReadyState();
    }

}

From source file:org.springframework.cloud.config.monitor.PropertyPathEndpoint.java

private Set<String> guessServiceName(String path) {
    Set<String> services = new LinkedHashSet<>();
    if (path != null) {
        String stem = StringUtils.stripFilenameExtension(StringUtils.getFilename(StringUtils.cleanPath(path)));
        // TODO: correlate with service registry
        int index = stem.indexOf("-");
        while (index >= 0) {
            String name = stem.substring(0, index);
            String profile = stem.substring(index + 1);
            if ("application".equals(name)) {
                services.add("*:" + profile);
            } else if (!name.startsWith("application")) {
                services.add(name + ":" + profile);
            }//w  w w  . j  av a  2s.co m
            index = stem.indexOf("-", index + 1);
        }
        String name = stem;
        if ("application".equals(name)) {
            services.add("*");
        } else if (!name.startsWith("application")) {
            services.add(name);
        }
    }
    return services;
}

From source file:org.springframework.cloud.config.server.AbstractSCMEnvironmentRepository.java

protected File getWorkingDirectory() {
    if (uri.startsWith("file:")) {
        try {/*  w  ww .  j  av a  2  s  .co  m*/
            return new UrlResource(StringUtils.cleanPath(uri)).getFile();
        } catch (Exception e) {
            throw new IllegalStateException("Cannot convert uri to file: " + uri);
        }
    }
    return basedir;
}

From source file:org.springframework.cloud.config.server.environment.NativeEnvironmentRepository.java

protected Environment clean(Environment value) {
    Environment result = new Environment(value.getName(), value.getProfiles(), value.getLabel(), this.version,
            value.getState());/*from  w  w w. ja  va  2 s.  c  o  m*/
    for (PropertySource source : value.getPropertySources()) {
        String name = source.getName();
        if (this.environment.getPropertySources().contains(name)) {
            continue;
        }
        name = name.replace("applicationConfig: [", "");
        name = name.replace("]", "");
        if (this.searchLocations != null) {
            boolean matches = false;
            String normal = name;
            if (normal.startsWith("file:")) {
                normal = StringUtils.cleanPath(new File(normal.substring("file:".length())).getAbsolutePath());
            }
            String profile = result.getProfiles() == null ? null
                    : StringUtils.arrayToCommaDelimitedString(result.getProfiles());
            for (String pattern : getLocations(result.getName(), profile, result.getLabel()).getLocations()) {
                if (!pattern.contains(":")) {
                    pattern = "file:" + pattern;
                }
                if (pattern.startsWith("file:")) {
                    pattern = StringUtils
                            .cleanPath(new File(pattern.substring("file:".length())).getAbsolutePath()) + "/";
                }
                if (logger.isTraceEnabled()) {
                    logger.trace("Testing pattern: " + pattern + " with property source: " + name);
                }
                if (normal.startsWith(pattern) && !normal.substring(pattern.length()).contains("/")) {
                    matches = true;
                    break;
                }
            }
            if (!matches) {
                // Don't include this one: it wasn't matched by our search locations
                if (logger.isDebugEnabled()) {
                    logger.debug("Not adding property source: " + name);
                }
                continue;
            }
        }
        logger.info("Adding property source: " + name);
        result.add(new PropertySource(name, source.getSource()));
    }
    return result;
}

From source file:org.springframework.cloud.config.server.environment.SvnKitEnvironmentRepository.java

private String[] getPaths(String application, String profile, String label) {
    String[] locations = getSearchLocations(getSvnPath(getWorkingDirectory(), label), application, profile,
            label);//from  ww w .j av a2  s  .  c om
    boolean exists = false;
    for (String location : locations) {
        location = StringUtils.cleanPath(location);
        URI locationUri = URI.create(location);
        if (new File(locationUri).exists()) {
            exists = true;
            break;
        }
    }
    if (!exists) {
        throw new NoSuchLabelException("No label found for: " + label);
    }
    return locations;
}

From source file:org.springframework.cloud.config.server.environment.SvnKitEnvironmentRepository.java

private void resolveRelativeFileUri() {
    if (getUri().startsWith("file:///./")) {
        String path = getUri().substring(8);
        String absolutePath = new File(path).getAbsolutePath();
        setUri("file:///" + StringUtils.cleanPath(absolutePath));
    }//from w  w  w.ja  va  2  s . co m

}

From source file:org.springframework.cloud.config.server.NativeEnvironmentRepository.java

protected Environment clean(Environment value) {
    Environment result = new Environment(value.getName(), value.getProfiles(), value.getLabel());
    for (PropertySource source : value.getPropertySources()) {
        String name = source.getName();
        if (environment.getPropertySources().contains(name)) {
            continue;
        }//from   ww  w .ja v a 2 s.  c o m
        name = name.replace("applicationConfig: [", "");
        name = name.replace("]", "");
        if (searchLocations != null) {
            boolean matches = false;
            String normal = name;
            if (normal.startsWith("file:")) {
                normal = StringUtils.cleanPath(new File(normal.substring("file:".length())).getAbsolutePath());
            }
            for (String pattern : StringUtils
                    .commaDelimitedListToStringArray(getLocations(searchLocations, result.getLabel()))) {
                if (!pattern.contains(":")) {
                    pattern = "file:" + pattern;
                }
                if (pattern.startsWith("file:")) {
                    pattern = StringUtils
                            .cleanPath(new File(pattern.substring("file:".length())).getAbsolutePath()) + "/";
                }
                if (logger.isTraceEnabled()) {
                    logger.trace("Testing pattern: " + pattern + " with property source: " + name);
                }
                if (normal.startsWith(pattern) && !normal.substring(pattern.length()).contains("/")) {
                    matches = true;
                    break;
                }
            }
            if (!matches) {
                // Don't include this one: it wasn't matched by our search locations
                if (logger.isDebugEnabled()) {
                    logger.debug("Not adding property source: " + name);
                }
                continue;
            }
        }
        logger.info("Adding property source: " + name);
        result.add(new PropertySource(name, source.getSource()));
    }
    return result;
}