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:net.refractions.udig.document.source.ShpDocUtils.java

/**
 * Gets the relative path with the url as the parent path and the absolute path as the child
 * path./*from w w w .j  a  v a2  s  .c  om*/
 * 
 * @param url
 * @param absolutePath
 * @return relative path
 */
public static String getRelativePath(URL url, String absolutePath) {
    if (absolutePath != null && absolutePath.trim().length() > 0) {
        try {
            final File parentFile = new File(new URI(url.toString()));
            final File parentDir = parentFile.getParentFile();
            final File childFile = new File(absolutePath);
            return parentDir.toURI().relativize(childFile.toURI()).getPath();
        } catch (URISyntaxException e) {
            // Should not happen as shapefile should be a valid file
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.wavemaker.commons.classloader.ClassLoaderUtils.java

/**
 * Returns path to resource, loaded from classpath.
 * //  w  w  w.j  a  va2  s. com
 * @param path The relative path to the resource.
 * @return Path on disk to the resource, or null if not found.
 */
public static String getResource(String path) {
    URL url = ClassLoaderUtils.getClassLoader().getResource(path);
    if (url == null) {
        return null;
    }
    return url.toString();
}

From source file:marytts.tools.install.LicenseRegistry.java

private static void downloadLicense(URL licenseURL) {

    assert remote2local != null;
    File downloadDir = new File(System.getProperty("mary.downloadDir", "."));
    String filename = licenseURL.toString().replace('/', '_').replace(':', '_');
    File licenseFile = new File(downloadDir, filename);
    System.out.println("Downloading license from " + licenseURL.toString());
    try (FileOutputStream out = new FileOutputStream(licenseFile); InputStream in = licenseURL.openStream()) {
        IOUtils.copy(in, out);/* w ww . j a v  a 2  s .c o m*/
    } catch (IOException e) {
        System.err.println("Cannot download license from " + licenseURL.toString());
        e.printStackTrace();
    }

    // Now we need to update remote2local and write an updated license-index.txt:
    remote2local.put(licenseURL, filename);
    saveIndex();

}

From source file:com.bfd.harpc.common.configure.PathUtils.java

/**
 * Normalize the path by suppressing sequences like "path/.." and inner
 * simple dots./*from   w  w w . j ava 2  s .c  om*/
 * <p>
 * The result is convenient for path comparison. For other uses, notice that
 * Windows separators ("\") are replaced by simple slashes.
 * 
 * @param originalUrl
 *            the url with original path
 * @return the url with normalized path
 * @throws MalformedURLException
 * @throws URISyntaxException
 */
public static URL cleanPath(URL originalUrl) throws MalformedURLException, URISyntaxException {
    String path = originalUrl.toString();
    if (StringUtils.isEmpty(path)) {
        return null;
    }
    URL curl = new URL(cleanPath(path));
    // curl.toURI().getPath()?
    return new URL(curl.getProtocol(), curl.getHost(), curl.toURI().getPath());
}

From source file:com.linkedin.pinot.util.TestUtils.java

public static String getFileFromResourceUrl(@Nonnull URL resourceUrl) {
    // For maven cross package use case, we need to extract the resource from jar to a temporary directory.
    String resourceUrlStr = resourceUrl.toString();
    if (resourceUrlStr.contains("jar!")) {
        try {//from  w w w  .  jav a  2 s . c  o m
            String extension = resourceUrlStr.substring(resourceUrlStr.lastIndexOf('.'));
            File tempFile = File.createTempFile("pinot-test-temp", extension);
            String tempFilePath = tempFile.getAbsolutePath();
            LOGGER.info("Extracting from " + resourceUrlStr + " to " + tempFilePath);
            FileUtils.copyURLToFile(resourceUrl, tempFile);
            return tempFilePath;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } else {
        return resourceUrl.getFile();
    }
}

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

public static boolean loadImage(final String imageKey, final URL imageUrl) {
    HttpEntity responseEntity = null;/*from   w w  w  .ja  v a2  s . c  o m*/
    InputStream contentInputStream = null;

    try {
        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 HttpGet httpGet = new HttpGet(imageUrlString);
        final HttpResponse response = httpClient.execute(httpGet);

        responseEntity = response.getEntity();
        if (responseEntity == null) {
            throw new Exception("No response entity for image: " + imageUrl.toString());
        }
        contentInputStream = responseEntity.getContent();
        if (contentInputStream == null) {
            throw new Exception("No content stream for image: " + imageUrl.toString());
        }

        Bitmap bitmap = BitmapFactory.decodeStream(contentInputStream);
        ImageCache.saveImageInFileCache(imageKey, bitmap);
        LogWrapper.logMessage("Downloaded image: " + imageUrl.toString());
        bitmap.recycle();
    } catch (IOException e) {
        LogWrapper.logException(e);
        return false;
    } catch (Exception e) {
        LogWrapper.logException(e);
        return false;
    } finally {
        try {
            if (contentInputStream != null) {
                contentInputStream.close();
            }
            if (responseEntity != null) {
                responseEntity.consumeContent();
            }
        } catch (IOException e) {
            LogWrapper.logException(e);
        }
    }

    return true;
}

From source file:com.qualogy.qafe.web.ContextLoader.java

private static void create(ServletContext servletContext) throws MalformedURLException, URISyntaxException {
    String configLocation = servletContext.getInitParameter(CONFIG_FILE_PARAM);
    String contextPath = getContextPath(servletContext);
    QafeConfigurationManager contextInitialiser = new QafeConfigurationManager(contextPath);
    ApplicationContext springContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(servletContext);
    contextInitialiser.setSpringContext(springContext);
    qafeContext.putInstance(QafeConfigurationManager.class.getName(), contextInitialiser);

    StopWatch watch = new StopWatch();
    watch.start();/*from   w  w w . j  av  a  2s  .com*/
    ApplicationContextLoader.unload();

    // The default way: works on JBoss/Tomcat/Jetty
    String configFileLocation = servletContext.getRealPath("/WEB-INF/");
    if (configFileLocation != null) {
        configFileLocation += File.separator + configLocation;
        logger.log(Level.INFO, "URL to config file on disk :" + configFileLocation + ")");
        ApplicationContextLoader.load(configFileLocation, true);
    } else {
        // This is how a weblogic explicitly wants the fetching of resources.
        URL url = servletContext.getResource("/WEB-INF/" + configLocation);
        logger.log(Level.INFO, "Fallback scenario" + url.toString());
        if (url != null) {
            logger.log(Level.INFO, "URL to config file " + url.toString());
            ApplicationContextLoader.load(url.toURI(), true);
        } else {
            throw new RuntimeException(
                    "Strange Error: /WEB-INF/ cannot be found. Check the appserver or installation directory.");
        }
    }

    watch.stop();
    logger.log(Level.INFO,
            "Root WebApplicationContext: initialization completed in " + watch.getTime() + " ms");
}

From source file:com.bfd.harpc.common.configure.PathUtils.java

/**
 * ??URL?class/*  www  .  java2  s .c  o  m*/
 * <p>
 * <b>NOTE:</b><br />
 * warfile:/path/my-app/calsses/ <br />
 * jarfile:/path/my-app/my-app.jar.
 * 
 * @return URL
 */
public static URL getCodeLocation(Class<?> clazz) {
    URL codeLocation = null;
    // If CodeSource didn't work, Class.getResource
    // instead.
    URL r = clazz.getResource("");
    synchronized (r) {
        String s = r.toString();
        Pattern jrare = Pattern.compile("jar:\\s?(.*)!/.*");
        Matcher m = jrare.matcher(s);
        if (m.find()) { // the code is run from a jar file.
            s = m.group(1);
        } else {
            String p = clazz.getPackage().getName().replace('.', '/');
            s = s.substring(0, s.lastIndexOf(p));
        }
        try {
            codeLocation = new URL(s);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }
    return codeLocation;
}

From source file:com.concursive.connect.web.modules.admin.utils.AdminPortalUtils.java

public static DashboardPage retrieveDashboardPage(AdminPortalBean portalBean) throws Exception {

    // Use the admin-portal-config.xml to determine the dashboard page to use for the current url
    URL resource = AdminPortalUtils.class.getResource("/portal/admin-portal-config.xml");
    LOG.debug("portal config file: " + resource.toString());
    XMLUtils library = new XMLUtils(resource);

    // The nodes are listed under the <module> tag
    Element portal = XMLUtils.getFirstChild(library.getDocumentElement(), "portal", "type", "controller");

    String moduleLayout = null;/*w  ww  . jav  a  2s . c o m*/
    String page = null;

    // Look through the modules
    NodeList moduleNodeList = portal.getElementsByTagName("module");
    for (int i = 0; i < moduleNodeList.getLength(); i++) {
        Node thisModule = moduleNodeList.item(i);

        NodeList urlNodeList = ((Element) thisModule).getElementsByTagName("url");
        for (int j = 0; j < urlNodeList.getLength(); j++) {
            Element urlElement = (Element) urlNodeList.item(j);

            // Construct a AdminPortalURL and add to the list for retrieving
            String name = urlElement.getAttribute("name");

            // <url name="/show" object="/" page="default"/>
            if (name.equals("/" + portalBean.getAction())) {
                String object = urlElement.getAttribute("object");
                if (object.equals("/" + portalBean.getDomainObject())) {
                    // Set the module for tab highlighting
                    portalBean.setModule(((Element) thisModule).getAttribute("name"));

                    // Set the page for looking up
                    page = urlElement.getAttribute("page");

                    // Set the layout filename to find the referenced page
                    moduleLayout = ((Element) thisModule).getAttribute("layout");

                    break;
                }
            }
        }
    }

    URL moduleResource = AdminPortalUtils.class.getResource("/portal/" + moduleLayout);
    LOG.debug("module config file: " + moduleResource.toString());
    XMLUtils module = new XMLUtils(moduleResource);

    Element moduleElement = XMLUtils.getFirstChild(module.getDocumentElement(), "controller");

    NodeList pageNodeList = moduleElement.getElementsByTagName("page");
    if (pageNodeList.getLength() == 0) {
        LOG.warn("No pages found in moduleLayout: " + moduleLayout);
    }

    for (int j = 0; j < pageNodeList.getLength(); j++) {
        Node thisPage = pageNodeList.item(j);

        String pageName = ((Element) thisPage).getAttribute("name");

        if (pageName.equals(page)) {
            LOG.debug("Found page " + pageName);

            // Find a portal template to use
            LOG.debug("Trying a specific portal: " + page);
            DashboardPage dashboardPage = DashboardUtils.loadDashboardPage(
                    DashboardTemplateList.TYPE_CONTROLLER, (portalBean.isPopup() ? page + "-popup" : page),
                    moduleLayout);
            if (dashboardPage == null) {
                LOG.warn("Page not found: " + page);
                return null;
            }
            return dashboardPage;
        }
    }
    return null;
}

From source file:org.lorislab.armonitor.client.MonitorClient.java

/**
 * Creates the monitor service./*from  w w w  .j  av a2 s . c  o  m*/
 *
 * @param url the URL.
 * @param username the user name.
 * @param password the password.
 * @return the monitor service.
 */
private static MonitorService createService(URL url, String username, String password, boolean auth) {
    ResteasyProviderFactory rpf = ResteasyProviderFactory.getInstance();
    RegisterBuiltin.register(rpf);

    String tmp = url.toString();
    if (!tmp.endsWith("/")) {
        tmp = tmp + "/";
    }
    tmp = tmp + APP_URL;

    if (auth) {
        Credentials credentials = new UsernamePasswordCredentials(username, password);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        BasicCredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(AuthScope.ANY, credentials);
        httpClient.setCredentialsProvider(provider);
        return ProxyFactory.create(MonitorService.class, tmp, new ApacheHttpClient4Executor(httpClient));
    }
    return ProxyFactory.create(MonitorService.class, tmp);
}