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:dk.kk.ibikecphlib.util.HttpUtils.java

public static JsonNode getFromServer(String urlString) {
    JsonNode ret = null;/*ww  w.  j a  v  a 2  s  . c o  m*/
    LOG.d("GET api request, url = " + urlString);
    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, CONNECTON_TIMEOUT);
    HttpConnectionParams.setSoTimeout(myParams, CONNECTON_TIMEOUT);
    HttpClient httpclient = new DefaultHttpClient(myParams);
    httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Config.USER_AGENT);
    HttpGet httpget = null;
    URL url = null;
    try {

        url = new URL(urlString);
        httpget = new HttpGet(url.toString());
        httpget.setHeader("Content-type", "application/json");
        httpget.setHeader("Accept", ACCEPT);
        httpget.setHeader("LANGUAGE_CODE", IBikeApplication.getLanguageString());
        HttpResponse response = httpclient.execute(httpget);
        String serverResponse = EntityUtils.toString(response.getEntity());
        LOG.d("API response = " + serverResponse);
        ret = Util.stringToJsonNode(serverResponse);
    } catch (Exception e) {
        if (e != null && e.getLocalizedMessage() != null) {
            LOG.e(e.getLocalizedMessage());
        }
    }
    return ret;
}

From source file:dk.kk.ibikecphlib.util.HttpUtils.java

public static JsonNode putToServer(String urlString, JSONObject objectToPost) {
    JsonNode ret = null;/*from ww  w .  j  a  va2s .c  o m*/
    LOG.d("PUT api request, url = " + urlString);
    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, CONNECTON_TIMEOUT);
    HttpConnectionParams.setSoTimeout(myParams, CONNECTON_TIMEOUT);
    HttpClient httpclient = new DefaultHttpClient(myParams);
    httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Config.USER_AGENT);
    HttpPut httput = null;
    URL url = null;
    try {
        url = new URL(urlString);
        httput = new HttpPut(url.toString());
        httput.setHeader("Content-type", "application/json");
        httput.setHeader("Accept", ACCEPT);
        httput.setHeader("LANGUAGE_CODE", IBikeApplication.getLanguageString());
        StringEntity se = new StringEntity(objectToPost.toString(), HTTP.UTF_8);
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httput.setEntity(se);
        HttpResponse response = httpclient.execute(httput);
        String serverResponse = EntityUtils.toString(response.getEntity());
        LOG.d("API response = " + serverResponse);
        ret = Util.stringToJsonNode(serverResponse);
    } catch (Exception e) {
        if (e != null && e.getLocalizedMessage() != null) {
            LOG.e(e.getLocalizedMessage());
        }
    }
    return ret;
}

From source file:name.yumao.douyu.http.PlaylistDownloader.java

private static String getBaseUrl(URL url) {
    String urlString = url.toString();
    int index = urlString.lastIndexOf('/');
    return urlString.substring(0, ++index);
}

From source file:com.netflix.nicobar.core.module.ScriptModuleUtils.java

/**
 * Convert a ScriptModule to its compiled equivalent ScriptArchive.
 * <p>//  ww w .j a  va 2s.  com
 * A jar script archive is created containing compiled bytecode
 * from a script module, as well as resources and other metadata from
 * the source script archive.
 * <p>
 * This involves serializing the class bytes of all the loaded classes in
 * the script module, as well as copying over all entries in the original
 * script archive, minus any that have excluded extensions. The module spec
 * of the source script archive is transferred as is to the target bytecode
 * archive.
 *
 * @param module the input script module containing loaded classes
 * @param jarPath the path to a destination JarScriptArchive.
 * @param excludeExtensions a set of extensions with which
 *        source script archive entries can be excluded.
 *
 * @throws Exception
 */
public static void toCompiledScriptArchive(ScriptModule module, Path jarPath, Set<String> excludeExtensions)
        throws Exception {
    ScriptArchive sourceArchive = module.getSourceArchive();
    JarOutputStream jarStream = new JarOutputStream(new FileOutputStream(jarPath.toFile()));
    try {
        // First copy all resources (excluding those with excluded extensions)
        // from the source script archive, into the target script archive
        for (String archiveEntry : sourceArchive.getArchiveEntryNames()) {
            URL entryUrl = sourceArchive.getEntry(archiveEntry);
            boolean skip = false;
            for (String extension : excludeExtensions) {
                if (entryUrl.toString().endsWith(extension)) {
                    skip = true;
                    break;
                }
            }

            if (skip)
                continue;

            InputStream entryStream = entryUrl.openStream();
            byte[] entryBytes = IOUtils.toByteArray(entryStream);
            entryStream.close();

            jarStream.putNextEntry(new ZipEntry(archiveEntry));
            jarStream.write(entryBytes);
            jarStream.closeEntry();
        }

        // Now copy all compiled / loaded classes from the script module.
        Set<Class<?>> loadedClasses = module.getModuleClassLoader().getLoadedClasses();
        Iterator<Class<?>> iterator = loadedClasses.iterator();
        while (iterator.hasNext()) {
            Class<?> clazz = iterator.next();
            String classPath = clazz.getName().replace(".", "/") + ".class";
            URL resourceURL = module.getModuleClassLoader().getResource(classPath);
            if (resourceURL == null) {
                throw new Exception("Unable to find class resource for: " + clazz.getName());
            }

            InputStream resourceStream = resourceURL.openStream();
            jarStream.putNextEntry(new ZipEntry(classPath));
            byte[] classBytes = IOUtils.toByteArray(resourceStream);
            resourceStream.close();
            jarStream.write(classBytes);
            jarStream.closeEntry();
        }

        // Copy the source moduleSpec, but tweak it to specify the bytecode compiler in the
        // compiler plugin IDs list.
        ScriptModuleSpec moduleSpec = sourceArchive.getModuleSpec();
        ScriptModuleSpec.Builder newModuleSpecBuilder = new ScriptModuleSpec.Builder(moduleSpec.getModuleId());
        newModuleSpecBuilder.addCompilerPluginIds(moduleSpec.getCompilerPluginIds());
        newModuleSpecBuilder.addCompilerPluginId(BytecodeLoadingPlugin.PLUGIN_ID);
        newModuleSpecBuilder.addMetadata(moduleSpec.getMetadata());
        newModuleSpecBuilder.addModuleDependencies(moduleSpec.getModuleDependencies());

        // Serialize the modulespec with GSON and its default spec file name
        ScriptModuleSpecSerializer specSerializer = new GsonScriptModuleSpecSerializer();
        String json = specSerializer.serialize(newModuleSpecBuilder.build());
        jarStream.putNextEntry(new ZipEntry(specSerializer.getModuleSpecFileName()));
        jarStream.write(json.getBytes(Charsets.UTF_8));
        jarStream.closeEntry();
    } finally {
        if (jarStream != null) {
            jarStream.close();
        }
    }
}

From source file:dk.kk.ibikecphlib.util.HttpUtils.java

public static JsonNode postToServer(String urlString, JSONObject objectToPost) {
    JsonNode ret = null;//from   w w  w. j a v a2 s. c o  m
    LOG.d("POST api request, url = " + urlString + " object = " + objectToPost.toString());
    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, CONNECTON_TIMEOUT);
    HttpConnectionParams.setSoTimeout(myParams, CONNECTON_TIMEOUT);
    HttpClient httpclient = new DefaultHttpClient(myParams);
    httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Config.USER_AGENT);
    HttpPost httppost = null;
    URL url = null;
    try {
        url = new URL(urlString);
        httppost = new HttpPost(url.toString());
        httppost.setHeader("Content-type", "application/json");
        httppost.setHeader("Accept", ACCEPT);
        httppost.setHeader("LANGUAGE_CODE", IBikeApplication.getLanguageString());
        StringEntity se = new StringEntity(objectToPost.toString(), HTTP.UTF_8);// , HTTP.UTF_8
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httppost.setEntity(se);
        HttpResponse response = httpclient.execute(httppost);
        String serverResponse = EntityUtils.toString(response.getEntity());
        LOG.d("API response = " + serverResponse);
        ret = Util.stringToJsonNode(serverResponse);
    } catch (Exception e) {
        if (e != null && e.getLocalizedMessage() != null) {
            LOG.e(e.getLocalizedMessage());
        }
    }
    return ret;
}

From source file:com.blackducksoftware.integration.hub.util.HubUrlParser.java

public static UUID getUUIDFromURL(final String identifier, final URL url) throws MissingUUIDException {
    if (StringUtils.isBlank(identifier)) {
        throw new IllegalArgumentException("No identifier was provided.");
    }// w w w  .j  a  v  a  2s. co  m
    if (url == null) {
        throw new IllegalArgumentException("No URL was provided to parse.");
    }
    return getUUIDFromURLString(identifier, url.toString());
}

From source file:ArchiveUtil.java

/**
 * Extracts the file {@code archive} to the target dir {@code targetDir} and deletes the 
 * files extracted upon jvm exit if the flag {@code deleteOnExit} is true.
 *///from   w  w  w . j av a 2  s .  c  o  m
public static boolean extract(URL archive, File targetDir, boolean deleteOnExit) throws IOException {
    String archiveStr = archive.toString();
    String jarEntry = null;
    int idx = archiveStr.indexOf("!/");
    if (idx != -1) {
        if (!archiveStr.startsWith("jar:") && archiveStr.length() == idx + 2)
            return false;
        archive = new URL(archiveStr.substring(4, idx));
        jarEntry = archiveStr.substring(idx + 2);
    } else if (!isSupported(archiveStr))
        return false;

    JarInputStream jis = new JarInputStream(archive.openConnection().getInputStream());
    if (!targetDir.exists())
        targetDir.mkdirs();
    JarEntry entry = null;
    while ((entry = jis.getNextJarEntry()) != null) {
        String entryName = entry.getName();
        File entryFile = new File(targetDir, entryName);
        if (!entry.isDirectory()) {
            if (jarEntry == null || entryName.startsWith(jarEntry)) {
                if (!entryFile.exists() || entryFile.lastModified() != entry.getTime())
                    extractEntry(entryFile, jis, entry, deleteOnExit);
            }
        }
    }
    try {
        jis.close();
    } catch (Exception e) {
    }
    return true;
}

From source file:com.futureplatforms.kirin.internal.attic.IOUtils.java

public static InputStream connectTo(Context context, URL url, HttpClient client) throws IOException {
    int retries = 1;
    IOException exception;//from w  w w .j  a  v a2 s .  c om
    do {
        try {
            HttpGet request = new HttpGet(url.toString());

            request.setHeader("User-Agent", C.getUserAgentString());

            HttpResponse resp = client.execute(request);
            HttpEntity entity = resp.getEntity();
            InputStream rawContent = entity.getContent();

            return rawContent;
        } catch (IOException e) {
            exception = e;
            Log.e(C.TAG, MessageFormat.format("Problem connecting to {0}. Have {1} retries left", url, retries),
                    e);
        } catch (IllegalStateException e) {
            exception = new IOException(e.getLocalizedMessage());
            Log.e(C.TAG, MessageFormat.format("Problem connecting to {0}. Aborting", url, retries), e);
            break;
        }
    } while (retries-- > 0);
    assert exception != null;
    throw exception;
}

From source file:com.revolsys.util.JavaBeanUtil.java

public static boolean isDefinedInClassLoader(final ClassLoader classLoader, final URL resourceUrl) {
    if (classLoader instanceof URLClassLoader) {
        final String resourceUrlString = resourceUrl.toString();
        final URLClassLoader urlClassLoader = (URLClassLoader) classLoader;
        for (final URL url : urlClassLoader.getURLs()) {
            if (resourceUrlString.contains(url.toString())) {
                return true;
            }//from   w w  w . j a v  a2  s . c  o  m
        }
        return false;
    } else {
        return true;
    }
}

From source file:dk.kk.ibikecphlib.util.HttpUtils.java

public static JsonNode deleteFromServer(String urlString, JSONObject objectToPost) {
    JsonNode ret = null;/*from  ww w  . j a v a  2  s.c o  m*/
    LOG.d("DELETE api request, url = " + urlString);
    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, CONNECTON_TIMEOUT);
    HttpConnectionParams.setSoTimeout(myParams, CONNECTON_TIMEOUT);
    HttpClient httpclient = new DefaultHttpClient(myParams);
    httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Config.USER_AGENT);
    HTTPDeleteWithBody httpdelete = null;
    URL url = null;
    try {
        url = new URL(urlString);
        httpdelete = new HTTPDeleteWithBody(url.toString());
        httpdelete.setHeader("Content-type", "application/json");
        httpdelete.setHeader("Accept", ACCEPT);
        httpdelete.setHeader("LANGUAGE_CODE", IBikeApplication.getLanguageString());
        StringEntity se = new StringEntity(objectToPost.toString(), HTTP.UTF_8);
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httpdelete.setEntity(se);
        HttpResponse response = httpclient.execute(httpdelete);
        String serverResponse = EntityUtils.toString(response.getEntity());
        LOG.d("API response = " + serverResponse);
        ret = Util.stringToJsonNode(serverResponse);
    } catch (Exception e) {
        if (e != null && e.getLocalizedMessage() != null)
            LOG.e(e.getLocalizedMessage());
    }
    return ret;
}