Example usage for java.net URL toURI

List of usage examples for java.net URL toURI

Introduction

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

Prototype

public URI toURI() throws URISyntaxException 

Source Link

Document

Returns a java.net.URI equivalent to this URL.

Usage

From source file:net.librec.util.FileUtil.java

/**
 * Return the BufferedReader List of files in a specified directory.
 *
 * @param path The path of the specified directory or file.
 *             Relative and absolute paths are both supported.
 * @return the BufferedReader List of files.
 * @throws IOException         if I/O error occurs
 * @throws URISyntaxException  if URI Syntax error occurs
 *//*from   w  w w  . j  a  v a2s. c  o  m*/
public static List<BufferedReader> getReader(String path) throws IOException, URISyntaxException {
    File file = new File(path);
    List<BufferedReader> readerList = new ArrayList<BufferedReader>();

    boolean isRelativePath = !(path.startsWith("/") || path.indexOf(":") > 0);

    if (isRelativePath) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        if (classLoader == null) {
            classLoader = FileUtil.class.getClassLoader();
        }
        URL url = classLoader.getResource(path);
        if (null != url) {
            file = new File(url.toURI());
        }
    }

    if (file.isFile()) {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        readerList.add(reader);
    } else if (file.isDirectory()) {
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                BufferedReader reader = new BufferedReader(new FileReader(files[i]));
                readerList.add(reader);
            }
        }
    }
    return readerList;
}

From source file:ca.sqlpower.wabit.enterprise.client.ServerInfoProvider.java

private static void init(String host, String port, String path, String username, String password)
        throws IOException {

    URL serverInfoUrl = toServerInfoURL(host, port, path);
    if (version.containsKey(generateServerKey(host, port, path, username, password)))
        return;// w w  w  . ja v  a2s  .c  om

    try {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 2000);
        DefaultHttpClient httpClient = new DefaultHttpClient(params);
        httpClient.setCookieStore(WabitClientSession.getCookieStore());
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(serverInfoUrl.getHost(), AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        HttpUriRequest request = new HttpOptions(serverInfoUrl.toURI());
        String responseBody = httpClient.execute(request, new BasicResponseHandler());

        // Decode the message
        String serverVersion;
        Boolean licensedServer;
        final String watermarkMessage;
        try {
            JSONObject jsonObject = new JSONObject(responseBody);
            serverVersion = jsonObject.getString(ServerProperties.SERVER_VERSION.toString());
            licensedServer = jsonObject.getBoolean(ServerProperties.SERVER_LICENSED.toString());
            watermarkMessage = jsonObject.getString(ServerProperties.SERVER_WATERMARK_MESSAGE.toString());
        } catch (JSONException e) {
            throw new IOException(e.getMessage());
        }

        // Save found values
        version.put(generateServerKey(host, port, path, username, password), new Version(serverVersion));
        licenses.put(generateServerKey(host, port, path, username, password), licensedServer);
        watermarkMessages.put(generateServerKey(host, port, path, username, password), watermarkMessage);

        // Notify the user if the server is not licensed.
        if (!licensedServer) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JOptionPane.showMessageDialog(null, watermarkMessage, "SQL Power Wabit Server License",
                            JOptionPane.WARNING_MESSAGE);
                }
            });
        }

        // Now get the available fonts.
        URL serverFontsURL = toServerFontsURL(host, port, path);
        HttpUriRequest fontsRequest = new HttpGet(serverFontsURL.toURI());
        String fontsResponseBody = httpClient.execute(fontsRequest, new BasicResponseHandler());
        try {
            JSONArray fontsArray = new JSONArray(fontsResponseBody);
            List<String> fontNames = new ArrayList<String>();
            for (int i = 0; i < fontsArray.length(); i++) {
                fontNames.add(fontsArray.getString(i));
            }
            // Sort the list.
            Collections.sort(fontNames);
            fonts.put(generateServerKey(host, port, path, username, password), fontNames);
        } catch (JSONException e) {
            throw new IOException(e.getMessage());
        }

    } catch (URISyntaxException e) {
        throw new IOException(e.getLocalizedMessage());
    }
}

From source file:com.datatorrent.stram.client.StramClientUtils.java

public static File getInstallationDir() {
    URL resource = StramClientUtils.class.getClassLoader().getResource(DT_ENV_SH_FILE);
    try {/*from  w  ww. j ava2 s  .  co m*/
        if (resource == null) {
            return null;
        }
        return new File(resource.toURI()).getParentFile().getParentFile();
    } catch (URISyntaxException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.datatorrent.stram.client.StramClientUtils.java

public static File getConfigDir() {
    URL resource = StramClientUtils.class.getClassLoader().getResource(DT_ENV_SH_FILE);
    try {/*from  w  w  w.  j av  a  2 s  .c  o m*/
        if (resource == null) {
            return getUserDTDirectory();
        }
        return new File(resource.toURI()).getParentFile();
    } catch (URISyntaxException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.erudika.para.utils.Utils.java

/**
 * The basic URL without any parameters: &gt;scheme&lt;:&gt;authority&lt;
 * @param url a full URL//from  w ww .  ja v a  2s  . c  o m
 * @return the basic URL
 */
public static String getBaseURL(String url) {
    URL u = toURL(url);
    String base = null;
    if (u != null) {
        try {
            base = u.toURI().getScheme().concat("://").concat(u.getAuthority());
        } catch (URISyntaxException ex) {
            base = null;
        }
    }
    return base;
}

From source file:de.javakaffee.web.msm.integration.TestUtils.java

private static void initLogConfig(final Class<? extends TestUtils> clazz) {
    final URL loggingProperties = clazz.getResource("/logging.properties");
    try {/*from w  w w .j  a  v a 2  s.  co  m*/
        System.setProperty("java.util.logging.config.file",
                new File(loggingProperties.toURI()).getAbsolutePath());
    } catch (final Exception e) {
        // we don't have a plain file (e.g. the case for msm-kryo-serializer etc), so we can skip reading the config
        return;
    }
    try {
        LogManager.getLogManager().readConfiguration();
    } catch (final Exception e) {
        LogFactory.getLog(TestUtils.class).error("Could not init logging configuration.", e);
    }
}

From source file:jp.go.nict.langrid.management.logic.service.HttpClientUtil.java

/**
 * /*from   ww  w  . j a v  a 2  s. c  om*/
 * 
 */
public static HttpClient createHttpClientWithHostConfig(URL url) {
    HttpClient client = new HttpClient();
    int port = url.getPort();
    if (port == -1) {
        port = url.getDefaultPort();
        if (port == -1) {
            port = 80;
        }
    }
    if ((url.getProtocol().equalsIgnoreCase("https")) && (sslSocketFactory != null)) {
        Protocol https = new Protocol("https",
                (ProtocolSocketFactory) new SSLSocketFactorySSLProtocolSocketFactory(sslSocketFactory), port);
        client.getHostConfiguration().setHost(url.getHost(), url.getPort(), https);
    } else {
        Protocol http = new Protocol("http", new SocketFactoryProtocolSocketFactory(SocketFactory.getDefault()),
                port);
        client.getHostConfiguration().setHost(url.getHost(), url.getPort(), http);
    }
    try {
        List<Proxy> proxies = ProxySelector.getDefault().select(url.toURI());
        for (Proxy p : proxies) {
            if (p.equals(Proxy.NO_PROXY))
                continue;
            if (!p.type().equals(Proxy.Type.HTTP))
                continue;
            InetSocketAddress addr = (InetSocketAddress) p.address();
            client.getHostConfiguration().setProxy(addr.getHostName(), addr.getPort());
            break;
        }
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return client;
}

From source file:jp.go.nict.langrid.servicesupervisor.invocationprocessor.executor.intragrid.HttpClientUtil.java

/**
 * /*from ww w  .  j  av  a 2  s .co  m*/
 * 
 */
public static HttpClient createHttpClientWithHostConfig(URL url) {
    HttpClient client = new HttpClient();
    int port = url.getPort();
    if (port == -1) {
        port = url.getDefaultPort();
        if (port == -1) {
            port = 80;
        }
    }
    if ((url.getProtocol().equalsIgnoreCase("https")) && (sslSocketFactory != null)) {
        Protocol https = new Protocol("https",
                (ProtocolSocketFactory) new SSLSocketFactorySSLProtocolSocketFactory(sslSocketFactory), port);
        client.getHostConfiguration().setHost(url.getHost(), url.getPort(), https);
    } else {
        Protocol http = new Protocol("http", new SocketFactoryProtocolSocketFactory(SocketFactory.getDefault()),
                port);
        client.getHostConfiguration().setHost(url.getHost(), url.getPort(), http);
    }
    try {
        List<Proxy> proxies = ProxySelector.getDefault().select(url.toURI());
        for (Proxy p : proxies) {
            if (p.equals(Proxy.NO_PROXY))
                continue;
            if (!p.type().equals(Proxy.Type.HTTP))
                continue;
            InetSocketAddress addr = (InetSocketAddress) p.address();
            client.getHostConfiguration().setProxy(addr.getHostName(), addr.getPort());
            client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials("", ""));
            break;
        }
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return client;
}

From source file:gov.nasa.ensemble.common.io.FileUtilities.java

/**
 * Copy the entries specified from the bundle provided to the metadata area for the bundle provided, and return the URL for the metadata area for this bundle.
 * //  w w  w .  j  a  v  a2  s  . c o m
 * @param bundle
 * @param path
 * @param filePattern
 * @param recurse
 * @return URL
 * @throws IOException
 */
public static URL copyToMetadata(Bundle bundle, String path, String filePattern, boolean recurse)
        throws IOException {
    Location instanceLocation = Platform.getInstanceLocation();
    URL dataArea = getDataArea(instanceLocation, bundle.getSymbolicName());
    Enumeration entries = bundle.findEntries(path, filePattern, recurse);
    while (entries.hasMoreElements()) {
        URL entry = (URL) entries.nextElement();
        String entryPath = entry.getPath();
        try {
            InputStream inputStream = FileLocator.openStream(bundle, new Path(entryPath), false);
            URI dataURI = dataArea.toURI();
            URI fullPath = URI.create(dataURI.toString() + entryPath);
            File file = new File(fullPath);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            FileOutputStream outputStream = new FileOutputStream(file);
            IOUtils.copy(inputStream, outputStream);
            outputStream.close();
        } catch (Exception e) {
            // skip this one
        }
    }
    return dataArea;
}

From source file:com.github.wolf480pl.mias4j.util.AbstractTransformingClassLoader.java

public static URL guessCodeSourceURL(String resourcePath, URL resourceURL) {
    // FIXME: Find a better way to do this
    @SuppressWarnings("restriction")
    String escaped = sun.net.www.ParseUtil.encodePath(resourcePath, false);
    String path = resourceURL.getPath();
    if (!path.endsWith(escaped)) {
        // Umm... whadda we do now? Maybe let's fallback to full resource URL.
        LOG.warn("Resource URL path \"" + path + "\" doesn't end with escaped resource path \"" + escaped
                + "\" for resource \"" + resourcePath + "\"");
        return resourceURL;
    }/*from  w  ww .  j  a v a 2 s  .  c  o m*/
    path = path.substring(0, path.length() - escaped.length());
    if (path.endsWith("!/")) { // JAR
        path = path.substring(0, path.length() - 2);
    }
    try {
        URI uri = resourceURL.toURI();
        return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), path, uri.getQuery(),
                uri.getFragment()).toURL();
    } catch (MalformedURLException | URISyntaxException e) {
        // Umm... whadda we do now? Maybe let's fallback to full resource URL.
        LOG.warn("Couldn't assemble CodeSource URL with modified path", e);
        return resourceURL;
    }
}