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:Main.java

/**
 * Gets the base location of the given class.
 * <p>//  w w  w .j  ava 2  s . com
 * If the class is directly on the file system (e.g.,
 * "/path/to/my/package/MyClass.class") then it will return the base directory
 * (e.g., "file:/path/to").
 * </p>
 * <p>
 * If the class is within a JAR file (e.g.,
 * "/path/to/my-jar.jar!/my/package/MyClass.class") then it will return the
 * path to the JAR (e.g., "file:/path/to/my-jar.jar").
 * </p>
 * 
 * @param c The class whose location is desired.
 * @see FileUtils#urlToFile(URL) to convert the result to a {@link File}.
 */
public static URL getLocation(final Class<?> c) {
    if (c == null)
        return null; // could not load the class

    // try the easy way first
    try {
        final URL codeSourceLocation = c.getProtectionDomain().getCodeSource().getLocation();
        if (codeSourceLocation != null)
            return codeSourceLocation;
    } catch (SecurityException e) {
        // NB: Cannot access protection domain.
    } catch (NullPointerException e) {
        // NB: Protection domain or code source is null.
    }

    // NB: The easy way failed, so we try the hard way. We ask for the class
    // itself as a resource, then strip the class's path from the URL string,
    // leaving the base path.

    // get the class's raw resource path
    final URL classResource = c.getResource(c.getSimpleName() + ".class");
    if (classResource == null)
        return null; // cannot find class resource

    final String url = classResource.toString();
    final String suffix = c.getCanonicalName().replace('.', '/') + ".class";
    if (!url.endsWith(suffix))
        return null; // weird URL

    // strip the class's path from the URL string
    final String base = url.substring(0, url.length() - suffix.length());

    String path = base;

    // remove the "jar:" prefix and "!/" suffix, if present
    if (path.startsWith("jar:"))
        path = path.substring(4, path.length() - 2);

    try {
        return new URL(path);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.redhat.rhn.common.validator.Validator.java

/**
 * <p>/* w w w  .ja  v  a2s.  c om*/
 * This will return the instance for the specific XML Schema URL. If a
 * schema exists, it is returned (as parsing will already be done);
 * otherwise, a new instance is created, and then returned.
 * </p>
 *
 * @param schemaURL <code>URL</code> of schema to validate against.
 * @return <code>Validator</code>- the instance, ready to use.
 * @throws IOException when errors in parsing occur.
 */
public static synchronized Validator getInstance(URL schemaURL) throws IOException {
    if (instances != null) {
        if (instances.containsKey(schemaURL.toString())) {
            return (Validator) instances.get(schemaURL.toString());
        }
        Validator validator = new Validator(schemaURL);
        instances.put(schemaURL.toString(), validator);
        return validator;
    }
    instances = new HashMap();
    Validator validator = new Validator(schemaURL);
    instances.put(schemaURL.toString(), validator);
    return validator;
}

From source file:com.redhat.victims.VictimsConfig.java

/**
 * Get a complete webservice uri by merging base and entry point.
 * //from  w ww  .  j a v a2 s  .c o m
 * @return
 * @throws VictimsException
 */
public static String serviceURI() throws VictimsException {
    URL merged;
    try {
        merged = new URL(new URL(uri()), entry());
        return merged.toString();
    } catch (MalformedURLException e) {
        throw new VictimsException("Invalid configuration for service URI.", e);
    }
}

From source file:org.openmhealth.shim.OAuth1Utils.java

/**
 * Signs an HTTP post request for cases where OAuth 1.0 posts are
 * required instead of GET./*from  w w w.  ja  v a  2  s . com*/
 *
 * @param unsignedUrl     - The unsigned URL
 * @param clientId        - The external provider assigned client id
 * @param clientSecret    - The external provider assigned client secret
 * @param token           - The access token
 * @param tokenSecret     - The 'secret' parameter to be used (Note: token secret != client secret)
 * @param oAuthParameters - Any additional parameters
 * @return The request to be signed and sent to external data provider.
 */
public static HttpRequestBase getSignedRequest(HttpMethod method, String unsignedUrl, String clientId,
        String clientSecret, String token, String tokenSecret, Map<String, String> oAuthParameters)
        throws ShimException {

    URL requestUrl = buildSignedUrl(unsignedUrl, clientId, clientSecret, token, tokenSecret, oAuthParameters);
    String[] signedParams = requestUrl.toString().split("\\?")[1].split("&");

    HttpRequestBase postRequest = method == HttpMethod.GET ? new HttpGet(unsignedUrl)
            : new HttpPost(unsignedUrl);
    String oauthHeader = "";
    for (String signedParam : signedParams) {
        String[] parts = signedParam.split("=");
        oauthHeader += parts[0] + "=\"" + parts[1] + "\",";
    }
    oauthHeader = "OAuth " + oauthHeader.substring(0, oauthHeader.length() - 1);
    postRequest.setHeader("Authorization", oauthHeader);
    CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(clientId, clientSecret);
    consumer.setSendEmptyTokens(false);
    if (token != null) {
        consumer.setTokenWithSecret(token, tokenSecret);
    }
    try {
        consumer.sign(postRequest);
        return postRequest;
    } catch (OAuthMessageSignerException | OAuthExpectationFailedException | OAuthCommunicationException e) {
        e.printStackTrace();
        throw new ShimException("Could not sign POST request, cannot continue");
    }
}

From source file:Main.java

/**
 * Check a xml file against a schema.//from   ww w.jav a2s  .com
 * 
 * @param fileToCheck
 * @param schemURL
 * @throws Exception
 */
static public void schemaCheck(File fileToCheck, URL schemURL) throws Exception {

    final String W3C_SCHEMA_SPEC = "http://www.w3.org/2001/XMLSchema";
    HashMap<String, Schema> MetsSchema = null;

    if (MetsSchema == null) {
        MetsSchema = new HashMap();
    }

    if (MetsSchema.get(schemURL.toString()) == null) {
        // 1. Lookup a factory for the W3C XML Schema language
        SchemaFactory factory = SchemaFactory.newInstance(W3C_SCHEMA_SPEC);

        // 2. Compile the schema. 
        MetsSchema.put(schemURL.toString(), factory.newSchema(schemURL));
    }

    // 3. Get a validator from the schema.
    Validator validator = MetsSchema.get(schemURL.toString()).newValidator();

    // 4. Parse the document you want to check.
    Source source = new StreamSource(fileToCheck);

    // 5. Check the document        
    validator.validate(source);
}

From source file:Main.java

/**
 * Get an URL to a schema file. This implementation finds the schema file using the ClassLoader
 * that loaded the argument class./*  w w w . j a  va 2 s. c o  m*/
 * 
 * @param resourceFileName
 * @param runningClass 
 * @return
 */
public static String getResourceUrlString(String resourceFileName, Class<?> runningClass) {
    String rtn = null;
    URL url = runningClass.getClassLoader().getResource(resourceFileName);
    if (url == null)
        throw new MissingResourceException("Resource not found: " + resourceFileName, runningClass.getName(),
                resourceFileName);
    rtn = url.toString();
    return rtn;
}

From source file:org.unitedinternet.cosmo.dav.caldav.report.MultigetReport.java

private static boolean isDescendentOrEqual(URL collection, URL test) {
    if (collection == null || test == null) {
        return false;
    }/*www.  ja v  a 2  s  . c  o  m*/
    if (collection.toString().equals(test.toString())) {
        return true;
    }

    try {
        String testPathDecoded = UriUtils.decode(test.getPath(), "UTF-8");
        String collectionPathDecoded = UriUtils.decode(collection.getPath(), "UTF-8");

        return testPathDecoded.startsWith(collectionPathDecoded);
    } catch (UnsupportedEncodingException e) {
        return test.getPath().startsWith(collection.getPath());
    }
}

From source file:org.jodconverter.office.OnlineOfficeManagerPoolEntry.java

private static File getFile(final URL url) {

    try {/*from w ww.  j ava  2s  .  co m*/
        return new File(new URI(StringUtils.replace(url.toString(), " ", "%20")).getSchemeSpecificPart());
    } catch (URISyntaxException ex) {
        // Fallback for URLs that are not valid URIs (should hardly ever happen).
        return new File(url.getFile());
    }
}

From source file:com.liusoft.sc.startup.DigesterFactory.java

/**
 * Load the resource and add it to the resolver.
 *///w  w w  .jav  a  2 s  .  com
protected static void register(String resourceURL, String resourcePublicId) {
    URL url = DigesterFactory.class.getResource(resourceURL);

    if (url == null) {
        log.warn("Could not get url for " + resourceURL);
    } else {
        schemaResolver.register(resourcePublicId, url.toString());
    }
}

From source file:gate.termraider.util.Utilities.java

public static String sourceOrName(Document document) {
    URL url = document.getSourceUrl();
    if (url == null) {
        return document.getName();
    }//from   w  ww .  j a  va  2 s.c  om

    //implied else
    return url.toString();
}