Example usage for java.io File toURL

List of usage examples for java.io File toURL

Introduction

In this page you can find the example usage for java.io File toURL.

Prototype

@Deprecated
public URL toURL() throws MalformedURLException 

Source Link

Document

Converts this abstract pathname into a file: URL.

Usage

From source file:com.amalto.core.util.SecurityEntityResolver.java

public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    if (systemId != null) {
        Pattern httpUrl = Pattern.compile("(http|https|ftp):(\\//|\\\\)(.*):(.*)");
        Matcher match = httpUrl.matcher(systemId);
        if (match.matches()) {
            StringBuilder buffer = new StringBuilder();
            String credentials = new String(Base64.encodeBase64("admin:talend".getBytes()));
            URL url = new URL(systemId);
            URLConnection conn = url.openConnection();
            conn.setAllowUserInteraction(true);
            conn.setDoOutput(true);//from  w ww. j av a2 s. c o  m
            conn.setDoInput(true);
            conn.setRequestProperty("Authorization", "Basic " + credentials);
            conn.setRequestProperty("Expect", "100-continue");
            InputStreamReader doc = new InputStreamReader(conn.getInputStream());
            BufferedReader reader = new BufferedReader(doc);
            String line = reader.readLine();
            while (line != null) {
                buffer.append(line);
                line = reader.readLine();
            }
            return new InputSource(new StringReader(buffer.toString()));
        } else {
            int mark = systemId.indexOf("file:///");
            String path = systemId.substring((mark != -1 ? mark + "file:///".length() : 0));
            File file = new File(path);
            return new InputSource(file.toURL().openStream());
        }

    }
    return null;
}

From source file:org.apache.servicemix.war.deployer.WarDeploymentListener.java

public File transform(File artifact, File tmpDir) {
    try {// w  ww .  j a va2 s  .com
        URL war = new URL("war:" + artifact.toURL().toString());
        File outFile = new File(tmpDir, artifact.getName());
        IOUtils.copyAndClose(war.openStream(), new FileOutputStream(outFile));
        return outFile;

    } catch (Exception e) {
        LOGGER.error("Failed to transform the WAR artifact into an OSGi bundle");
        return null;
    }
}

From source file:JarUtils.java

/** Given a URL check if its a jar url(jar:<url>!/archive) and if it is,
 extract the archive entry into the given dest directory and return a file
 URL to its location. If jarURL is not a jar url then it is simply returned
 as the URL for the jar./*  www  . j a v a2  s  . com*/
        
 @param jarURL the URL to validate and extract the referenced entry if its
   a jar protocol URL
 @param dest the directory into which the nested jar will be extracted.
 @return the file: URL for the jar referenced by the jarURL parameter.
 * @throws IOException 
 */
public static URL extractNestedJar(URL jarURL, File dest) throws IOException {
    // This may not be a jar URL so validate the protocol 
    if (jarURL.getProtocol().equals("jar") == false)
        return jarURL;

    String destPath = dest.getAbsolutePath();
    URLConnection urlConn = jarURL.openConnection();
    JarURLConnection jarConn = (JarURLConnection) urlConn;
    // Extract the archive to dest/jarName-contents/archive
    String parentArchiveName = jarConn.getJarFile().getName();
    // Find the longest common prefix between destPath and parentArchiveName
    int length = Math.min(destPath.length(), parentArchiveName.length());
    int n = 0;
    while (n < length) {
        char a = destPath.charAt(n);
        char b = parentArchiveName.charAt(n);
        if (a != b)
            break;
        n++;
    }
    // Remove any common prefix from parentArchiveName
    parentArchiveName = parentArchiveName.substring(n);

    File archiveDir = new File(dest, parentArchiveName + "-contents");
    if (archiveDir.exists() == false && archiveDir.mkdirs() == false)
        throw new IOException(
                "Failed to create contents directory for archive, path=" + archiveDir.getAbsolutePath());
    String archiveName = jarConn.getEntryName();
    File archiveFile = new File(archiveDir, archiveName);
    File archiveParentDir = archiveFile.getParentFile();
    if (archiveParentDir.exists() == false && archiveParentDir.mkdirs() == false)
        throw new IOException(
                "Failed to create parent directory for archive, path=" + archiveParentDir.getAbsolutePath());
    InputStream archiveIS = jarConn.getInputStream();
    FileOutputStream fos = new FileOutputStream(archiveFile);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    byte[] buffer = new byte[4096];
    int read;
    while ((read = archiveIS.read(buffer)) > 0) {
        bos.write(buffer, 0, read);
    }
    archiveIS.close();
    bos.close();

    // Return the file url to the extracted jar
    return archiveFile.toURL();
}

From source file:utils.VocabularyFromFiles.java

public void parseWordInputCSV(String wordFileLocation, String bandColumnName, String wordColumnName,
        String ratingLabels, String correctResponse) throws IOException {
    File inputFileWords = new File(wordFileLocation);
    final Reader reader = new InputStreamReader(inputFileWords.toURL().openStream(), "UTF-8"); // todo: this might need to change to "ISO-8859-1" depending on the usage
    Iterable<CSVRecord> records = CSVFormat.newFormat(';').withHeader().parse(reader);

    for (CSVRecord record : records) {
        int bandNumber = Integer.parseInt(record.get(bandColumnName));
        String spelling = record.get(wordColumnName);
        String stimulusString = bandNumber + ";" + spelling;
        localWORDS.add(stimulusString);/*from   ww w  .  j a v a  2  s  .  com*/
    }
}

From source file:utils.VocabularyFromFiles.java

public void parseNonwordInputCSV(String nonwordFileLocation, String nonwordColumnName, String ratingLabels,
        String correctResponse) throws IOException {
    final File inputFileNonWords = new File(nonwordFileLocation);
    final Reader reader = new InputStreamReader(inputFileNonWords.toURL().openStream(), "UTF-8"); // todo: this might need to change to "ISO-8859-1" depending on the usage
    Iterable<CSVRecord> records = CSVFormat.newFormat(';').withHeader().parse(reader);
    for (CSVRecord record : records) {
        String spelling = record.get(nonwordColumnName);
        localNONWORDS.add(spelling);/*from  w  w w.  j a v  a  2 s .co m*/
    }

}

From source file:ItemSearcher.java

/**
 * <p>This method takes a file, and searches it for specific
 *   pieces of data using DOM traversal.</p>
 *
 * @param filename name of XML file to search through.
 * @throws <code>Exception</code> - generic problem handling.
 *//*from   ww w. ja  va 2s. com*/
public void search(String filename) throws Exception {
    // Parse into a DOM tree
    File file = new File(filename);
    DOMParser parser = new DOMParser();
    parser.parse(file.toURL().toString());
    Document doc = parser.getDocument();

    // Get node to start iterating with
    Element root = doc.getDocumentElement();
    NodeList descriptionElements = root.getElementsByTagNameNS(docNS, "description");
    Element description = (Element) descriptionElements.item(0);

    // Get a NodeIterator
    NodeIterator i = ((DocumentTraversal) doc).createNodeIterator(description, NodeFilter.SHOW_ALL,
            new FormattingNodeFilter(), true);

    Node n;
    while ((n = i.nextNode()) != null) {
        System.out.println("Search phrase found: '" + n.getNodeValue() + "'");
    }
}

From source file:com.autentia.tnt.bean.JPivotBean.java

public String showTable() {
    try {//from  w ww.  j a  v a 2 s.  com
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        File file = new File(loader.getResource("com/autentia/tnt/jpivot/jpivot_test.xml").toURI());
        cubeURL = file.toURL();

        String mdxQuery = "select {[Measures].[Muestras]} on columns , {([Contacto])} on rows from [Informe]";

        this.olapModel = JPivotUtils.executeOlapQuery(mdxQuery, cubeURL,
                (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false));
    } catch (Exception e) {
        log.error("cannot generate the jpivot cube: ", e);
        return "error";
    }

    return "jpivot";
}

From source file:WebstartLauncher.java

private String toURLFormat(File file) {
    try {//  www .j a v a 2  s .  c  o  m
        URL fileURL = file.toURL();
        return fileURL.toExternalForm();
    } catch (MalformedURLException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.mbari.aved.ui.utils.VideoUtils.java

/**
 * Helper function to import still image archive/video files to associate with a XML file
 *
 * @param source The image source URL associated with the xmlfile
 * @param xmlfile The xmlfile //w  w w  . j  ava  2 s .  c  om
 *
 * @returns the URL to the video source file it found or null if none found
 */
public static URL searchImageSource(File xmlfile, URL source) {

    // Convert input source associated with the XML to frames
    // and use these frames to start the image loader to
    // extract images of the events

    if (source != null) {
        try {
            boolean isValidUrl = URLUtils.isValidURL(source);
            if (isValidUrl) {

                // If the source is a valid URL
                return source;
            } else if (!isValidUrl) {

                // If the video source is an invalid URL, alert user and search for
                // a source in the same directory as the xmlfile
                // File f = new File(UserPreferences.getModel().getImportVideoDir().toString());
                File f = new File(xmlfile.toString());
                File file;

                if ((file = searchForClip(xmlfile, ".avi")) != null
                        || (file = searchForClip(xmlfile, ".avi", f)) != null
                        || (file = searchForClip(xmlfile, ".mov")) != null
                        || (file = searchForClip(xmlfile, ".mov", f)) != null
                        || (file = searchForClip(xmlfile, ".tar")) != null
                        || (file = searchForClip(xmlfile, ".tar", f)) != null
                        || (file = searchForClip(xmlfile, ".tar.gz")) != null
                        || (file = searchForClip(xmlfile, ".tar.gz", f)) != null) {
                    if (file != null) {
                        Logger.getLogger(ApplicationController.class.getName()).log(Level.INFO, null,
                                "Found alternative video source " + file.toString());
                        return file.toURL();
                    }

                }
            } else if (URLUtils.isFileUrl(source.toString())) {

                // if not a URL, simply use the original file
                return source;
            }
        } catch (Exception ex) {
            Logger.getLogger(ApplicationController.class.getName()).log(Level.SEVERE, null, ex);

            return null;
        }
    }

    return null;
}

From source file:org.codehaus.mojo.gwt.webxml.MergeWebXmlMojo.java

private ClassLoader getAnnotationSearchClassLoader() throws ClasspathBuilderException, MalformedURLException {
    Collection<File> classPathFiles = classpathBuilder.buildClasspathList(getProject(), Artifact.SCOPE_COMPILE,
            Collections.<Artifact>emptySet());

    List<URL> urls = new ArrayList<URL>(classPathFiles.size());

    for (File file : classPathFiles) {
        urls.add(file.toURL());
    }/*from  ww w  .j ava  2 s  .c  o m*/

    URLClassLoader url = new URLClassLoader(urls.toArray(new URL[urls.size()]));
    return url;

}