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:org.wikimedia.analytics.kraken.pig.CanonicalizeArticleTitleTest.java

@Test
public void testSemiColonInUri() throws URISyntaxException, MalformedURLException {
    // A bug in Apache HttpComponents 4.0.x means
    // that it is not properly handling semicolons to separate key/values
    // in a query String. The solution is to replace the semicolon with an
    // ampersand.

    String urlString = "http://m.heise.de/newsticker/meldung/TomTom-baut-um-1643641.html?mrw_channel=ho;mrw_channel=ho;from-classic=1";
    URL url = new URL(urlString.replace(";", "&"));
    URLEncodedUtils.parse(url.toURI(), "utf-8");
}

From source file:io.anserini.doc.GenerateRegressionDocsTest.java

@Test
public void main() throws Exception {
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    URL resource = GenerateRegressionDocsTest.class.getResource("/regression/all.yaml");
    DataModel data = mapper.readValue(Paths.get(resource.toURI()).toFile(), DataModel.class);
    //System.out.println(ReflectionToStringBuilder.toString(data, ToStringStyle.MULTI_LINE_STYLE));

    for (String collection : data.getCollections().keySet()) {
        Map<String, String> valuesMap = new HashMap<>();
        valuesMap.put("index_cmds", data.generateIndexingCommand(collection));
        valuesMap.put("ranking_cmds", data.generateRankingCommand(collection));
        valuesMap.put("eval_cmds", data.generateEvalCommand(collection));
        valuesMap.put("effectiveness", data.generateEffectiveness(collection));
        StrSubstitutor sub = new StrSubstitutor(valuesMap);
        URL template = GenerateRegressionDocsTest.class
                .getResource(String.format("/docgen/templates/%s.template", collection));
        Scanner scanner = new Scanner(Paths.get(template.toURI()).toFile(), "UTF-8");
        String text = scanner.useDelimiter("\\A").next();
        scanner.close();//from ww  w.ja  v a  2  s .com
        String resolvedString = sub.replace(text);

        FileUtils.writeStringToFile(new File(String.format("docs/experiments-%s.md", collection)),
                resolvedString, "UTF-8");
    }
}

From source file:org.wikimedia.analytics.kraken.pig.CanonicalizeArticleTitleTest.java

@Test
public void test() throws URISyntaxException, MalformedURLException {
    //URL url = new URL("http://en.wikipedia.org/w/index.php?search=symptoms+of+vitamin+d+deficiency&title=Special%3ASearch");
    URL url = new URL("http://en.wikipedia.org/w/index.php?");
    URLEncodedUtils.parse(url.toURI(), "utf-8");
}

From source file:org.openmrs.module.webservices.rest.web.RestUtil.java

/**
 * Gets a list of classes in a given package. Note that interfaces are not returned.
 * /*from   www  .j a  v  a2 s . c  o m*/
 * @param pkgname the package name.
 * @param suffix the ending text on name. eg "Resource.class"
 * @return the list of classes.
 */
public static ArrayList<Class<?>> getClassesForPackage(String pkgname, String suffix) throws IOException {
    ArrayList<Class<?>> classes = new ArrayList<Class<?>>();

    //Get a File object for the package
    File directory = null;
    String relPath = pkgname.replace('.', '/');
    Enumeration<URL> resources = OpenmrsClassLoader.getInstance().getResources(relPath);
    while (resources.hasMoreElements()) {

        URL resource = resources.nextElement();
        if (resource == null) {
            throw new RuntimeException("No resource for " + relPath);
        }

        try {
            directory = new File(resource.toURI());
        } catch (URISyntaxException e) {
            throw new RuntimeException(pkgname + " (" + resource
                    + ") does not appear to be a valid URL / URI.  Strange, since we got it from the system...",
                    e);
        } catch (IllegalArgumentException ex) {
            //ex.printStackTrace();
        }

        //If folder exists, look for all resource class files in it.
        if (directory != null && directory.exists()) {

            //Get the list of the files contained in the package
            String[] files = directory.list();

            for (int i = 0; i < files.length; i++) {

                //We are only interested in Resource.class files
                if (files[i].endsWith(suffix)) {

                    //Remove the .class extension
                    String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6);

                    try {
                        Class<?> cls = Class.forName(className);
                        if (!cls.isInterface())
                            classes.add(cls);
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException("ClassNotFoundException loading " + className);
                    }
                }
            }
        } else {

            //Directory does not exist, look in jar file.
            try {
                String fullPath = resource.getFile();
                String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
                JarFile jarFile = new JarFile(jarPath);

                Enumeration<JarEntry> entries = jarFile.entries();
                while (entries.hasMoreElements()) {
                    JarEntry entry = entries.nextElement();

                    String entryName = entry.getName();

                    if (!entryName.endsWith(suffix))
                        continue;

                    if (entryName.startsWith(relPath)
                            && entryName.length() > (relPath.length() + "/".length())) {
                        String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");

                        try {
                            Class<?> cls = Class.forName(className);
                            if (!cls.isInterface())
                                classes.add(cls);
                        } catch (ClassNotFoundException e) {
                            throw new RuntimeException("ClassNotFoundException loading " + className);
                        }
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(
                        pkgname + " (" + directory + ") does not appear to be a valid package", e);
            }
        }
    }

    return classes;
}

From source file:au.org.ala.delta.confor.ErrorsTest.java

private File urlToFile(String urlString) throws Exception {
    URL url = ErrorsTest.class.getResource(urlString);
    File file = new File(url.toURI());
    return file;//  w w w . j  a v  a  2s  .co m
}

From source file:org.opencastproject.util.IoSupport.java

/**
 * Convenience method to read in a file from either a remote or local source.
 *
 * @param url// w ww .  j  av  a2  s  .  co m
 *         The {@code URL} to read the source data from.
 * @param trustedClient
 *         The {@code TrustedHttpClient} which should be used to communicate with the remote server. This can be null
 *         for local file reads.
 * @return A String containing the source data or null in the case of an error.
 * @deprecated this method doesn't support UTF8 or handle HTTP response codes
 */
public static String readFileFromURL(URL url, TrustedHttpClient trustedClient) {
    StringBuilder sb = new StringBuilder();
    DataInputStream in = null;
    HttpResponse response = null;
    try {
        // Do different things depending on what we're reading...
        if ("file".equals(url.getProtocol())) {
            in = new DataInputStream(url.openStream());
        } else {
            if (trustedClient == null) {
                logger.error("Unable to read from remote source {} because trusted client is null!",
                        url.getFile());
                return null;
            }
            HttpGet get = new HttpGet(url.toURI());
            try {
                response = trustedClient.execute(get);
            } catch (TrustedHttpClientException e) {
                logger.warn("Unable to fetch file from {}.", url, e);
                trustedClient.close(response);
                return null;
            }
            in = new DataInputStream(response.getEntity().getContent());
        }
        int c = 0;
        while ((c = in.read()) != -1) {
            sb.append((char) c);
        }
    } catch (IOException e) {
        logger.warn("IOException attempting to get file from {}.", url);
        return null;
    } catch (URISyntaxException e) {
        logger.warn("URI error attempting to get file from {}.", url);
        return null;
    } catch (NullPointerException e) {
        logger.warn("Nullpointer attempting to get file from {}.", url);
        return null;
    } finally {
        IOUtils.closeQuietly(in);

        if (response != null && trustedClient != null) {
            trustedClient.close(response);
            response = null;
        }
    }

    return sb.toString();
}

From source file:com.stratio.explorer.reader.FileConfByNameFileLocator.java

/**
 * Constructor init with folder of class.
 *///from w  w w.jav a 2s . c  o  m
public FileConfByNameFileLocator() {
    try {
        URL url = getClass().getClassLoader().getResource(".");
        folder = new File(url.toURI().getPath());
    } catch (URISyntaxException e) {
        Logger.error("Class FileConfLocator have not been  loaded ");
    }
}

From source file:com.synopsys.integration.blackduck.rest.BlackDuckHttpClient.java

public BlackDuckHttpClient(IntLogger logger, int timeout, boolean alwaysTrustServerCertificate,
        ProxyInfo proxyInfo, String baseUrl) {
    super(logger, timeout, alwaysTrustServerCertificate, proxyInfo);
    this.baseUrl = baseUrl;

    if (StringUtils.isBlank(baseUrl)) {
        throw new IllegalArgumentException("No base url was provided.");
    } else {/*w  ww  . j  a  v  a2 s. co  m*/
        try {
            URL url = new URL(baseUrl);
            url.toURI();
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("The provided base url is not a valid java.net.URL.", e);
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("The provided base url is not a valid java.net.URI.", e);
        }
    }
}

From source file:au.org.ala.delta.delfor.DelforTest.java

private File urlToFile(String urlString) throws Exception {
    URL url = DelforTest.class.getResource(urlString);
    File file = new File(url.toURI());
    return file;/*  w w w . j av  a 2s . c  o  m*/
}