Example usage for java.net URL getPath

List of usage examples for java.net URL getPath

Introduction

In this page you can find the example usage for java.net URL getPath.

Prototype

public String getPath() 

Source Link

Document

Gets the path part of this URL .

Usage

From source file:ResourceUtils.java

/**
 * Determine whether the given URL points to a resource in a jar file,
 * that is, has protocol "jar", "zip", "wsjar" or "code-source".
 * <p>"zip" and "wsjar" are used by BEA WebLogic Server and IBM WebSphere, respectively,
 * but can be treated like jar files. The same applies to "code-source" URLs on Oracle
 * OC4J, provided that the path contains a jar separator.
 * @param url the URL to check/* w  ww  .  j  a  v  a  2 s. c  o m*/
 * @return whether the URL has been identified as a JAR URL
 */
public static boolean isJarURL(URL url) {
    String protocol = url.getProtocol();
    return (URL_PROTOCOL_JAR.equals(protocol) || URL_PROTOCOL_ZIP.equals(protocol)
            || URL_PROTOCOL_WSJAR.equals(protocol)
            || (URL_PROTOCOL_CODE_SOURCE.equals(protocol) && url.getPath().indexOf(JAR_URL_SEPARATOR) != -1));
}

From source file:com.redhat.rcm.version.testutil.TestProjectFixture.java

public static File getResourceFile(final String path) {
    final URL resource = Thread.currentThread().getContextClassLoader().getResource(path);
    if (resource == null) {
        fail("Resource not found: " + path);
    }//from   w  w w  .ja va2s  . c  o m

    return new File(resource.getPath());
}

From source file:be.i8c.sag.util.FileUtils.java

/**
 * Get the File that represents the location of this jar that contains the clazz.
 *
 * Note: The file may be a directory when you are running this
 * code from your IDE or without packing it into a jar.
 *
 * @param clazz A class that is located in the jar file.
 * @return A File that represents the location of the jar that contains the clazz.
 *//*w w  w.  ja v a  2 s .co m*/
public static File getJarFile(Class<?> clazz) {
    String className = clazz.getSimpleName() + ".class";
    String classPath = "/" + clazz.getName().replace('.', '/') + ".class";

    URL generatorFileUrl = clazz.getResource(className);

    // We want to remove the last instance of the internal class path
    String jarPath = new StringBuilder(new StringBuilder(generatorFileUrl.getPath()).reverse().toString()
            .replaceFirst(new StringBuilder(classPath).reverse().toString(), "")).reverse().toString();

    // Remove the file:/ and the '!' at the end of the path.
    // This only needs to be done if it's a file
    jarPath = jarPath.replaceAll("^file:/", "");
    jarPath = jarPath.replaceAll("!$", "");

    return new File(jarPath);
}

From source file:org.dataconservancy.dcs.integration.main.ContainerStartIT.java

@BeforeClass
public static void loadProperties() throws IOException {
    final URL defaultProps = ContainerStartIT.class.getResource("/default.properties");
    assertNotNull("Could not resolve /default.properties from the classpath.", defaultProps);
    assertTrue("default.properties does not exist.", new File(defaultProps.getPath()).exists());
    props.load(defaultProps.openStream());
}

From source file:org.dataconservancy.dcs.integration.main.IngestTest.java

@BeforeClass
public static void init() throws IOException {
    /* ClassPathXmlApplicationContext appContext =
        new ClassPathXmlApplicationContext(new String[] {
                "depositClientContext.xml", "classpath*:org/dataconservancy/config/applicationContext.xml"});*/

    client = new DefaultHttpClient();//(DefaultHttpClient) appContext.getBean("httpClient");

    final URL defaultProps = IngestTest.class.getResource("/default.properties");
    assertNotNull("Could not resolve /default.properties from the classpath.", defaultProps);
    assertTrue("default.properties does not exist.", new File(defaultProps.getPath()).exists());
    props.load(defaultProps.openStream());
}

From source file:org.hawkular.apm.api.services.ConfigurationLoader.java

/**
 * This method loads the configuration from the supplied URI.
 *
 * @param uri The URI/*from ww w. j a  va  2  s. co m*/
 * @param type The type, or null if default (jvm)
 * @return The configuration
 */
protected static CollectorConfiguration loadConfig(String uri, String type) {
    final CollectorConfiguration config = new CollectorConfiguration();

    if (type == null) {
        type = DEFAULT_TYPE;
    }

    uri += java.io.File.separator + type;

    File f = new File(uri);

    if (!f.isAbsolute()) {
        if (f.exists()) {
            uri = f.getAbsolutePath();
        } else if (System.getProperties().containsKey("jboss.server.config.dir")) {
            uri = System.getProperty("jboss.server.config.dir") + java.io.File.separatorChar + uri;
        } else {
            try {
                URL url = Thread.currentThread().getContextClassLoader().getResource(uri);
                if (url != null) {
                    uri = url.getPath();
                } else {
                    log.severe("Failed to get absolute path for uri '" + uri + "'");
                }
            } catch (Exception e) {
                log.log(Level.SEVERE, "Failed to get absolute path for uri '" + uri + "'", e);
                uri = null;
            }
        }
    }

    if (uri != null) {
        String[] uriParts = uri.split(Matcher.quoteReplacement(File.separator));
        int startIndex = 0;

        // Remove any file prefix
        if (uriParts[0].equals("file:")) {
            startIndex++;
        }

        try {
            Path path = getPath(startIndex, uriParts);

            Files.walkFileTree(path, new FileVisitor<Path>() {

                @Override
                public FileVisitResult postVisitDirectory(Path path, IOException exc) throws IOException {
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attrs)
                        throws IOException {
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                    if (path.toString().endsWith(".json")) {
                        String json = new String(Files.readAllBytes(path));
                        CollectorConfiguration childConfig = mapper.readValue(json,
                                CollectorConfiguration.class);
                        if (childConfig != null) {
                            config.merge(childConfig, false);
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path path, IOException exc) throws IOException {
                    return FileVisitResult.CONTINUE;
                }

            });
        } catch (Throwable e) {
            log.log(Level.SEVERE, "Failed to load configuration", e);
        }
    }

    return config;
}

From source file:org.jboss.as.test.integration.web.security.WebSecurityCERTTestCase.java

public static void createSecurityDomains(final ModelControllerClient client) throws Exception {
    final List<ModelNode> updates = new ArrayList<ModelNode>();
    ModelNode op = new ModelNode();
    op.get(OP).set(ADD);//from www.  j a v a2s  .c  om
    op.get(OP_ADDR).add(SUBSYSTEM, "security");
    op.get(OP_ADDR).add(SECURITY_DOMAIN, "cert-test");
    ModelNode loginModule = op.get(AUTHENTICATION).add();
    loginModule.get(CODE).set("CertificateRoles");
    loginModule.get(FLAG).set("required");
    ModelNode moduleOptions = loginModule.get(MODULE_OPTIONS);
    moduleOptions.add("securityDomain", "cert");
    updates.add(op);

    op = new ModelNode();
    op.get(OP).set(ADD);
    op.get(OP_ADDR).add(SUBSYSTEM, "security");
    op.get(OP_ADDR).add(SECURITY_DOMAIN, "cert");
    ModelNode jsse = op.get(JSSE);
    jsse.get(TRUSTSTORE_PASSWORD).set("changeit");
    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    URL keystore = tccl.getResource("security/jsse.keystore");
    jsse.get(TRUSTSTORE_URL).set(keystore.getPath());
    updates.add(op);

    applyUpdates(updates, client);
}

From source file:com.mashape.unirest.android.http.HttpClientHelper.java

private static HttpRequestBase prepareRequest(HttpRequest request, boolean async) {

    Object defaultHeaders = Options.getOption(Option.DEFAULT_HEADERS);
    if (defaultHeaders != null) {
        @SuppressWarnings("unchecked")
        Set<Entry<String, String>> entrySet = ((Map<String, String>) defaultHeaders).entrySet();
        for (Entry<String, String> entry : entrySet) {
            request.header(entry.getKey(), entry.getValue());
        }//w  w w  . j  a v  a  2 s  .c  o  m
    }

    if (!request.getHeaders().containsKey(USER_AGENT_HEADER)) {
        request.header(USER_AGENT_HEADER, USER_AGENT);
    }
    if (!request.getHeaders().containsKey(ACCEPT_ENCODING_HEADER)) {
        request.header(ACCEPT_ENCODING_HEADER, "gzip");
    }

    HttpRequestBase reqObj = null;

    String urlToRequest = null;
    try {
        URL url = new URL(request.getUrl());
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(),
                URLDecoder.decode(url.getPath(), "UTF-8"), "", url.getRef());
        urlToRequest = uri.toURL().toString();
        if (url.getQuery() != null && !url.getQuery().trim().equals("")) {
            if (!urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
                urlToRequest += "?";
            }
            urlToRequest += url.getQuery();
        } else if (urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
            urlToRequest = urlToRequest.substring(0, urlToRequest.length() - 1);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    switch (request.getHttpMethod()) {
    case GET:
        reqObj = new HttpGet(urlToRequest);
        break;
    case POST:
        reqObj = new HttpPost(urlToRequest);
        break;
    case PUT:
        reqObj = new HttpPut(urlToRequest);
        break;
    case DELETE:
        //reqObj = new HttpDeleteWithBody(urlToRequest);
        break;
    case PATCH:
        //reqObj = new HttpPatchWithBody(urlToRequest);
        break;
    case OPTIONS:
        reqObj = new HttpOptions(urlToRequest);
        break;
    case HEAD:
        reqObj = new HttpHead(urlToRequest);
        break;
    }

    Set<Entry<String, List<String>>> entrySet = request.getHeaders().entrySet();
    for (Entry<String, List<String>> entry : entrySet) {
        List<String> values = entry.getValue();
        if (values != null) {
            for (String value : values) {
                reqObj.addHeader(entry.getKey(), value);
            }
        }
    }

    // Set body
    if (!(request.getHttpMethod() == HttpMethod.GET || request.getHttpMethod() == HttpMethod.HEAD)) {
        if (request.getBody() != null) {
            HttpEntity entity = request.getBody().getEntity();
            if (async) {
                if (reqObj.getHeaders(CONTENT_TYPE) == null || reqObj.getHeaders(CONTENT_TYPE).length == 0) {
                    reqObj.setHeader(entity.getContentType());
                }
                try {
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    entity.writeTo(output);
                    NByteArrayEntity en = new NByteArrayEntity(output.toByteArray());
                    ((HttpEntityEnclosingRequestBase) reqObj).setEntity(en);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                ((HttpEntityEnclosingRequestBase) reqObj).setEntity(entity);
            }
        }
    }

    return reqObj;
}

From source file:org.jboss.as.test.integration.web.security.WebSecurityCERTTestCase.java

public static HttpClient wrapClient(HttpClient base, String alias) {
    try {//from www. j a v a 2 s. co m
        SSLContext ctx = SSLContext.getInstance("TLS");
        JBossJSSESecurityDomain jsseSecurityDomain = new JBossJSSESecurityDomain("client-cert");
        jsseSecurityDomain.setKeyStorePassword("changeit");
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        URL keystore = tccl.getResource("security/client.keystore");
        jsseSecurityDomain.setKeyStoreURL(keystore.getPath());
        jsseSecurityDomain.setClientAlias(alias);
        jsseSecurityDomain.reloadKeyAndTrustStore();
        KeyManager[] keyManagers = jsseSecurityDomain.getKeyManagers();
        TrustManager[] trustManagers = jsseSecurityDomain.getTrustManagers();
        ctx.init(keyManagers, trustManagers, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 8380, ssf));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:com.adaptris.core.fs.FsHelper.java

/**
 * Create a file reference from a URL using the platform default encoding for the URL.
 * //from w  w  w  .  ja v a 2 s  . c  om
 * @param url the URL.
 * @param charset the encoding that the url is considered to be in.
 * @return a File object
 * @throws UnsupportedEncodingException if the encoding was not supported.
 */
public static File createFileReference(URL url, String charset) throws UnsupportedEncodingException {
    String charSetToUse = StringUtils.defaultIfBlank(charset, System.getProperty("file.encoding"));
    String filename = URLDecoder.decode(url.getPath(), charSetToUse);
    // Cope with file://localhost/./config/blah -> /./config/blah is the result of getPath()
    // Munge that properly.
    if (filename.startsWith("/.")) {
        filename = filename.substring(1);
    }
    return new File(filename);
}