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.aurel.track.admin.customize.category.report.execute.ReportExecuteBL.java

/**
 * Serializes the data source into the response's output stream using a DOM
 * to XML converter//from w w w  . java 2 s .  c  o  m
 *
 * @param pluggableDatasouce
 * @param datasource
 * @return
 */
static String prepareDatasourceResponse(HttpServletResponse response, Integer templateID,
        IPluggableDatasource pluggableDatasouce, Map<String, Object> description, Object datasource) {
    // otherwise prepare an XML result
    DownloadUtil.prepareResponse(ServletActionContext.getRequest(), response, "TrackReport.xml", "text/xml");
    try {
        final OutputStream outputStream = response.getOutputStream();
        final String xslt = (String) description.get("xslt");
        if ((datasource != null) && (xslt != null) && (templateID != null)) {
            final File template = ReportBL.getDirTemplate(templateID);
            URL baseURL = null;
            try {
                baseURL = template.toURL();
            } catch (final MalformedURLException e) {
                LOGGER.error("Wrong template URL for " + template.getName() + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
            if (baseURL != null) {
                final String absolutePathXslt = baseURL.getFile() + xslt;
                try {
                    datasource = XsltTransformer.getInstance().transform((Document) datasource,
                            absolutePathXslt);
                } catch (final Exception e) {
                    LOGGER.warn("Tranforming the datasource with " + absolutePathXslt + " failed with "
                            + e.getMessage());
                    LOGGER.debug(ExceptionUtils.getStackTrace(e));
                }
            }
        }
        if (pluggableDatasouce == null) {
            // the default datasource (ReportBeans from last executed query)
            // serialize the DOM object into an XML stream
            ReportBeansToXML.convertToXml(outputStream, (Document) datasource);
        } else {
            // datasource specific serialization
            pluggableDatasouce.serializeDatasource(outputStream, datasource);
        }
    } catch (final Exception e) {
        LOGGER.error("Serializing the datasource to output stream failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));

    }
    return null;
}

From source file:org.apache.oodt.cas.filemgr.versioning.VersioningUtils.java

public static List<Reference> getReferencesFromDir(File dirRoot) {
    List<Reference> references;

    if (dirRoot == null) {
        throw new IllegalArgumentException("null");
    }//from ww  w .ja  v a  2  s .  c om
    if (!dirRoot.isDirectory()) {
        dirRoot = dirRoot.getParentFile();
    }

    references = new Vector<Reference>();

    Stack<File> stack = new Stack<File>();
    stack.push(dirRoot);
    while (!stack.isEmpty()) {
        File dir = stack.pop();
        // add the reference for the dir
        // except if it's the rootDir, then, skip it
        if (!dir.equals(dirRoot)) {
            try {
                Reference r = new Reference();
                r.setOrigReference(dir.toURL().toExternalForm());
                r.setFileSize(dir.length());
                references.add(r);
            } catch (MalformedURLException e) {
                LOG.log(Level.SEVERE, e.getMessage());
                LOG.log(Level.WARNING, "MalformedURLException when generating reference for dir: " + dir);
            }
        }

        File[] files = dir.listFiles(FILE_FILTER);

        if (files != null) {
            for (File file : files) {
                // add the file references
                try {
                    Reference r = new Reference();
                    r.setOrigReference(file.toURL().toExternalForm());
                    r.setFileSize(file.length());
                    references.add(r);
                } catch (MalformedURLException e) {
                    LOG.log(Level.SEVERE, e.getMessage());
                    LOG.log(Level.WARNING, "MalformedURLException when generating reference for file: " + file);
                }

            }
            File[] subdirs = dir.listFiles(DIR_FILTER);
            if (subdirs != null) {
                for (File subdir : subdirs) {
                    stack.push(subdir);
                }
            }
        }
    }

    return references;
}

From source file:org.apache.sling.osgi.obr.Resource.java

public static Resource create(File file) throws IOException {
    return create(file.toURL());
}

From source file:org.apache.xml.security.samples.encryption.Decrypter.java

private static void outputDocToFile(Document doc, String fileName) throws Exception {
    File encryptionFile = new File(fileName);
    FileOutputStream f = new FileOutputStream(encryptionFile);

    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(f);
    transformer.transform(source, result);

    f.close();//from   ww  w  .  j a va 2  s.com
    System.out.println("Wrote document containing decrypted data to " + encryptionFile.toURL().toString());
}

From source file:com.sun.faces.generate.AbstractGenerator.java

/**
 * <p>Parse the specified configuration file, and return the root of the
 * resulting tree of configuration beans.</p>
 *
 * @param digester Digester instance to use for parsing
 * @param config Pathname of the configuration file to be parsed
 *
 * @exception IOException an input/output error occurred while parsing
 * @exception SAXException an XML processing error occurred while parsing
 *///ww w .  j  a  v a 2 s.  c  om
protected static FacesConfigBean parse(Digester digester, String config) throws IOException, SAXException {

    File file = null;
    FacesConfigBean fcb = null;
    InputSource source = null;
    InputStream stream = null;
    try {
        file = new File(config);
        stream = new BufferedInputStream(new FileInputStream(file));
        source = new InputSource(file.toURL().toString());
        source.setByteStream(stream);
        fcb = (FacesConfigBean) digester.parse(source);
        stream.close();
        stream = null;
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (Exception e) {
                ;
            }
            stream = null;
        }
    }
    return (fcb);

}

From source file:com.aurel.track.Constants.java

public static void setGroovyScriptEngine() {
    // Create a plugin directory for Groovy scripts if it does not exist
    // already anyways.
    File groovyPluginDir = new File(HandleHome.getGroovyPluginPath());

    if (!groovyPluginDir.exists() || !groovyPluginDir.isDirectory()) {
        LOGGER.info("Creating " + HandleHome.getGroovyPluginPath());
        if (HandleHome.getGroovyPluginPath().length() > 1) {
            if (!groovyPluginDir.mkdirs()) {
                System.err.println("Create failed.");
            }//from   ww  w .  j a  v  a 2s .  com
        }
    }

    try {
        URL extern = groovyPluginDir.toURL();
        ClassLoader parent = ApplicationBean.getInstance().getClass().getClassLoader();
        GroovyClassLoader loader = new GroovyClassLoader(parent);

        // external plugins have precedence; they can cover internal
        // plugins with the same name!
        URL[] roots = new URL[] { extern/*,
                                        groovyURL*/
        };
        groovyScriptEngine = null;
        groovyScriptEngine = new GroovyScriptEngine(roots, loader);
    } catch (Exception ioe) {
        System.err.println("Cannot initialize Groovy script engine");
        LOGGER.error(ExceptionUtils.getStackTrace(ioe));
    }
}

From source file:edu.ku.brc.helpers.XMLHelper.java

/**
 * Reads in a file of HTML, primarily from the Help directory and fixes up the images
 * to have an absolute path. Plus it strip everything before and including the 'body' tag and
 * strips the '</body>' to the end.
 * @param file the html file to be read.
 * @return the file as a string//from   www  .  ja  va2  s.  com
 */
@SuppressWarnings("deprecation") //$NON-NLS-1$
public static String fixUpHTML(final File file) {
    String path = FilenameUtils.getFullPath(file.getAbsolutePath());

    StringBuilder sb = new StringBuilder();
    try {
        List<?> lines = FileUtils.readLines(file);
        boolean fndBegin = false;

        for (Object lineObj : lines) {
            String line = (String) lineObj;
            if (!fndBegin) {
                if (line.indexOf("<body") > -1) //$NON-NLS-1$
                {
                    fndBegin = true;
                }
                continue;
            }
            int inx = line.indexOf("<img"); //$NON-NLS-1$
            if (inx > -1) {
                inx = line.indexOf("src=\"", inx); //$NON-NLS-1$

                sb.append(line.substring(0, inx + 5));
                File f = new File(path);
                sb.append(f.toURL()); // needed for 1.5
                sb.append(line.substring(inx + 5, line.length()));
            } else {
                sb.append(line + "\n"); //$NON-NLS-1$
            }
        }
    } catch (IOException ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(XMLHelper.class, ex);
        log.error(ex);
    }
    return sb.toString();
}

From source file:org.apache.xml.security.samples.encryption.Encrypter.java

private static void outputDocToFile(Document doc, String fileName) throws Exception {
    File encryptionFile = new File(fileName);
    FileOutputStream f = new FileOutputStream(encryptionFile);

    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(f);
    transformer.transform(source, result);

    f.close();//w  w w.  ja  v a  2  s. com
    System.out.println("Wrote document containing encrypted data to " + encryptionFile.toURL().toString());
}

From source file:org.springframework.osgi.web.deployer.internal.util.JasperUtils.java

/**
 * Creates a temporary jar using the given resources.
 * //  www  .  ja v  a2 s  . c  o  m
 * @param resource
 * @return
 */
private static URL createTaglibJar(Resource[] resources, Manifest mf) throws IOException {
    File tempJar = File.createTempFile("spring.dm.tld.", ".jar");
    tempJar.deleteOnExit();
    OutputStream fos = new FileOutputStream(tempJar);

    Map entries = new LinkedHashMap();
    for (int i = 0; i < resources.length; i++) {
        Resource resource = resources[i];
        String name = URLDecoder.decode(resource.getURL().getPath(), "UTF8");
        entries.put(name, resource);
    }
    JarUtils.createJar(mf, entries, fos);

    URL jarURL = tempJar.toURL();
    if (log.isTraceEnabled()) {
        StringBuilder buf = new StringBuilder();
        buf.append("\n");
        for (Iterator iterator = entries.entrySet().iterator(); iterator.hasNext();) {
            Map.Entry entry = (Map.Entry) iterator.next();
            buf.append(entry.getKey());
            buf.append("\t\t");
            buf.append(entry.getValue());
            buf.append("\n");
        }

        log.trace("Created TLD jar at " + tempJar.toURL() + " containing " + buf);
    }

    return jarURL;
}

From source file:org.nuxeo.runtime.jboss.adapter.ComponentAdapter.java

protected static void deployComponent(RegistrationInfo ri)
        throws MBeanProxyCreationException, MalformedObjectNameException {
    ComponentName name = ri.getName();//from  w  w  w. j av a2 s. c  o  m
    if (log.isDebugEnabled()) {
        log.debug("Registering Mbean for service: " + name);
    }
    RuntimeAdapterMBean rad = (RuntimeAdapterMBean) ServiceLocator.getService(RuntimeAdapterMBean.class,
            RuntimeAdapter.NAME);
    File file = new File(rad.getTempDeployDir(), name + "-service.xml");
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(file);
        out.write(ComponentMBean.getMBeanXMLContent(name).getBytes());
        out.close();
        if (log.isTraceEnabled()) {
            log.trace("Deploying Mbean file to: " + file.getAbsolutePath());
        }
        // use the ear deployment if any to correctly handle isolation
        DeploymentInfo parent = JBossOSGiAdapter.getEARDeployment();
        DeploymentHelper.deploy(file.toURL(), parent);
    } catch (Exception e) {
        log.error("Failed to register Mbean for service " + ri.getName(), e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}