Example usage for java.net URL toString

List of usage examples for java.net URL toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Constructs a string representation of this URL .

Usage

From source file:ch.vorburger.mariadb4j.Util.java

/**
 * Extract files from a package on the classpath into a directory.
 * /*from   w w  w  .  j  av a2 s.co m*/
 * @param packagePath e.g. "com/stuff" (always forward slash not backslash, never dot)
 * @param toDir directory to extract to
 * @return int the number of files copied
 * @throws java.io.IOException if something goes wrong, including if nothing was found on
 *             classpath
 */
public static int extractFromClasspathToFile(String packagePath, File toDir) throws IOException {
    String locationPattern = "classpath*:" + packagePath + "/**";
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = resourcePatternResolver.getResources(locationPattern);
    if (resources.length == 0) {
        throw new IOException("Nothing found at " + locationPattern);
    }
    int counter = 0;
    for (Resource resource : resources) {
        if (resource.isReadable()) { // Skip hidden or system files
            final URL url = resource.getURL();
            String path = url.toString();
            if (!path.endsWith("/")) { // Skip directories
                int p = path.lastIndexOf(packagePath) + packagePath.length();
                path = path.substring(p);
                final File targetFile = new File(toDir, path);
                long len = resource.contentLength();
                if (!targetFile.exists() || targetFile.length() != len) { // Only copy new files
                    tryN(5, 500, new Procedure<IOException>() {

                        @Override
                        public void apply() throws IOException {
                            FileUtils.copyURLToFile(url, targetFile);
                        }
                    });
                    counter++;
                }
            }
        }
    }
    if (counter > 0) {
        Object[] info = new Object[] { counter, locationPattern, toDir };
        logger.info("Unpacked {} files from {} to {}", info);
    }
    return counter;
}

From source file:org.apache.cxf.fediz.service.idp.integrationtests.RestITTest.java

@BeforeClass
public static void init() {
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
    System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
    System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "info");
    System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "info");
    System.setProperty("org.apache.commons.logging.simplelog.log.org.springframework.webflow", "info");
    System.setProperty("org.apache.commons.logging.simplelog.log.org.springframework.security.web", "info");
    System.setProperty("org.apache.commons.logging.simplelog.log.org.springframework.security", "info");
    System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.cxf.fediz", "info");
    System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.cxf", "info");

    idpHttpsPort = System.getProperty("idp.https.port");
    Assert.assertNotNull("Property 'idp.https.port' null", idpHttpsPort);

    SpringBusFactory bf = new SpringBusFactory();

    URL busFile = RestITTest.class.getResource("/rest-client.xml");
    bus = bf.createBus(busFile.toString());
    SpringBusFactory.setDefaultBus(bus);
    SpringBusFactory.setThreadDefaultBus(bus);

}

From source file:com.wrapp.android.webimage.ImageDownloader.java

public static Date getServerTimestamp(final URL imageUrl) {
    Date expirationDate = new Date();

    try {//from   www  .  j  a  v  a  2  s . co  m
        final String imageUrlString = imageUrl.toString();
        if (imageUrlString == null || imageUrlString.length() == 0) {
            throw new Exception("Passed empty URL");
        }
        LogWrapper.logMessage("Requesting image '" + imageUrlString + "'");
        final HttpClient httpClient = new DefaultHttpClient();
        final HttpParams httpParams = httpClient.getParams();
        httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, CONNECTION_TIMEOUT_IN_MS);
        httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT_IN_MS);
        httpParams.setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, DEFAULT_BUFFER_SIZE);
        final HttpHead httpHead = new HttpHead(imageUrlString);
        final HttpResponse response = httpClient.execute(httpHead);

        Header[] header = response.getHeaders("Expires");
        if (header != null && header.length > 0) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US);
            expirationDate = dateFormat.parse(header[0].getValue());
            LogWrapper
                    .logMessage("Image at " + imageUrl.toString() + " expires on " + expirationDate.toString());
        }
    } catch (Exception e) {
        LogWrapper.logException(e);
    }

    return expirationDate;
}

From source file:com.cdancy.artifactory.rest.util.ArtifactoryUtils.java

public static GAVCoordinates gavFromURL(URL url, URL endpoint) {
    GAVCoordinates gavCoordinates = new GAVCoordinates();

    String sanitizedURL = getBasePath(url, endpoint.toString());
    String[] sanitizedURLParts = sanitizedURL.split("/");

    List<String> gavArray = Arrays.asList(Arrays.copyOfRange(sanitizedURLParts, 2, sanitizedURLParts.length));
    List<String> groupArray = gavArray.subList(0, gavArray.size() - 3);

    gavCoordinates.group = collectionToString(groupArray, ".");
    gavCoordinates.artifact = gavArray.get(groupArray.size());
    gavCoordinates.version = gavArray.get(groupArray.size() + 1);

    return gavCoordinates;
}

From source file:ch.lipsch.subsonic4j.internal.SubsonicUtil.java

public static String restifySubsonicUrl(URL url, String view) {
    StateChecker.check(url, "url");
    StateChecker.check(view, "view");
    String restifiedUrl = url.toString();
    restifiedUrl = addSlashIfNecessary(restifiedUrl);
    restifiedUrl += REST_PATH;//from   w w w.ja v  a2  s  .  c  o  m
    restifiedUrl = addSlashIfNecessary(restifiedUrl);
    restifiedUrl += view;
    return restifiedUrl;
}

From source file:es.javocsoft.android.lib.toolbox.net.HttpOperations.java

/**
 * A POST operation./*from   ww  w. j  a va2 s.  co  m*/
 * 
 * @param url         Url for the POST operation 
 * @param data         JSON data 
 * @throws Exception   In case of any error.
 */
public static String doPost(String url, String data, Map<String, String> headersData) throws Exception {
    String res;

    String theJSON = data;
    if (LOG_ENABLE)
        Log.d(TAG, "POST: " + theJSON);

    URL urlPath = null;
    try {
        urlPath = new URL(url);
        res = ToolBox.net_httpclient_doAction(HTTP_METHOD.POST, urlPath.toString(), theJSON, headersData);

    } catch (Exception e) {
        if (LOG_ENABLE)
            Log.e(TAG, "POST: Error sending data (POS) to service url '" + urlPath.toString() + "': "
                    + e.getMessage(), e);

        throw e;
    }

    return res;
}

From source file:com.linkedin.pinot.common.utils.SchemaUtils.java

/**
 * Given host, port and schema name, send a http GET request to download the {@link Schema}.
 *
 * @return schema on success.// ww  w  .j  av a2  s . com
 * <P><code>null</code> on failure.
 */
public static @Nullable Schema getSchema(@Nonnull String host, int port, @Nonnull String schemaName) {
    Preconditions.checkNotNull(host);
    Preconditions.checkNotNull(schemaName);

    try {
        URL url = new URL("http", host, port, "/schemas/" + schemaName);
        GetMethod httpGet = new GetMethod(url.toString());
        try {
            int responseCode = HTTP_CLIENT.executeMethod(httpGet);
            String response = httpGet.getResponseBodyAsString();
            if (responseCode >= 400) {
                // File not find error code.
                if (responseCode == 404) {
                    LOGGER.info("Cannot find schema: {} from host: {}, port: {}", schemaName, host, port);
                } else {
                    LOGGER.warn("Got error response code: {}, response: {}", responseCode, response);
                }
                return null;
            }
            return Schema.fromString(response);
        } finally {
            httpGet.releaseConnection();
        }
    } catch (Exception e) {
        LOGGER.error("Caught exception while getting the schema: {} from host: {}, port: {}", schemaName, host,
                port, e);
        return null;
    }
}

From source file:org.dojotoolkit.zazl.internal.XMLHttpRequestUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static String xhrRequest(String shrDataString) {
    InputStream is = null;/*from   w  w w  .  j a  v a2 s  . c  om*/
    String json = null;

    try {
        logger.logp(Level.FINER, XMLHttpRequestUtils.class.getName(), "xhrRequest",
                "shrDataString [" + shrDataString + "]");

        Map<String, Object> xhrData = (Map<String, Object>) JSONParser.parse(new StringReader(shrDataString));
        String url = (String) xhrData.get("url");
        String method = (String) xhrData.get("method");
        List headers = (List) xhrData.get("headers");
        URL requestURL = createURL(url);
        URI uri = new URI(requestURL.toString());

        HashMap httpMethods = new HashMap(7);
        httpMethods.put("DELETE", new HttpDelete(uri));
        httpMethods.put("GET", new HttpGet(uri));
        httpMethods.put("HEAD", new HttpHead(uri));
        httpMethods.put("OPTIONS", new HttpOptions(uri));
        httpMethods.put("POST", new HttpPost(uri));
        httpMethods.put("PUT", new HttpPut(uri));
        httpMethods.put("TRACE", new HttpTrace(uri));
        HttpUriRequest request = (HttpUriRequest) httpMethods.get(method.toUpperCase());

        if (request.equals(null)) {
            throw new Error("SYNTAX_ERR");
        }

        for (Object header : headers) {
            StringTokenizer st = new StringTokenizer((String) header, ":");
            String name = st.nextToken();
            String value = st.nextToken();
            request.addHeader(name, value);
        }

        HttpClient client = new DefaultHttpClient();

        HttpResponse response = client.execute(request);
        Map headerMap = new HashMap();

        HeaderIterator headerIter = response.headerIterator();

        while (headerIter.hasNext()) {
            Header header = headerIter.nextHeader();
            headerMap.put(header.getName(), header.getValue());
        }

        int status = response.getStatusLine().getStatusCode();
        String statusText = response.getStatusLine().toString();

        is = response.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        StringBuffer sb = new StringBuffer();

        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append('\n');
        }
        Map m = new HashMap();
        m.put("status", new Integer(status));
        m.put("statusText", statusText);
        m.put("responseText", sb.toString());
        m.put("headers", headerMap.toString());
        StringWriter w = new StringWriter();
        JSONSerializer.serialize(w, m);
        json = w.toString();
        logger.logp(Level.FINER, XMLHttpRequestUtils.class.getName(), "xhrRequest", "json [" + json + "]");
    } catch (Throwable e) {
        logger.logp(Level.SEVERE, XMLHttpRequestUtils.class.getName(), "xhrRequest",
                "Failed request for [" + shrDataString + "]", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }
    return json;
}

From source file:com.linkedin.pinot.common.utils.SchemaUtils.java

/**
 * Given host, port and schema name, send a http DELETE request to delete the {@link Schema}.
 *
 * @return <code>true</code> on success.
 * <P><code>false</code> on failure.
 *//*w w  w. ja v a 2 s  .  c o  m*/
public static boolean deleteSchema(@Nonnull String host, int port, @Nonnull String schemaName) {
    Preconditions.checkNotNull(host);
    Preconditions.checkNotNull(schemaName);

    try {
        URL url = new URL("http", host, port, "/schemas/" + schemaName);
        DeleteMethod httpDelete = new DeleteMethod(url.toString());
        try {
            int responseCode = HTTP_CLIENT.executeMethod(httpDelete);
            if (responseCode >= 400) {
                String response = httpDelete.getResponseBodyAsString();
                LOGGER.warn("Got error response code: {}, response: {}", responseCode, response);
                return false;
            }
            return true;
        } finally {
            httpDelete.releaseConnection();
        }
    } catch (Exception e) {
        LOGGER.error("Caught exception while getting the schema: {} from host: {}, port: {}", schemaName, host,
                port, e);
        return false;
    }
}

From source file:es.javocsoft.android.lib.toolbox.net.HttpOperations.java

/**
 * A GET operation./* ww w  . j  a v  a2  s .  co  m*/
 * 
 * @param url
 * @return
 * @throws Exception
 */
public static String doGet(String url, Map<String, String> headersData)
        throws ConnectTimeoutException, SocketTimeoutException, Exception {
    String res = null;

    if (LOG_ENABLE)
        Log.d(TAG, "GET: " + url);

    URL urlPath = null;
    try {
        urlPath = new URL(url);
        res = ToolBox.net_httpclient_doAction(HTTP_METHOD.GET, urlPath.toString(), null, headersData);

    } catch (ConnectTimeoutException e) {
        if (LOG_ENABLE)
            Log.e(TAG, "GET: Error doing get to service url '" + urlPath.toString() + "': " + e.getMessage(),
                    e);
        throw e;
    } catch (SocketTimeoutException e) {
        if (LOG_ENABLE)
            Log.e(TAG, "GET: Error doing get to service url '" + urlPath.toString() + "': " + e.getMessage(),
                    e);
        throw e;
    } catch (Exception e) {
        if (LOG_ENABLE)
            Log.e(TAG, "GET: Error doing get to service url '" + urlPath.toString() + "': " + e.getMessage(),
                    e);
        throw e;
    }

    return res;
}