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:eu.planets_project.tb.impl.services.ServiceRegistryManager.java

/**
 * As the wsdlcontent is not well-formed we're not able to use DOM here.
 * Parse through the xml manually to return a list of given ServiceEndpointAddresses
 * @param xhtml/*  w w  w .j av a  2 s  .  c o  m*/
 * @return
 * @throws Exception
 */
@Deprecated
private static Set<URI> extractEndpointsFromWebPage(String xhtml) {
    Set<URI> ret = new HashSet<URI>();

    // Pull out all matching URLs:
    Matcher matcher = urlpattern.matcher(xhtml);
    while (matcher.find()) {
        //log.info("Found match: "+matcher.group());
        try {
            URL wsdlUrl = new URL(matcher.group());
            // Switch the authority for the 'proper' one:
            wsdlUrl = new URL(wsdlUrl.getProtocol(), PlanetsServerConfig.getHostname(),
                    PlanetsServerConfig.getPort(), wsdlUrl.getFile());
            //log.info("Got matching URL: "+wsdlUrl);
            try {
                ret.add(wsdlUrl.toURI());
            } catch (URISyntaxException e) {
            }
        } catch (MalformedURLException e) {
            log.warn("Could not parse URL from " + matcher.group());
        }
    }

    return ret;
}

From source file:org.apache.hadoop.gateway.GatewayMultiFuncTest.java

public static void setupLdap() throws Exception {
    URL usersUrl = TestUtils.getResourceUrl(DAT, "users.ldif");
    ldapTransport = new TcpTransport(0);
    ldap = new SimpleLdapDirectoryServer("dc=hadoop,dc=apache,dc=org", new File(usersUrl.toURI()),
            ldapTransport);//from   w w  w. jav  a  2 s .  co  m
    ldap.start();
    LOG.info("LDAP port = " + ldapTransport.getAcceptor().getLocalAddress().getPort());
}

From source file:org.wso2.bam.integration.tests.reciever.RESTAPITestCase.java

private static String[] getHiveQueries(String resourceName) {
    String[] queries = null;/*from   www  . j a  v a  2 s  .c om*/
    try {
        initializeHiveStub();
    } catch (Exception e) {
        e.printStackTrace();
        fail("Error while initializing hive stub: " + e.getMessage());
    }

    URL url = RESTAPITestCase.class.getClassLoader().getResource(resourceName);

    try {
        BufferedReader bufferedReader = new BufferedReader(
                new FileReader(new File(url.toURI()).getAbsolutePath()));
        String script = "";
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            script += line;
        }
        queries = script.split(";");
    } catch (Exception e) {
        fail("Error while reading resource : " + resourceName);
    }
    return queries;
}

From source file:com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfigurationTest.java

/**
 * Return the classes inside the specified package and its sub-packages.
 * @param klass a class inside that package
 * @return a list of class names//from  www .jav a  2 s  .  c o m
 */
public static List<String> getClassesForPackage(final Class<?> klass) {
    final List<String> list = new ArrayList<>();

    File directory = null;
    final String relPath = klass.getName().replace('.', '/') + ".class";

    final URL resource = JavaScriptConfiguration.class.getClassLoader().getResource(relPath);

    if (resource == null) {
        throw new RuntimeException("No resource for " + relPath);
    }
    final String fullPath = resource.getFile();

    try {
        directory = new File(resource.toURI()).getParentFile();
    } catch (final URISyntaxException e) {
        throw new RuntimeException(klass.getName() + " (" + resource + ") does not appear to be a valid URL",
                e);
    } catch (final IllegalArgumentException e) {
        directory = null;
    }

    if (directory != null && directory.exists()) {
        addClasses(directory, klass.getPackage().getName(), list);
    } else {
        try {
            String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
            if (System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win")) {
                jarPath = jarPath.replace("%20", " ");
            }
            final JarFile jarFile = new JarFile(jarPath);
            for (final Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
                final String entryName = entries.nextElement().getName();
                if (entryName.endsWith(".class")) {
                    list.add(entryName.replace('/', '.').replace('\\', '.').replace(".class", ""));
                }
            }
            jarFile.close();
        } catch (final IOException e) {
            throw new RuntimeException(klass.getPackage().getName() + " does not appear to be a valid package",
                    e);
        }
    }
    return list;
}

From source file:com.mpower.mintel.android.utilities.WebUtils.java

/**
 * Common method for returning a parsed xml document given a url and the
 * http context and client objects involved in the web connection.
 * //ww w .  j a  v  a2 s .c  o m
 * @param urlString
 * @param localContext
 * @param httpclient
 * @return
 */
public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext,
        HttpClient httpclient, String auth) {
    URI u = null;
    try {
        URL url = new URL(URLDecoder.decode(urlString, "utf-8"));
        u = url.toURI();
    } catch (Exception e) {
        e.printStackTrace();
        return new DocumentFetchResult(e.getLocalizedMessage()
                // + app.getString(R.string.while_accessing) + urlString);
                + ("while accessing") + urlString, 0);
    }

    // set up request...
    HttpGet req = WebUtils.createOpenRosaHttpGet(u, auth);

    HttpResponse response = null;
    try {
        response = httpclient.execute(req, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();

        if (entity != null && (statusCode != 200 || !entity.getContentType().getValue().toLowerCase()
                .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML))) {
            try {
                // don't really care about the stream...
                InputStream is = response.getEntity().getContent();
                // read to end of stream...
                final long count = 1024L;
                while (is.skip(count) == count)
                    ;
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (statusCode != 200) {
            String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")";

            return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode);
        }

        if (entity == null) {
            String error = "No entity body returned from: " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        if (!entity.getContentType().getValue().toLowerCase().contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) {
            String error = "ContentType: " + entity.getContentType().getValue() + " returned from: "
                    + u.toString()
                    + " is not text/xml.  This is often caused a network proxy.  Do you need to login to your network?";
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        // parse response
        Document doc = null;
        try {
            InputStream is = null;
            InputStreamReader isr = null;
            try {
                is = entity.getContent();
                isr = new InputStreamReader(is, "UTF-8");
                doc = new Document();
                KXmlParser parser = new KXmlParser();
                parser.setInput(isr);
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
                doc.parse(parser);
                isr.close();
            } finally {
                if (isr != null) {
                    try {
                        isr.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                        // no-op
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString();
            Log.e(t, error);
            return new DocumentFetchResult(error, 0);
        }

        boolean isOR = false;
        Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER);
        if (fields != null && fields.length >= 1) {
            isOR = true;
            boolean versionMatch = false;
            boolean first = true;
            StringBuilder b = new StringBuilder();
            for (Header h : fields) {
                if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) {
                    versionMatch = true;
                    break;
                }
                if (!first) {
                    b.append("; ");
                }
                first = false;
                b.append(h.getValue());
            }
            if (!versionMatch) {
                Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString());
            }
        }
        return new DocumentFetchResult(doc, isOR);
    } catch (Exception e) {
        e.printStackTrace();
        String cause;
        if (e.getCause() != null) {
            cause = e.getCause().getMessage();
        } else {
            cause = e.getMessage();
        }
        String error = "Error: " + cause + " while accessing " + u.toString();

        Log.w(t, error);
        return new DocumentFetchResult(error, 0);
    }
}

From source file:uk.ac.cam.cl.dtg.picky.client.analytics.Analytics.java

private static void upload(Properties properties, String datasetURL) {
    if (datasetURL == null)
        return;// w ww  .  j a  v a2  s. c om
    URL url;

    try {
        url = new URL(new URL(datasetURL), URL);
    } catch (MalformedURLException e1) {
        e1.printStackTrace();
        return;
    }

    try {
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpPost post = new HttpPost(url.toURI());
        post.setHeader("Content-Type", "text/plain; charset=utf-8");

        StringWriter stringWriter = new StringWriter();
        properties.store(stringWriter, "");

        HttpEntity entity = new StringEntity(stringWriter.toString());
        post.setEntity(entity);

        HttpResponse response = client.execute(post);

        LOG.info("Uploading analytics: " + response.getStatusLine());
    } catch (IOException | URISyntaxException e) {
        LOG.error(e.getMessage());
    }
}

From source file:net.rptools.lib.FileUtil.java

public static String getNameWithoutExtension(URL url) {
    String file = url.getFile();/*from   w  ww.  j av a  2s.  co  m*/
    try {
        file = url.toURI().getPath();
        //         int beginning = file.lastIndexOf(File.separatorChar); // Don't need to strip the path since the File() constructor will take care of that
        //         file = file.substring(beginning < 0 ? 0 : beginning + 1);
    } catch (URISyntaxException e) {
        // If the conversion doesn't work, ignore it and use the original file name.
    }
    return getNameWithoutExtension(new File(file));
}

From source file:org.dkpro.lab.Util.java

/**
 * Make the given URL available as a file. A temporary file is created and
 * deleted upon a regular shutdown of the JVM. If the parameter {@code
 * aCache} is {@code true}, the temporary file is remembered in a cache and
 * if a file is requested for the same URL at a later time, the same file is
 * returned again. If the previously created file has been deleted
 * meanwhile, it is recreated from the URL.
 *
 * @param aUrl//from   w  w  w  .java 2  s  .  co m
 *            the URL.
 * @param aCache
 *            use the cache or not.
 * @return a file created from the given URL.
 * @throws IOException
 *             if the URL cannot be accessed to (re)create the file.
 */
public static synchronized File getUrlAsFile(URL aUrl, boolean aCache) throws IOException {
    // If the URL already points to a file, there is not really much to do.
    if ("file".equals(aUrl.getProtocol())) {
        try {
            return new File(aUrl.toURI());
        } catch (URISyntaxException e) {
            throw new IOException(e);
        }
    }

    // Lets see if we already have a file for this URL in our cache. Maybe
    // the file has been deleted meanwhile, so we also check if the file
    // actually still exists on disk.
    File file = urlFileCache.get(aUrl);
    if (!aCache || (file == null) || !file.exists()) {
        // Create a temporary file and try to preserve the file extension
        String suffix = ".temp";
        String name = new File(aUrl.getPath()).getName();
        int suffixSep = name.indexOf(".");
        if (suffixSep != -1) {
            suffix = name.substring(suffixSep + 1);
            name = name.substring(0, suffixSep);
        }

        // Get a temporary file which will be deleted when the JVM shuts
        // down.
        file = File.createTempFile(name, suffix);
        file.deleteOnExit();

        // Now copy the file from the URL to the file.
        shoveAndClose(aUrl.openStream(), new FileOutputStream(file));

        // Remember the file
        if (aCache) {
            urlFileCache.put(aUrl, file);
        }
    }

    return file;
}

From source file:it.geosolutions.geostore.core.security.password.URLMasterPasswordProvider.java

static InputStream input(URL url, File configDir) throws IOException {
    //check for a file url
    if (url == null) {
        //default master password
        url = URLMasterPasswordProvider.class.getClassLoader().getResource("passwd");
    }/*from   w w  w . j a  v a 2 s  .c om*/
    if ("file".equalsIgnoreCase(url.getProtocol())) {
        File f;
        try {
            f = new File(url.toURI());
        } catch (URISyntaxException e) {
            f = new File(url.getPath());
        }

        //check if the file is relative
        if (!f.isAbsolute()) {
            //make it relative to the config directory for this password provider
            f = new File(configDir, f.getPath());
        }
        return new FileInputStream(f);
    } else {
        return url.openStream();
    }
}

From source file:spark.protocol.SparqlCall.java

/**
 * Executes a SPARQL HTTP protocol request for the given command, and returns the response.
 * @param command The SPARQL protocol command.
 * @return The HTTP response.//  w w  w . j ava  2s.  c  o m
 */
static HttpResponse executeRequest(ProtocolCommand command, String mimeType) {
    HttpClient client = ((ProtocolConnection) command.getConnection()).getHttpClient();
    URL url = ((ProtocolDataSource) command.getConnection().getDataSource()).getUrl();
    HttpUriRequest req;

    try {
        String params = "query=" + encode(command.getCommand());
        String u = url.toString() + "?" + params;
        if (u.length() > QUERY_LIMIT) {
            // POST connection
            try {
                req = new HttpPost(url.toURI());
            } catch (URISyntaxException e) {
                throw new SparqlException("Endpoint <" + url + "> not in an acceptable format", e);
            }
            ((HttpPost) req).setEntity((HttpEntity) new StringEntity(params));
        } else {
            // GET connection
            req = new HttpGet(u);
        }

        if (command.getTimeout() != Command.NO_TIMEOUT) {
            HttpParams reqParams = new BasicHttpParams();
            HttpConnectionParams.setSoTimeout(reqParams, (int) (command.getTimeout() * 1000));
            req.setParams(reqParams);
        }

        // Add Accept and Content-Type (for POST'ed queries) headers to the request.
        addHeaders(req, mimeType);

        // There's a small chance the request could be aborted before it's even executed, we'll have to live with that.
        command.setRequest(req);

        //dump(client, req);
        HttpResponse response = client.execute(req);
        StatusLine status = response.getStatusLine();
        int code = status.getStatusCode();

        // TODO the client doesn't handle redirects for posts; should we do that here?

        if (code >= SUCCESS_MIN && code <= SUCCESS_MAX) {
            return response;
        } else {
            throw new SparqlException("Unexpected status code in server response: " + status.getReasonPhrase()
                    + "(" + code + ")");
        }
    } catch (UnsupportedEncodingException e) {
        throw new SparqlException("Unabled to encode data", e);
    } catch (ClientProtocolException cpe) {
        throw new SparqlException("Error in protocol", cpe);
    } catch (IOException e) {
        throw new SparqlException(e);
    }
}