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:com.microsoft.alm.plugin.idea.common.utils.IdeaHelper.java

/**
 * Finds the full path to a resource whether it's installed by the idea or being run inside the idea
 *
 * @param resourceUrl  the URL for the resource
 * @param resourceName name of the resource
 * @param directory    the directory under the idea.plugin/resource directory to for the resource
 * @return the path to the resource//w w w. j a v a  2s . c  om
 * @throws UnsupportedEncodingException
 */
public static String getResourcePath(final URL resourceUrl, final String resourceName, final String directory)
        throws UnsupportedEncodingException {
    // find location of the resource
    String resourcePath = resourceUrl.getPath();
    resourcePath = URLDecoder.decode(resourcePath, CHARSET_UTF8);
    resourcePath = StringUtils.chomp(resourcePath, "/");

    // When running the plugin inside of the idea for test, the path to the app needs to be
    // manipulated to look in a different location than where the resource resides in production.
    // For prod the url is .../../.IdeaIC15/config/plugins/com.microsoft.alm/lib but for test
    // the url is ../.IdeaIC15/system/plugins-sandbox/plugins/com.microsoft.alm.plugin.idea/classes
    if (resourcePath != null && resourcePath.endsWith(PROD_RESOURCES_SUB_PATH)) {
        return resourcePath + "/" + directory + "/" + resourceName;
    } else {
        return resourcePath + TEST_RESOURCES_SUB_PATH + directory + "/" + resourceName;
    }
}

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

public static void createTestConnector(final ModelControllerClient client) throws Exception {
    final List<ModelNode> updates = new ArrayList<ModelNode>();
    ModelNode op = new ModelNode();
    op.get(OP).set(ADD);/*from  w w  w .ja  v  a2 s.  c o  m*/
    op.get(OP_ADDR).add("socket-binding-group", "standard-sockets");
    op.get(OP_ADDR).add("socket-binding", "https-test");
    op.get("interface").set("default");
    op.get("port").set(8380);

    updates.add(op);

    op = new ModelNode();
    op.get(OP).set(ADD);
    op.get(OP_ADDR).add(SUBSYSTEM, "web");
    op.get(OP_ADDR).add("connector", "testConnector");
    op.get("socket-binding").set("https-test");
    op.get("enabled").set(true);
    op.get("protocol").set("HTTP/1.1");
    op.get("scheme").set("https");
    op.get("secure").set(true);
    ModelNode ssl = new ModelNode();
    ssl.setEmptyObject();
    ssl.get("name").set("https-test");
    ssl.get("key-alias").set("test");
    ssl.get("password").set("changeit");
    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    URL keystore = tccl.getResource("security/server.keystore");
    ssl.get("certificate-key-file").set(keystore.getPath());
    ssl.get("protocol").set("TLS");
    ssl.get("verify-client").set(true);
    op.get("ssl").set(ssl);

    updates.add(op);
    applyUpdates(updates, client);
}

From source file:com.base.httpclient.HttpJsonClient.java

/**
 * get/*  ww  w . jav a 2  s .c o m*/
 * 
 * @param url
 *            URL
 * @param params
 *            getkey-value
 * @return JSON
 * @throws ClientProtocolException
 * @throws IOException
 * @throws URISyntaxException 
 */
public static String get(String url, Map<String, ?> params)
        throws ClientProtocolException, IOException, URISyntaxException {
    DefaultHttpClient httpclient = getHttpClient();
    try {
        if (params != null && !(params.isEmpty())) {
            List<NameValuePair> values = new ArrayList<NameValuePair>();
            for (Map.Entry<String, ?> entity : params.entrySet()) {
                BasicNameValuePair pare = new BasicNameValuePair(entity.getKey(), entity.getValue().toString());
                values.add(pare);

            }
            String str = URLEncodedUtils.format(values, "UTF-8");
            if (url.indexOf("?") > -1) {
                url += "&" + str;
            } else {
                url += "?" + str;
            }
        }
        URL pageURL = new URL(url);
        //pageUrl?httpget
        URI uri = new URI(pageURL.getProtocol(), pageURL.getHost(), pageURL.getPath(), pageURL.getQuery(),
                null);
        HttpGet httpget = createHttpUriRequest(HttpMethod.GET, uri);
        httpget.setHeader("Pragma", "no-cache");
        httpget.setHeader("Cache-Control", "max-age=0, no-cache, no-store, must-revalidate");
        httpget.setHeader("Connection", "keep-alive");
        httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        httpget.setHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
        httpget.setHeader("Accept-Charset", "gbk,utf-8;q=0.7,*;q=0.7");
        httpget.setHeader("Referer", url);
        /*httpget.setHeader("Content-Encoding", "gzip");
        httpget.setHeader("Accept-Encoding", "gzip, deflate");*/
        //httpget.setHeader("Host", "s.taobao.com");
        /*int temp = Integer.parseInt(Math.round(Math.random()*(MingSpiderService.UserAgent.length-1))+"");//???
        httpget.setHeader("User-Agent", MingSpiderService.UserAgent[temp]);*/
        HttpResponse response = httpclient.execute(httpget);
        httpclient.getCookieStore().clear();
        int resStatu = response.getStatusLine().getStatusCode();
        String html = "";
        if (resStatu == HttpStatus.SC_OK) {//200 
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                html = EntityUtils.toString(entity, "GBK");
                EntityUtils.consume(entity);
            }
        }
        return html;
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:eu.trentorise.smartcampus.protocolcarrier.Communicator.java

private static HttpRequestBase buildRequest(MessageRequest msgRequest, String appToken, String authToken)
        throws URISyntaxException, UnsupportedEncodingException {
    String host = msgRequest.getTargetHost();
    if (host == null)
        throw new URISyntaxException(host, "null URI");
    if (!host.endsWith("/"))
        host += '/';
    String address = msgRequest.getTargetAddress();
    if (address == null)
        address = "";
    if (address.startsWith("/"))
        address = address.substring(1);//from   www.jav  a  2 s .co  m
    String uriString = host + address;
    try {
        URL url = new URL(uriString);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        uriString = uri.toURL().toString();
    } catch (MalformedURLException e) {
        throw new URISyntaxException(uriString, e.getMessage());
    }
    if (msgRequest.getQuery() != null)
        uriString += "?" + msgRequest.getQuery();

    //      new URI(uriString);

    HttpRequestBase request = null;
    if (msgRequest.getMethod().equals(Method.POST)) {
        HttpPost post = new HttpPost(uriString);
        HttpEntity httpEntity = null;
        if (msgRequest.getRequestParams() != null) {
            // if body and requestparams are either not null there is an
            // exception
            if (msgRequest.getBody() != null && msgRequest != null) {
                throw new IllegalArgumentException("body and requestParams cannot be either populated");
            }
            httpEntity = new MultipartEntity();

            for (RequestParam param : msgRequest.getRequestParams()) {
                if (param.getParamName() == null || param.getParamName().trim().length() == 0) {
                    throw new IllegalArgumentException("paramName cannot be null or empty");
                }
                if (param instanceof FileRequestParam) {
                    FileRequestParam fileparam = (FileRequestParam) param;
                    ((MultipartEntity) httpEntity).addPart(param.getParamName(), new ByteArrayBody(
                            fileparam.getContent(), fileparam.getContentType(), fileparam.getFilename()));
                }
                if (param instanceof ObjectRequestParam) {
                    ObjectRequestParam objectparam = (ObjectRequestParam) param;
                    ((MultipartEntity) httpEntity).addPart(param.getParamName(),
                            new StringBody(convertObject(objectparam.getVars())));
                }
            }
            // mpe.addPart("file",
            // new ByteArrayBody(msgRequest.getFileContent(), ""));
            // post.setEntity(mpe);
        }
        if (msgRequest.getBody() != null) {
            httpEntity = new StringEntity(msgRequest.getBody(), Constants.CHARSET);
            ((StringEntity) httpEntity).setContentType(msgRequest.getContentType());
        }
        post.setEntity(httpEntity);
        request = post;
    } else if (msgRequest.getMethod().equals(Method.PUT)) {
        HttpPut put = new HttpPut(uriString);
        if (msgRequest.getBody() != null) {
            StringEntity se = new StringEntity(msgRequest.getBody(), Constants.CHARSET);
            se.setContentType(msgRequest.getContentType());
            put.setEntity(se);
        }
        request = put;
    } else if (msgRequest.getMethod().equals(Method.DELETE)) {
        request = new HttpDelete(uriString);
    } else {
        // default: GET
        request = new HttpGet(uriString);
    }

    Map<String, String> headers = new HashMap<String, String>();

    // default headers
    if (appToken != null) {
        headers.put(RequestHeader.APP_TOKEN.toString(), appToken);
    }
    if (authToken != null) {
        // is here for compatibility
        headers.put(RequestHeader.AUTH_TOKEN.toString(), authToken);
        headers.put(RequestHeader.AUTHORIZATION.toString(), "Bearer " + authToken);
    }
    headers.put(RequestHeader.ACCEPT.toString(), msgRequest.getContentType());

    if (msgRequest.getCustomHeaders() != null) {
        headers.putAll(msgRequest.getCustomHeaders());
    }

    for (String key : headers.keySet()) {
        request.addHeader(key, headers.get(key));
    }

    return request;
}

From source file:com.ebay.logstorm.core.PipelineContext.java

public static PipelineContextBuilder pipelineResource(String pipelineResource)
        throws IOException, PipelineException {
    URL resourceUrl = PipelineCompiler.class.getResource(pipelineResource);
    if (resourceUrl == null) {
        throw new IOException("Pipeline resource " + pipelineResource + " not found");
    } else {//from w ww  .j  a v a2  s.  co  m
        return new PipelineContextBuilder(FileUtils.readFileToString(new File(resourceUrl.getPath())));
    }
}

From source file:de.betterform.agent.web.WebFactory.java

/**
 * allow absolute paths otherwise resolve relative to the servlet context
 *
 * @param resolvePath XPath locationpath
 * @return the absolute path or path relative to the servlet context
 * @deprecated/*from ww w . j av a2 s  .com*/
 */
public static final String resolvePath(String resolvePath, ServletContext servletContext) {
    String path = resolvePath;
    try {
        if (path != null && !(path.startsWith("/"))) {
            path = "/" + path;
        }
        URL pathURL = servletContext.getResource(path);
        if (pathURL != null) {
            path = java.net.URLDecoder.decode(pathURL.getPath(), StandardCharsets.UTF_8.name());
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    }
    return path;
}

From source file:com.dragome.compiler.parser.Parser.java

public static String getResourcePath(String name) {
    name = name.replace('.', '/') + ".class";
    java.net.URL url = Parser.class.getClassLoader().getResource(name);
    if (url == null)
        throw new RuntimeException("Resource not found: " + name);
    return url.getPath();
}

From source file:de.jwi.ftp.FTPUploader.java

public static String upload(URL url, List files) {
    String rcs = "";

    if (!"ftp".equals(url.getProtocol())) {
        return "not ftp protocol";
    }/*  w  w  w.  jav  a 2s.  c o m*/

    String host = url.getHost();
    String userInfo = url.getUserInfo();
    String path = url.getPath();
    String user = null;
    String pass = null;

    int p;
    if ((userInfo != null) && ((p = userInfo.indexOf(':')) > -1)) {
        user = userInfo.substring(0, p);
        pass = userInfo.substring(p + 1);
    } else {
        user = userInfo;
    }

    FTPClient ftp = new FTPClient();

    try {
        int reply;
        ftp.connect(host);

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return "connection refused";
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        return "could not connect to " + host;
    }

    try {
        if (!ftp.login(user, pass)) {
            ftp.logout();
            return "failed to login";
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        ftp.enterLocalPassiveMode();

        rcs = uploadFiles(ftp, path, files);

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        return "connection closed";
    } catch (IOException e) {
        return e.getMessage();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    return rcs;
}

From source file:jetbrains.exodus.util.ForkSupportIO.java

public static List<String> getClasspath(Class cls) {
    List<String> classpath = new ArrayList<>();
    URL[] urls = ((URLClassLoader) cls.getClassLoader()).getURLs();
    for (URL url : urls) {
        File f;/*from www. j  a v a  2s.  co m*/
        try {
            f = new File(url.toURI());
        } catch (URISyntaxException e) {
            f = new File(url.getPath());
        }

        classpath.add(f.getAbsolutePath());
    }

    return classpath;
}

From source file:com.google.api.auth.IntegrationTest.java

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    // Set the path to the trustStore.
    URL truststoreUrl = IntegrationTest.class.getClassLoader().getResource("truststore.jks");
    System.setProperty("javax.net.ssl.trustStore", truststoreUrl.getPath());

    server.start();//  w ww. ja  v  a 2s . com
}