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.sshtools.j2ssh.util.ExtensionClassLoader.java

private URL findResourceInZipfile(File file, String name) {
    try {//www.  j a va 2s.c  o  m
        ZipFile zipfile = new ZipFile(file);
        ZipEntry entry = zipfile.getEntry(name);

        if (entry != null) {
            return new URL("jar:" + file.toURL() + "!" + (name.startsWith("/") ? "" : "/") + name);
        } else {
            return null;
        }
    } catch (IOException e) {
        return null;
    }

}

From source file:com.jf.javafx.Application.java

/**
 * Load a node and its controller./* www . j  a va 2 s  .  co  m*/
 * 
 * @param path
 * @return the node
 */
public Pair<Node, ?> createNode(String path) {
    final Application app = this;
    File fxml = getTemplateFile(path + ".fxml");
    Node node;
    Object controller = null;
    try {
        ResourceBundle bundle;
        try {
            bundle = getResourceBundle("controllers/" + path);
        } catch (Exception ex) {
            bundle = null;
        }

        FXMLLoader loader = new FXMLLoader(fxml.toURL(), bundle, new JavaFXBuilderFactory(),
                (Class<?> param) -> {
                    try {
                        Class cls = Controller.class;

                        if (cls.isAssignableFrom(param)) {
                            try {
                                return param.getConstructor(Application.class).newInstance(app);
                            } catch (Exception ex) {
                                Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
                                return param.newInstance();
                            }
                        } else {
                            return param.newInstance();
                        }
                    } catch (IllegalAccessException | IllegalArgumentException | InstantiationException
                            | SecurityException ex) {
                        MsgBox.showException(ex);
                        return null;
                    }
                });
        node = loader.load();
        controller = loader.getController();
    } catch (IOException ex) {
        MsgBox.showException(ex, "Error while navigate to path: " + path);

        // customize error screen
        AnchorPane p = new AnchorPane();

        //            StringWriter sw = new StringWriter();
        //            ex.printStackTrace(new PrintWriter(sw));
        //            p.getChildren().add(new Label(sw.toString()));

        node = p;
    }

    return new Pair(node, controller);
}

From source file:org.apache.cayenne.util.ResourceLocator.java

/**
 * Returns a resource URL using the lookup strategy configured for this
 * Resourcelocator or <code>null</code> if no readable resource can be found for the
 * given name./*from   ww  w.j av  a2  s .  co  m*/
 */
public URL findResource(String name) {
    if (!willSkipAbsolutePath()) {
        File f = new File(name);
        if (f.isAbsolute() && f.exists()) {
            logObj.debug("File found at absolute path: " + name);
            try {
                return f.toURL();
            } catch (MalformedURLException ex) {
                // ignoring
                logObj.debug("Malformed url, ignoring.", ex);
            }
        } else {
            logObj.debug("No file at absolute path: " + name);
        }
    }

    if (!willSkipHomeDirectory()) {
        File f = findFileInHomeDirectory(name);
        if (f != null) {

            try {
                return f.toURL();
            } catch (MalformedURLException ex) {
                // ignoring
                logObj.debug("Malformed url, ignoring", ex);
            }
        }
    }

    if (!willSkipCurrentDirectory()) {
        File f = findFileInCurrentDirectory(name);
        if (f != null) {

            try {
                return f.toURL();
            } catch (MalformedURLException ex) {
                // ignoring
                logObj.debug("Malformed url, ignoring", ex);
            }
        }
    }

    if (!additionalFilesystemPaths.isEmpty()) {
        logObj.debug("searching additional paths: " + this.additionalFilesystemPaths);
        for (String filePath : this.additionalFilesystemPaths) {
            File f = new File(filePath, name);
            logObj.debug("searching for: " + f.getAbsolutePath());
            if (f.exists()) {
                try {
                    return f.toURL();
                } catch (MalformedURLException ex) {
                    // ignoring
                    logObj.debug("Malformed URL, ignoring.", ex);
                }
            }
        }
    }

    if (!willSkipClasspath()) {

        // start with custom classpaths and then move to the default one
        if (!this.additionalClassPaths.isEmpty()) {
            logObj.debug("searching additional classpaths: " + this.additionalClassPaths);

            for (String classPath : this.additionalClassPaths) {
                String fullName = classPath + "/" + name;
                logObj.debug("searching for: " + fullName);
                URL url = findURLInClassLoader(fullName, getClassLoader());
                if (url != null) {
                    return url;
                }
            }
        }

        URL url = findURLInClassLoader(name, getClassLoader());
        if (url != null) {
            return url;
        }
    }

    return null;
}

From source file:UnpackedJarFile.java

public static URL createJarURL(JarFile jarFile, String path) throws MalformedURLException {
    if (jarFile instanceof NestedJarFile) {
        NestedJarFile nestedJar = (NestedJarFile) jarFile;
        if (nestedJar.isUnpacked()) {
            JarFile baseJar = nestedJar.getBaseJar();
            String basePath = nestedJar.getBasePath();
            if (baseJar instanceof UnpackedJarFile) {
                File baseDir = ((UnpackedJarFile) baseJar).getBaseDir();
                baseDir = new File(baseDir, basePath);
                return new File(baseDir, path).toURL();
            }/*from   w  ww.j  a va 2s.c om*/
        }
    }

    if (jarFile instanceof UnpackedJarFile) {
        File baseDir = ((UnpackedJarFile) jarFile).getBaseDir();
        return new File(baseDir, path).toURL();
    } else {
        String urlString = "jar:" + new File(jarFile.getName()).toURL() + "!/" + path;
        if (jarUrlRewrite) {
            // To prevent the lockout of archive, instead of returning a jar url, write the content to a
            // temp file and return the url of that file.
            File tempFile = null;
            try {
                tempFile = toTempFile(new URL(urlString));
            } catch (IOException e) {
                // The JarEntry does not exist!
                // Return url of a file that does not exist.
                try {
                    tempFile = createTempFile();
                    tempFile.delete();
                } catch (IOException ignored) {
                }
            }
            return tempFile.toURL();
        } else {
            return new URL(urlString);
        }
    }
}

From source file:org.apache.xml.security.test.c14n.implementations.ExclusiveC14NInterop.java

/**
 * Method t//w w  w  .j  ava2s. c  o m
 *
 * @param directory
 * @param file
 *
 * @throws Exception
 */
public String t(String directory, String file) throws Exception {
    String basedir = System.getProperty("basedir");
    if (basedir != null && !"".equals(basedir)) {
        directory = basedir + "/" + directory;
    }

    File f = new File(directory + "/" + file);
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.parse(f);

    Element sigElement = (Element) doc
            .getElementsByTagNameNS(Constants.SignatureSpecNS, Constants._TAG_SIGNATURE).item(0);
    XMLSignature signature = new XMLSignature(sigElement, f.toURL().toString());
    boolean verify = signature.checkSignatureValue(signature.getKeyInfo().getPublicKey());

    log.debug("   signature.checkSignatureValue finished: " + verify);

    int failures = 0;

    // if (!verify) {
    if (true) {
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < signature.getSignedInfo().getLength(); i++) {
            boolean refVerify = signature.getSignedInfo().getVerificationResult(i);
            JavaUtils.writeBytesToFilename(directory + "/c14n-" + i + ".apache.html",
                    signature.getSignedInfo().item(i).getHTMLRepresentation().getBytes());

            if (refVerify) {
                log.debug("Reference " + i + " was OK");
            } else {
                failures++;

                sb.append(i + " ");

                JavaUtils.writeBytesToFilename(directory + "/c14n-" + i + ".apache.txt",
                        signature.getSignedInfo().item(i).getContentsAfterTransformation().getBytes());
                JavaUtils.writeBytesToFilename(directory + "/c14n-" + i + ".apache.html",
                        signature.getSignedInfo().item(i).getHTMLRepresentation().getBytes());

                Reference reference = signature.getSignedInfo().item(i);
                int length = reference.getTransforms().getLength();
                String algo = reference.getTransforms().item(length - 1).getURI();

                log.debug("Reference " + i + " failed: " + algo);
            }
        }

        String r = sb.toString().trim();

        if (r.length() == 0) {
            return null;
        } else {
            return r;
        }
    } else {
        return null;
    }
}

From source file:org.deegree.portal.portlet.modules.wfs.actions.portlets.WFSClientPortletPerform_BAK.java

/**
 * transforms the result of a WFS request using the XSLT script defined
 * by an init parameter// ww  w.j  a  v  a 2s  .  co m
 * @param xml
 * @return
 * @throws PortalException
 */
private XMLFragment transform(XMLFragment xml) throws PortalException {
    String xslF = getInitParam(INIT_XSLT);
    File file = new File(xslF);
    if (!file.isAbsolute()) {
        file = new File(sc.getRealPath(xslF));
    }
    XSLTDocument xslt = new XSLTDocument();
    try {
        xslt.load(file.toURL());
        xml = xslt.transform(xml);
    } catch (Exception e) {
        LOG.logError(e.getMessage(), e);
        throw new PortalException("could not transform result of WFS request", e);
    }
    return xml;
}

From source file:org.fusesource.meshkeeper.distribution.PluginClassLoader.java

public synchronized PluginResolver getPluginResolver() {
    if (PLUGIN_RESOLVER == null) {
        PluginClassLoader loader = this;
        try {//from w w  w.j  av a2  s . c o  m
            // Extract the jar to temp file...
            InputStream is = PluginClassLoader.class.getClassLoader()
                    .getResourceAsStream("meshkeeper-mop-resolver.jar");
            if (is != null) {
                File tempJar = File.createTempFile("meshkeeper-mop-resolver", ".jar");
                tempJar.deleteOnExit();
                try {
                    FileSupport.write(is, tempJar);
                } finally {
                    IOSupport.close(is);
                }
                loader.addUrl(tempJar.toURL());
            }
            PLUGIN_RESOLVER = (PluginResolver) loader
                    .loadClass("org.fusesource.meshkeeper.distribution.MopPluginResolver").newInstance();
        } catch (Throwable thrown) {
            LOG.error("Error loading plugin resolver:" + thrown.getMessage(), thrown);
            throw new RuntimeException(thrown);
        }
        PLUGIN_RESOLVER.setDefaultPluginVersion(getDefaultPluginVersion());
    }
    return PLUGIN_RESOLVER;
}

From source file:org.apache.archiva.xml.XMLReader.java

public XMLReader(String type, File file) throws XMLException {
    if (!file.exists()) {
        throw new XMLException("file does not exist: " + file.getAbsolutePath());
    }/* w  w w  .ja  v a 2 s  . co m*/

    if (!file.isFile()) {
        throw new XMLException("path is not a file: " + file.getAbsolutePath());
    }

    if (!file.canRead()) {
        throw new XMLException("Cannot read xml file due to permissions: " + file.getAbsolutePath());
    }

    try {
        init(type, file.toURL());
    } catch (MalformedURLException e) {
        throw new XMLException("Unable to translate file " + file + " to URL: " + e.getMessage(), e);
    }
}

From source file:tufts.oki.dr.fedora.DR.java

private java.net.URL getResource(String name) {
    java.net.URL url = null;//from ww w  .j  a v a2s  .c om
    java.io.File f = new java.io.File(name);
    if (f.exists()) {
        try {
            url = f.toURL();
        } catch (Exception e) {
            e.printStackTrace();
            f = null;
        }
    }
    if (url == null)
        url = getClass().getResource(name);
    System.out.println("DR.getResource(" + name + ") = " + url + " f=" + f);
    return url;
}

From source file:org.apache.cayenne.modeler.action.OpenProjectAction.java

/** Opens specified project file. File must already exist. */
public void openProject(File file) {
    try {//from   ww  w  .j  a v  a2  s  .com
        if (!file.exists()) {
            JOptionPane.showMessageDialog(Application.getFrame(),
                    "Can't open project - file \"" + file.getPath() + "\" does not exist", "Can't Open Project",
                    JOptionPane.OK_OPTION);
            return;
        }

        CayenneModelerController controller = Application.getInstance().getFrameController();
        controller.addToLastProjListAction(file.getAbsolutePath());

        URL url = file.toURL();
        Resource rootSource = new URLResource(url);

        ProjectUpgrader upgrader = getApplication().getInjector().getInstance(ProjectUpgrader.class);
        UpgradeHandler handler = upgrader.getUpgradeHandler(rootSource);
        UpgradeMetaData md = handler.getUpgradeMetaData();

        if (UpgradeType.DOWNGRADE_NEEDED == md.getUpgradeType()) {
            JOptionPane.showMessageDialog(Application.getFrame(),
                    "Can't open project - it was created using a newer version of the Modeler",
                    "Can't Open Project", JOptionPane.OK_OPTION);
            closeProject(false);
        } else if (UpgradeType.INTERMEDIATE_UPGRADE_NEEDED == md.getUpgradeType()) {
            JOptionPane.showMessageDialog(Application.getFrame(),
                    // TODO: andrus 05/02/2010 - this message shows intermediate
                    // version of the project XML, not the Modeler code
                    // version that
                    // can be used for upgrade
                    "Can't upgrade project. Open the project in the Modeler v."
                            + md.getIntermediateUpgradeVersion()
                            + " to do an intermediate upgrade before you can upgrade to v."
                            + md.getSupportedVersion(),
                    "Can't Upgrade Project", JOptionPane.OK_OPTION);
            closeProject(false);
        } else if (UpgradeType.UPGRADE_NEEDED == md.getUpgradeType()) {
            if (processUpgrades(md)) {
                // perform upgrade
                logObj.info("Will upgrade project " + url.getPath());
                Resource upgraded = handler.performUpgrade();
                if (upgraded != null) {
                    Project project = openProjectResourse(upgraded, controller);

                    getProjectController().getFileChangeTracker().pauseWatching();
                    getProjectController().getFileChangeTracker().reconfigure();

                    // if project file name changed
                    // need upgrade all
                    if (!file.getAbsolutePath().equals(project.getConfigurationResource().getURL().getPath())) {
                        controller.changePathInLastProjListAction(file.getAbsolutePath(),
                                project.getConfigurationResource().getURL().getPath());
                    }
                } else {
                    closeProject(false);
                }
            }
        } else {
            openProjectResourse(rootSource, controller);
        }
    } catch (Exception ex) {
        logObj.warn("Error loading project file.", ex);
        ErrorDebugDialog.guiWarning(ex, "Error loading project");
    }
}