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:com.motorola.studio.android.localization.translators.GoogleTranslator.java

/**
 * Creates an HTTP request with the URL, execute it as a get, and returns
 * the a string with the result./* w w w  .ja  va  2 s  . co m*/
 * 
 * @param url
 *            URL to be executed.
 * @return String with the URL execution result.
 * @throws IOException
 *             If an exception occurs on transport
 * @throws HttpException
 *             If an exception occurs on the protocol
 * @throws Exception
 *             on error.
 */
protected static String executeHttpGetRequest(final URL url) throws HttpException {

    // Checking query size due to google policies
    if (url.toString().length() > MAX_QUERY_SIZE) {
        throw new HttpException(TranslateNLS.GoogleTranslator_Error_QueryTooBig);
    }

    // Try to retrieve proxy configuration to use if necessary
    IProxyService proxyService = ProxyManager.getProxyManager();
    IProxyData proxyData = null;
    if (proxyService.isProxiesEnabled() || proxyService.isSystemProxiesEnabled()) {
        Authenticator.setDefault(new ProxyAuthenticator());
        String urlStr = url.toString();
        if (urlStr.startsWith("https")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTPS_PROXY_TYPE);
            StudioLogger.debug(GoogleTranslator.class, "Using https proxy"); //$NON-NLS-1$
        } else if (urlStr.startsWith("http")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTP_PROXY_TYPE);
            StudioLogger.debug(GoogleTranslator.class, "Using http proxy"); //$NON-NLS-1$
        } else {
            StudioLogger.debug(GoogleTranslator.class, "Not using any proxy"); //$NON-NLS-1$
        }
    }

    // Creates the http client and the method to be executed
    HttpClient client = null;
    client = new HttpClient();

    // If there is proxy data, work with it
    if (proxyData != null) {
        if (proxyData.getHost() != null) {
            // Sets proxy host and port, if any
            client.getHostConfiguration().setProxy(proxyData.getHost(), proxyData.getPort());
        }

        if (proxyData.getUserId() != null && proxyData.getUserId().trim().length() > 0) {
            // Sets proxy user and password, if any
            Credentials cred = new UsernamePasswordCredentials(proxyData.getUserId(),
                    proxyData.getPassword() == null ? "" : proxyData.getPassword()); //$NON-NLS-1$
            client.getState().setProxyCredentials(AuthScope.ANY, cred);
        }
    }

    // Creating the method to be executed, the URL at this point is enough
    // because it is complete
    GetMethod method = new GetMethod(url.toString());

    // Set method to be retried three times in case of error
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(RETRIES, false));

    method.setRequestHeader(REFERER_HEADER, REFERER_SITE);

    // Set the connection timeout               
    client.getHttpConnectionManager().getParams().setConnectionTimeout(new Integer(TIMEOUT));

    String result = ""; //$NON-NLS-1$
    try {
        // Execute the method.
        int statusCode;
        try {
            statusCode = client.executeMethod(method);
            result = method.getResponseBodyAsString(MAX_SIZE);
        } catch (IOException e) {
            throw new HttpException(TranslateNLS.GoogleTranslator_Error_CannotConnectToServer + e.getMessage());
        }

        checkStatusCode(statusCode, result);

        // Unescape any possible unicode char
        result = unescapeUnicode(result);

        // Unescape any possible HTML sequence
        result = unescapeHTML(result);

    }

    finally {
        // Release the connection.
        method.releaseConnection();
    }

    return result;
}

From source file:com.ibm.team.build.internal.hjplugin.RTCFacadeFactory.java

private static URL getHjplugin_rtcJar(ClassLoader originalClassLoader, String fullClassName,
        PrintStream debugLog) {/*from   www.  java2  s  .  c  om*/
    if (originalClassLoader instanceof URLClassLoader) {
        URLClassLoader urlClassLoader = (URLClassLoader) originalClassLoader;
        URL[] originalURLs = urlClassLoader.getURLs();
        for (URL url : originalURLs) {
            String file = url.getFile();
            if (file.contains("com.ibm.team.build.hjplugin-rtc")) { //$NON-NLS-1$ //$NON-NLS-2$
                debug(debugLog, "Found hjplugin-rtc jar " + url.getFile()); //$NON-NLS-1$
                return url;
            }
        }
        debug(debugLog, "Did not find hjplugin-rtc jar from URLClassLoader"); //$NON-NLS-1$
    }
    String realClassName = fullClassName.replace('.', '/') + ".class"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    URL url = originalClassLoader.getResource(realClassName);
    debug(debugLog, "Found " + realClassName + " in " + url.toString()); //$NON-NLS-1$ //$NON-NLS-2$
    try {
        URLConnection connection = url.openConnection();
        if (connection instanceof JarURLConnection) {
            JarURLConnection jarConnection = (JarURLConnection) connection;
            debug(debugLog, "hjplugin-rtc jar from the connection " + jarConnection.getJarFileURL()); //$NON-NLS-1$
            return jarConnection.getJarFileURL();
        }
    } catch (IOException e) {
        debug(debugLog, "Unable to obtain URLConnection ", e); //$NON-NLS-1$ 
    }
    debug(debugLog, "Unable to find hjplugin-rtc.jar"); //$NON-NLS-1$ 
    return null;
}

From source file:fr.cls.atoll.motu.processor.wps.TestServiceMetadata.java

public static String[] getServiceMetadataSchemaAsString(String schemaPath) throws MotuException {

    List<String> stringList = new ArrayList<String>();
    String localIso19139SchemaPath = "file:///c:/tempVFS/testISO";
    String localIso19139RootSchemaRelPath = "/srv/srv.xsd";
    String localIso19139RootSchemaPath = String.format("%s%s", localIso19139SchemaPath,
            localIso19139RootSchemaRelPath);

    FileObject dest = Organizer.resolveFile(localIso19139RootSchemaPath);
    boolean hasIso19139asLocalSchema = false;
    try {/*from w w w. j  a  v  a 2  s. c o m*/
        if (dest != null) {
            hasIso19139asLocalSchema = dest.exists();
        }
    } catch (FileSystemException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    if (hasIso19139asLocalSchema) {
        try {
            dest.close();
        } catch (FileSystemException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } else {

        // URL url = Organizer.findResource("schema/iso/srv/srv.xsd");
        // URL url =
        // Organizer.findResource("J:/dev/iso/19139/20070417/schema/src/main/resources/iso/19139/20070417/srv/srv.xsd");
        // URL url = Organizer.findResource("iso/19139/20070417/srv/srv.xsd");
        URL url = Organizer.findResource(schemaPath);
        System.out.println(url);

        // String[] arr = url.toString().split("!");

        // FileObject jarFile = Organizer.resolveFile(arr[0]);
        FileObject jarFile = Organizer.resolveFile(url.toString());

        // List the children of the Jar file
        FileObject[] children = null;
        try {
            children = jarFile.getChildren();
        } catch (FileSystemException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("Children of " + jarFile.getName().getURI());
        for (int i = 0; i < children.length; i++) {
            System.out.println(children[i].getName().getBaseName());
        }

        dest = Organizer.resolveFile(localIso19139SchemaPath);
        Organizer.deleteDirectory(dest);

        Organizer.copyFile(jarFile, dest);
    }

    // stringList.add(url.toString());
    // stringList.add("J:/dev/iso/19139/20070417/schema/src/main/resources/iso/19139/20070417/srv/srv.xsd");
    stringList.add(localIso19139RootSchemaPath);
    // stringList.add("C:/Documents and Settings/dearith/Mes documents/Atoll/SchemaIso/srv/serviceMetadata.xsd");
    String[] inS = new String[stringList.size()];
    inS = stringList.toArray(inS);
    return inS;
}

From source file:fr.gael.dhus.service.ProductService.java

private static boolean checkUrl(URL url) {
    Objects.requireNonNull(url, "`url` parameter must not be null");

    // OData Synchronized product, DELME
    if (url.getPath().endsWith("$value")) {
        // Ignoring ...
        return true;
    }//  w  ww  .  ja v  a  2s.c o m

    // Case of simple file
    try {
        File f = new File(url.toString());
        if (f.exists())
            return true;
    } catch (Exception e) {
        logger.debug("url \"" + url + "\" not formatted as a file");
    }

    // Case of local URL
    try {
        URI local = new File(".").toURI();
        URI uri = local.resolve(url.toURI());
        File f = new File(uri);
        if (f.exists())
            return true;
    } catch (Exception e) {
        logger.debug("url \"" + url + "\" not a local URL");
    }

    // Case of remote URL
    try {
        URLConnection con = url.openConnection();
        con.connect();
        InputStream is = con.getInputStream();
        is.close();
        return true;
    } catch (Exception e) {
        logger.debug("url \"" + url + "\" not a remote URL");
    }
    // Unrecovrable case
    return false;
}

From source file:org.jboss.as.test.integration.web.sso.SSOTestBase.java

/**
 * Test single sign-on across two web apps using form based auth
 *
 * @throws Exception/*from w  ww  . j a  v a 2 s  . c  om*/
 */
public static void executeFormAuthSingleSignOnTest(URL serverA, URL serverB, Logger log) throws Exception {
    URL warA1 = new URL(serverA, "/war1/");
    URL warB2 = new URL(serverB, "/war2/");

    // Start by accessing the secured index.html of war1
    DefaultHttpClient httpclient = new DefaultHttpClient();

    checkAccessDenied(httpclient, warA1 + "index.html");

    CookieStore store = httpclient.getCookieStore();

    log.debug("Saw JSESSIONID=" + getSessionIdValueFromState(store));

    // Submit the login form
    executeFormLogin(httpclient, warA1);

    String ssoID = processSSOCookie(store, serverA.toString(), serverB.toString());
    log.debug("Saw JSESSIONIDSSO=" + ssoID);

    // Now try getting the war2 index using the JSESSIONIDSSO cookie
    log.debug("Prepare /war2/index.html get");
    checkAccessAllowed(httpclient, warB2 + "index.html");

    // Access a secured servlet that calls a secured ejb in war2 to test
    // propagation of the SSO identity to the ejb container.
    checkAccessAllowed(httpclient, warB2 + "EJBServlet");

    // Now try logging out of war2
    executeLogout(httpclient, warB2);

    // Reset Http client
    httpclient = new DefaultHttpClient();

    // Try accessing war1 again
    checkAccessDenied(httpclient, warA1 + "index.html");

    // Try accessing war2 again
    checkAccessDenied(httpclient, warB2 + "index.html");

}

From source file:com.sworddance.util.CUtilities.java

/**
 * @param searchRoot//from   w  w w  .  ja  v  a  2s  . co  m
 * @param fileName
 * @param optional
 * @param searchPaths
 * @return a de-duped Enumeration<URL> never returns null.
 */
private static Collection<URL> getResources(Object searchRoot, String fileName, boolean optional,
        List<String> searchPaths) {
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    ClassLoader searchRootClassLoader = searchRoot != null ? searchRoot.getClass().getClassLoader() : null;
    HashMap<String, URL> results = new HashMap<String, URL>();
    for (String searchPath : searchPaths) {
        Enumeration<URL> resource = null;
        if (searchRootClassLoader != null) {
            try {
                resource = searchRootClassLoader.getResources(searchPath);
                for (URL url : NotNullIterator.<URL>newNotNullIterator(resource)) {
                    results.put(url.toString(), url);
                }
            } catch (IOException e) {
                // TODO what?
            }
        }
        if (contextClassLoader != null) {
            try {
                resource = contextClassLoader.getResources(searchPath);
                for (URL url : NotNullIterator.<URL>newNotNullIterator(resource)) {
                    results.put(url.toString(), url);
                }
            } catch (IOException e) {
                // TODO what?
            }
        }
        if (resource == null) {
            try {
                resource = ClassLoader.getSystemResources(searchPath);
                for (URL url : NotNullIterator.<URL>newNotNullIterator(resource)) {
                    results.put(url.toString(), url);
                }
            } catch (IOException e) {
                // TODO what?
            }
        }
    }
    if (isEmpty(results) && !optional) {
        if (fileName != null) {
            throw new ApplicationNullPointerException(fileName, " not found in ", join(searchPaths, ","),
                    " java.class.path=", System.getProperty("java.class.path"), " java.library.path=",
                    System.getProperty("java.library.path"), " searchRoot =", getClassSafely(searchRoot));
        } else {
            throw new ApplicationNullPointerException("No listed file found ", join(searchPaths, ","),
                    " java.class.path=", System.getProperty("java.class.path"), " java.library.path=",
                    System.getProperty("java.library.path"), " searchRoot =", getClassSafely(searchRoot));
        }
    } else {
        return results.values();
    }
}

From source file:com.gallatinsystems.common.util.S3Util.java

public static String getObjectAcl(String bucketName, String objectKey, String awsAccessId, String awsSecretKey)
        throws IOException {

    final String date = getDate();
    final URL url = new URL(String.format(S3_URL, bucketName, objectKey) + "?acl");
    final String payload = String.format(GET_PAYLOAD_ACL, date, bucketName, objectKey);
    final String signature = MD5Util.generateHMAC(payload, awsSecretKey);

    InputStream in = null;/*from  w w  w.j  a v a2  s.  c  om*/
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Date", date);
        conn.setRequestProperty("Authorization", "AWS " + awsAccessId + ":" + signature);

        in = new BufferedInputStream(conn.getInputStream());

        return IOUtils.toString(in);
    } catch (Exception e) {
        log.log(Level.SEVERE, "Error getting ACL for : " + url.toString(), e);
        return null;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
        IOUtils.closeQuietly(in);
    }
}

From source file:imageLines.ImageHelpers.java

/**Read a jpeg image from a url into a BufferedImage*/
public static BufferedImage readAsBufferedImage(URL imageURL) {
    InputStream i = null;//from w  w w .ja  v a 2  s.c o  m
    try {
        URLConnection u = imageURL.openConnection();
        u.setRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.151 Safari/535.19");
        if (u instanceof HttpURLConnection) {
            HttpURLConnection h = (HttpURLConnection) u;
            if (h.getResponseCode() == 403)
                throw new Exception("403 forbidden");
        }

        i = u.getInputStream();

        BufferedImage bi = ImageIO.read(i);
        return bi;
    } catch (Exception e) {
        System.out.println(e + " for " + imageURL.toString() + "\n");
        return null;
    } finally {
        try {
            i.close();
        } catch (IOException ex) {

        }
    }
}

From source file:org.whispersystems.textsecuregcm.entities.AttachmentUri.java

public AttachmentUri(URL uri) {
    this.location = uri.toString();
}

From source file:Main.java

@Override
public void start(Stage primaryStage) {
    final URL resource = getClass().getResource("a.mp3");
    final Media media = new Media(resource.toString());
    final MediaPlayer mediaPlayer = new MediaPlayer(media);
    mediaPlayer.play();/*from w ww .  j  ava 2 s .  co m*/

    primaryStage.setTitle("Audio Player 1");
    primaryStage.setWidth(200);
    primaryStage.setHeight(200);
    primaryStage.show();
}