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.opendoorlogistics.core.geometry.ImportShapefile.java

public static DataStore openDataStore(File file) {
    Map<String, URL> map = new HashMap<String, URL>();
    try {//from w w w.  j a  va 2  s.c  om
        map.put("url", file.toURL());
        return DataStoreFinder.getDataStore(map);
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
}

From source file:org.openadaptor.util.URLUtils.java

/**
 * Checks the supplied url string to make sure that it is valid. It does this by checking that it:
 * //ww w  .  j  av a 2 s. c  o m
 * <pre>
 *   a. a valid url format
 *   b. points to a data source that contains data
 * </pre>
 * 
 * Note that in the case of files you do not need to supply the "file:" protocol.
 * 
 * @throws RuntimeException
 *           if the url is null, or it does not exist, or it does not contain any data
 */
public static void validateURLAsDataSource(String url) {
    if (url == null || url.equals(""))
        throw new RuntimeException("Null url");

    // check the url is of valid format, exists and contains data
    try {
        URL u;

        try {
            u = new URL(url);
        } catch (MalformedURLException e) {
            // we assume that if it is not a valid URL then we are dealing with
            // a file and need to check that it exists and is not a directory
            File f = new File(url);

            if (!f.exists())
                throw new Exception("File not found and " + e.getMessage());

            if (f.isDirectory())
                throw new Exception("URL points to a directory");

            u = f.toURL();
        }

        InputStream in = u.openStream();
        int numBytes = in.available();
        in.close();

        if (numBytes <= 0) {
            log.warn("Number of bytes available from [" + url + "] = " + in.available());
            throw new Exception("Unable to read from file");
        }
    } catch (Exception e) {
        throw new RuntimeException("Invalid URL [" + url + "]: " + e.toString());
    }

    log.info("URL [" + url + "] is valid");
}

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

private static SecretKey loadKeyEncryptionKey() throws Exception {

    String fileName = "kek";
    String jceAlgorithmName = "DESede";

    File kekFile = new File(fileName);

    DESedeKeySpec keySpec = new DESedeKeySpec(JavaUtils.getBytesFromFile(fileName));
    SecretKeyFactory skf = SecretKeyFactory.getInstance(jceAlgorithmName);
    SecretKey key = skf.generateSecret(keySpec);

    System.out.println("Key encryption key loaded from " + kekFile.toURL().toString());
    return key;/*  ww w. j a va  2 s.c  o m*/
}

From source file:org.blindsideproject.fileupload.document.impl.PptToJpegConverter.java

public static synchronized SlideInfo[] exportSlides(File fileSource, File fileOutDir, String strMachine,
        int iPort, PptToJpegConverter format) {

    //      String srcUrl = "C:/temp/Balancing.ppt";
    //      String destDir = "C:/temp/dest";

    logger.warn("Connecting to: " + strMachine + ":" + iPort);

    XComponent xComponent = null;//from w w  w . ja va 2s . c  o m
    SlideInfo[] slideInfos = null;
    OOOConnection oooConn = null;
    OOODocument oooDoc = null;

    try {
        oooConn = Helper.connectEx(strMachine, iPort);

        // suppress Presentation Autopilot when opening the document
        // properties are the same as described for
        // com.sun.star.document.MediaDescriptor
        PropertyValue[] pPropValues = new PropertyValue[1];
        pPropValues[0] = new PropertyValue();
        pPropValues[0].Name = "Hidden";
        pPropValues[0].Value = new Boolean(true);

        //            java.io.File sourceFile = new java.io.File(srcUrl);
        StringBuffer sUrl = new StringBuffer(FILE_URL_PREFIX);
        sUrl.append(fileSource.getCanonicalPath().replace('\\', '/'));

        logger.info("PPTExporter - source canonical path: " + fileSource.getCanonicalPath());
        logger.info("PPTExporter - source: " + sUrl);

        //            oooDoc = Helper.createDocument(oooConn.getComponentFactory(),
        //                        sUrl.toString(), "_blank", 0, pPropValues);

        oooDoc = Helper.createDocument(oooConn.getComponentFactory(), fileSource.getCanonicalPath(), "_blank",
                0, pPropValues);

        Object graphicExportFilter = oooConn.getComponentFactory()
                .createInstanceWithContext("com.sun.star.drawing.GraphicExportFilter", oooDoc.getContext());

        XExporter xExporter = (XExporter) UnoRuntime.queryInterface(XExporter.class, graphicExportFilter);

        xComponent = oooDoc.getComponent();

        int numSlides = PageHelper.getDrawPageCount(xComponent);
        slideInfos = new SlideInfo[numSlides];

        PropertyValue aFilterData[] = new PropertyValue[5];
        aFilterData[0] = new PropertyValue();
        aFilterData[0].Name = "PixelWidth";
        aFilterData[0].Value = new Integer(800);
        aFilterData[1] = new PropertyValue();
        aFilterData[1].Name = "PixelHeight";
        aFilterData[1].Value = new Integer(600);
        aFilterData[2] = new PropertyValue();
        aFilterData[2].Name = "LogicalWidth";
        aFilterData[2].Value = new Integer(800);
        aFilterData[3] = new PropertyValue();
        aFilterData[3].Name = "LogicalHeight";
        aFilterData[3].Value = new Integer(600);
        aFilterData[4] = new PropertyValue();
        aFilterData[4].Name = "Quality";
        aFilterData[4].Value = new Integer(100);

        for (int i = 0; i < numSlides; i++) {

            PropertyValue aProps[] = new PropertyValue[3];
            aProps[0] = new PropertyValue();
            aProps[0].Name = "MediaType";
            aProps[0].Value = "image/jpeg";
            aProps[1] = new PropertyValue();
            aProps[1].Name = "FilterData";
            aProps[1].Value = aFilterData;

            /* some graphics e.g. the Windows Metafile does not have a Media Type,
               for this case
               aProps[0].Name = "FilterName"; // it is possible to set a FilterName 
               aProps[0].Value = "WMF";
             */
            String slideName = fileOutDir.getAbsolutePath() + "/slide" + i + ".jpg";

            java.io.File destFile = new java.io.File(slideName);
            java.net.URL destUrl = destFile.toURL();

            aProps[2] = new PropertyValue();
            aProps[2].Name = "URL";
            aProps[2].Value = destUrl.toString();

            XDrawPage xPage = PageHelper.getDrawPageByIndex(xComponent, i);
            String slideTitle = PageHelper.getDrawPageName(xPage);

            XComponent xComp = (XComponent) UnoRuntime.queryInterface(XComponent.class, xPage);

            xExporter.setSourceDocument(xComp);

            XFilter xFilter = (XFilter) UnoRuntime.queryInterface(XFilter.class, xExporter);
            xFilter.filter(aProps);

            logger.info("*** graphics on page \"" + i + "\" with title '" + slideTitle + "' from file \""
                    + fileSource.toString() + "\" exported under the name \"" + fileOutDir.getAbsolutePath()
                    + "\" in the local directory");

            slideInfos[i] = new SlideInfo(slideTitle, slideName, PptToJpegConverter.FORMAT_JPEG);
        }
    } catch (Exception ex) {
        logger.error(ex);
    } finally {
        try {
            if (null != xComponent) {
                xComponent.dispose();
            }
        } catch (Exception e) {
            logger.error("error calling dispose\n" + e);
        }
        try {
            if (null != oooConn) {
                Helper.closeConnection(oooConn);
            }
        } catch (Exception e) {
            logger.error("error closing connection\n" + e);
        }
    }
    return slideInfos;
}

From source file:org.bigbluebuttonproject.fileupload.document.impl.PptToJpegConverter.java

/**
 * Export slides.// w  w  w.ja v  a 2  s  . c  o  m
 * 
 * @param fileSource the file source
 * @param fileOutDir the file out dir
 * @param strMachine the str machine
 * @param iPort the i port
 * @param format the format
 * 
 * @return the slide info[]
 */
public static synchronized SlideInfo[] exportSlides(File fileSource, File fileOutDir, String strMachine,
        int iPort, PptToJpegConverter format) {

    //      String srcUrl = "C:/temp/Balancing.ppt";
    //      String destDir = "C:/temp/dest";

    logger.warn("Connecting to: " + strMachine + ":" + iPort);

    XComponent xComponent = null;
    SlideInfo[] slideInfos = null;
    OOOConnection oooConn = null;
    OOODocument oooDoc = null;

    try {
        oooConn = Helper.connectEx(strMachine, iPort);

        // suppress Presentation Autopilot when opening the document
        // properties are the same as described for
        // com.sun.star.document.MediaDescriptor
        PropertyValue[] pPropValues = new PropertyValue[1];
        pPropValues[0] = new PropertyValue();
        pPropValues[0].Name = "Hidden";
        pPropValues[0].Value = new Boolean(true);

        //            java.io.File sourceFile = new java.io.File(srcUrl);
        StringBuffer sUrl = new StringBuffer(FILE_URL_PREFIX);
        sUrl.append(fileSource.getCanonicalPath().replace('\\', '/'));

        logger.info("PPTExporter - source canonical path: " + fileSource.getCanonicalPath());
        logger.info("PPTExporter - source: " + sUrl);

        //            oooDoc = Helper.createDocument(oooConn.getComponentFactory(),
        //                        sUrl.toString(), "_blank", 0, pPropValues);

        oooDoc = Helper.createDocument(oooConn.getComponentFactory(), fileSource.getCanonicalPath(), "_blank",
                0, pPropValues);

        Object graphicExportFilter = oooConn.getComponentFactory()
                .createInstanceWithContext("com.sun.star.drawing.GraphicExportFilter", oooDoc.getContext());

        XExporter xExporter = (XExporter) UnoRuntime.queryInterface(XExporter.class, graphicExportFilter);

        xComponent = oooDoc.getComponent();

        int numSlides = PageHelper.getDrawPageCount(xComponent);
        slideInfos = new SlideInfo[numSlides];

        PropertyValue aFilterData[] = new PropertyValue[5];
        aFilterData[0] = new PropertyValue();
        aFilterData[0].Name = "PixelWidth";
        aFilterData[0].Value = new Integer(800);
        aFilterData[1] = new PropertyValue();
        aFilterData[1].Name = "PixelHeight";
        aFilterData[1].Value = new Integer(600);
        aFilterData[2] = new PropertyValue();
        aFilterData[2].Name = "LogicalWidth";
        aFilterData[2].Value = new Integer(800);
        aFilterData[3] = new PropertyValue();
        aFilterData[3].Name = "LogicalHeight";
        aFilterData[3].Value = new Integer(600);
        aFilterData[4] = new PropertyValue();
        aFilterData[4].Name = "Quality";
        aFilterData[4].Value = new Integer(100);

        for (int i = 0; i < numSlides; i++) {

            PropertyValue aProps[] = new PropertyValue[3];
            aProps[0] = new PropertyValue();
            aProps[0].Name = "MediaType";
            aProps[0].Value = "image/jpeg";
            aProps[1] = new PropertyValue();
            aProps[1].Name = "FilterData";
            aProps[1].Value = aFilterData;

            /* some graphics e.g. the Windows Metafile does not have a Media Type,
               for this case
               aProps[0].Name = "FilterName"; // it is possible to set a FilterName 
               aProps[0].Value = "WMF";
             */
            String slideName = fileOutDir.getAbsolutePath() + "/slide" + i + ".jpg";

            java.io.File destFile = new java.io.File(slideName);
            java.net.URL destUrl = destFile.toURL();

            aProps[2] = new PropertyValue();
            aProps[2].Name = "URL";
            aProps[2].Value = destUrl.toString();

            XDrawPage xPage = PageHelper.getDrawPageByIndex(xComponent, i);
            String slideTitle = PageHelper.getDrawPageName(xPage);

            XComponent xComp = (XComponent) UnoRuntime.queryInterface(XComponent.class, xPage);

            xExporter.setSourceDocument(xComp);

            XFilter xFilter = (XFilter) UnoRuntime.queryInterface(XFilter.class, xExporter);
            xFilter.filter(aProps);

            logger.info("*** graphics on page \"" + i + "\" with title '" + slideTitle + "' from file \""
                    + fileSource.toString() + "\" exported under the name \"" + fileOutDir.getAbsolutePath()
                    + "\" in the local directory");

            slideInfos[i] = new SlideInfo(slideTitle, slideName, PptToJpegConverter.FORMAT_JPEG);
        }
    } catch (Exception ex) {
        logger.error(ex);
    } finally {
        try {
            if (null != xComponent) {
                xComponent.dispose();
            }
        } catch (Exception e) {
            logger.error("error calling dispose\n" + e);
        }
        try {
            if (null != oooConn) {
                Helper.closeConnection(oooConn);
            }
        } catch (Exception e) {
            logger.error("error closing connection\n" + e);
        }
    }
    return slideInfos;
}

From source file:JarMaker.java

public static void RealPackUtilityJar(String s_src, String s_dest) throws IOException {

    URL _src, _dest;//from  w w w. j a v a2s  .  c  o  m

    File f_src = new File(s_src);
    if (!f_src.isDirectory())
        throw new IOException(s_src + " is not a directory");
    _src = f_src.toURL();
    _dest = new File(s_dest).toURL();

    int path_l = s_dest.lastIndexOf("/");
    if (path_l > 0) {
        File dir = new File(s_dest.substring(0, path_l));
        if (!dir.exists())
            dir.mkdirs();
    }

    JarOutputStream jout = new JarOutputStream(new FileOutputStream(_dest.getFile()));
    // put all into the jar...
    add(jout, new File(_src.getFile()), "");
    jout.close();
}

From source file:net.sf.joost.trax.TrAXHelper.java

/**
 * HelperMethod for initiating StxEmitter.
 * @param result A <code>Result</code> object.
 * @return An <code>StxEmitter</code>.
 * @throws javax.xml.transform.TransformerException
 *///from  w w w .j  av  a2  s  .  c o  m
public static StxEmitter initStxEmitter(Result result, Processor processor, Properties outputProperties)
        throws TransformerException {

    if (outputProperties == null)
        outputProperties = processor.outputProperties;

    if (DEBUG)
        log.debug("init StxEmitter");
    // Return the content handler for this Result object
    try {
        // Result object could be SAXResult, DOMResult, or StreamResult
        if (result instanceof SAXResult) {
            final SAXResult target = (SAXResult) result;
            final ContentHandler handler = target.getHandler();
            if (handler != null) {
                if (DEBUG)
                    log.debug("return SAX specific Implementation for " + "StxEmitter");
                //SAX specific Implementation
                return new SAXEmitter(handler);
            }
        } else if (result instanceof DOMResult) {
            if (DEBUG)
                log.debug("return DOM specific Implementation for " + "StxEmitter");
            //DOM specific Implementation
            return new DOMEmitter((DOMResult) result);
        } else if (result instanceof StreamResult) {
            if (DEBUG)
                log.debug("return StreamResult specific Implementation " + "for StxEmitter");
            // Get StreamResult
            final StreamResult target = (StreamResult) result;
            // StreamResult may have been created with a java.io.File,
            // java.io.Writer, java.io.OutputStream or just a String
            // systemId.
            // try to get a Writer from Result object
            final Writer writer = target.getWriter();
            if (writer != null) {
                if (DEBUG)
                    log.debug("get a Writer object from Result object");
                return StreamEmitter.newEmitter(writer, DEFAULT_ENCODING, outputProperties);
            }
            // or try to get an OutputStream from Result object
            final OutputStream ostream = target.getOutputStream();
            if (ostream != null) {
                if (DEBUG)
                    log.debug("get an OutputStream from Result object");
                return StreamEmitter.newEmitter(ostream, outputProperties);
            }
            // or try to get just a systemId string from Result object
            String systemId = result.getSystemId();
            if (DEBUG)
                log.debug("get a systemId string from Result object");
            if (systemId == null) {
                if (DEBUG)
                    log.debug("JAXP_NO_RESULT_ERR");
                throw new TransformerException("JAXP_NO_RESULT_ERR");
            }
            // System Id may be in one of several forms, (1) a uri
            // that starts with 'file:', (2) uri that starts with 'http:'
            // or (3) just a filename on the local system.
            OutputStream os = null;
            URL url = null;
            if (systemId.startsWith("file:")) {
                url = new URL(systemId);
                os = new FileOutputStream(url.getFile());
                return StreamEmitter.newEmitter(os, outputProperties);
            } else if (systemId.startsWith("http:")) {
                url = new URL(systemId);
                URLConnection connection = url.openConnection();
                os = connection.getOutputStream();
                return StreamEmitter.newEmitter(os, outputProperties);
            } else {
                // system id is just a filename
                File tmp = new File(systemId);
                url = tmp.toURL();
                os = new FileOutputStream(url.getFile());
                return StreamEmitter.newEmitter(os, outputProperties);
            }
        }
        // If we cannot create the file specified by the SystemId
    } catch (IOException iE) {
        if (DEBUG)
            log.debug(iE);
        throw new TransformerException(iE);
    } catch (ParserConfigurationException pE) {
        if (DEBUG)
            log.debug(pE);
        throw new TransformerException(pE);
    }
    return null;
}

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

private static Document loadEncryptionDocument() throws Exception {

    String fileName = "encryptedInfo.xml";
    File encryptionFile = new File(fileName);
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*  w w  w.  j a  va2  s.  c om*/
    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(encryptionFile);
    System.out.println("Encryption document loaded from " + encryptionFile.toURL().toString());
    return document;
}

From source file:org.squidy.designer.util.SourceCodeUtils.java

/**
 * @param processable/*  w  w  w.java2  s .c  om*/
 * @return
 */
public static URL getSourceCode(Processable processable) throws MalformedURLException {

    String processableName = processable.getClass().getName();
    processableName = processableName.replace('.', '/');

    URL sourceUrl = SourceCodeUtils.class.getClassLoader().getResource(processableName + ".java");
    if (sourceUrl == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Could not find source in dynamic code repository.");
        }
        sourceUrl = NodeShape.class.getResource(processableName + ".java");
    }

    if (sourceUrl == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Could not find source in classpath.");
        }

        File sourceFile = new File("src/main/java/" + processableName + ".java");

        // TODO [RR]: Change this path to a dynamic path.
        if (sourceFile == null || !sourceFile.exists()) {
            sourceFile = new File("src/main/java/" + processableName + ".java");
        }

        sourceUrl = sourceFile.toURL();
    }

    return sourceUrl;
}

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

public static FacesConfigBean getConfigBean(String facesConfig) throws Exception {

    FacesConfigBean fcb = null;/*from w  w w .ja  v  a2 s . c o m*/
    InputStream stream = null;
    try {
        File file = new File(facesConfig);
        stream = new BufferedInputStream(new FileInputStream(file));
        InputSource source = new InputSource(file.toURL().toString());
        source.setByteStream(stream);
        fcb = (FacesConfigBean) createDigester(true, false, true).parse(source);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (Exception e) {
                ;
            }
            stream = null;
        }
    }
    return (fcb);

}