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:org.apache.axis2.jaxws.util.BaseWSDLLocator.java

/**
 * Returns an InputSource pointed at an imported wsdl document whose
 * parent document was located at parentLocation and whose
 * relative location to the parent document is specified by
 * relativeLocation./*  w  w w  . ja va 2s  .  com*/
 *
 * @param parentLocation a URI specifying the location of the
 * document doing the importing.
 * @param relativeLocation a URI specifying the location of the
 * document to import, relative to the parent document's location.
 */
public InputSource getImportInputSource(String parentLocation, String relativeLocation) {
    if (log.isDebugEnabled()) {
        log.debug("getImportInputSource, parentLocation= " + parentLocation + " relativeLocation= "
                + relativeLocation);
    }
    InputStream is = null;
    URL absoluteURL = null;

    String redirectedURI = getRedirectedURI(relativeLocation, parentLocation);
    if (redirectedURI != null)
        relativeLocation = redirectedURI;

    try {
        if (isAbsoluteImport(relativeLocation)) {
            try {
                absoluteURL = new URL(relativeLocation);
                is = absoluteURL.openStream();
                lastestImportURI = absoluteURL.toExternalForm();
            } catch (Throwable t) {
                if (relativeLocation.startsWith("file://")) {
                    try {
                        relativeLocation = "file:/" + relativeLocation.substring("file://".length());
                        absoluteURL = new URL(relativeLocation);
                        is = absoluteURL.openStream();
                        lastestImportURI = absoluteURL.toExternalForm();
                    } catch (Throwable t2) {
                    }
                }
            }
            if (is == null) {
                try {
                    URI fileURI = new URI(relativeLocation);
                    absoluteURL = fileURI.toURL();
                    is = absoluteURL.openStream();
                    lastestImportURI = absoluteURL.toExternalForm();
                } catch (Throwable t) {
                    //No FFDC code needed  
                }
            }
            if (is == null) {
                try {
                    File file = new File(relativeLocation);
                    absoluteURL = file.toURL();
                    is = absoluteURL.openStream();
                    lastestImportURI = absoluteURL.toExternalForm();
                } catch (Throwable t) {
                    //No FFDC code needed           
                }
            }

        } else {
            String importPath = normalizePath(parentLocation, relativeLocation);
            is = getInputStream(importPath);
            lastestImportURI = importPath;
        }
    } catch (IOException ex) {
        throw ExceptionFactory.makeWebServiceException(
                Messages.getMessage("WSDLRelativeErr1", relativeLocation, parentLocation, ex.toString()));
    }
    if (is == null) {
        throw ExceptionFactory.makeWebServiceException(
                Messages.getMessage("WSDLRelativeErr2", relativeLocation, parentLocation));
    }
    if (log.isDebugEnabled()) {
        log.debug("Loaded file: " + relativeLocation);
    }
    return new InputSource(is);
}

From source file:org.apache.catalina.startup.SetDocBaseRule.java

/**
 * Handle the beginning of an XML element.
 *
 * @param attributes The attributes of this element
 *
 * @exception Exception if a processing error occurs
 *///from   w w w. j a va  2s.  co m
public void begin(Attributes attributes) throws Exception {

    Context child = (Context) digester.peek(0);
    Deployer parent = (Deployer) digester.peek(1);
    Host host = null;
    if (!(parent instanceof StandardHost)) {
        Method method = parent.getClass().getMethod("getHost", null);
        host = (Host) method.invoke(parent, null);
    } else {
        host = (Host) parent;
    }
    String appBase = host.getAppBase();

    boolean unpackWARs = true;
    if (host instanceof StandardHost) {
        unpackWARs = ((StandardHost) host).isUnpackWARs();
    }
    if (!unpackWARs && !("true".equals(attributes.getValue("unpackWAR")))) {
        return;
    }
    if ("false".equals(attributes.getValue("unpackWAR"))) {
        return;
    }

    File canonicalAppBase = new File(appBase);
    if (canonicalAppBase.isAbsolute()) {
        canonicalAppBase = canonicalAppBase.getCanonicalFile();
    } else {
        canonicalAppBase = new File(System.getProperty("catalina.base"), appBase).getCanonicalFile();
    }

    String docBase = child.getDocBase();
    if (docBase == null) {
        // Trying to guess the docBase according to the path
        String path = child.getPath();
        if (path == null) {
            return;
        }
        if (path.equals("")) {
            docBase = "ROOT";
        } else {
            if (path.startsWith("/")) {
                docBase = path.substring(1);
            } else {
                docBase = path;
            }
        }
    }

    File file = new File(docBase);
    if (!file.isAbsolute()) {
        docBase = (new File(canonicalAppBase, docBase)).getPath();
    } else {
        docBase = file.getCanonicalPath();
    }

    if (docBase.toLowerCase().endsWith(".war")) {
        URL war = new URL("jar:" + (new File(docBase)).toURL() + "!/");
        String contextPath = child.getPath();
        if (contextPath.equals("")) {
            contextPath = "ROOT";
        }
        docBase = ExpandWar.expand(host, war, contextPath);
        file = new File(docBase);
        docBase = file.getCanonicalPath();
    } else {
        File docDir = new File(docBase);
        if (!docDir.exists()) {
            File warFile = new File(docBase + ".war");
            if (warFile.exists()) {
                URL war = new URL("jar:" + warFile.toURL() + "!/");
                docBase = ExpandWar.expand(host, war, child.getPath());
                file = new File(docBase);
                docBase = file.getCanonicalPath();
            }
        }
    }

    if (docBase.startsWith(canonicalAppBase.getPath())) {
        docBase = docBase.substring(canonicalAppBase.getPath().length());
        docBase = docBase.replace(File.separatorChar, '/');
        if (docBase.startsWith("/")) {
            docBase = docBase.substring(1);
        }
    } else {
        docBase = docBase.replace(File.separatorChar, '/');
    }

    child.setDocBase(docBase);

}

From source file:org.kuali.rice.kew.batch.XmlIngestionTest.java

protected boolean verifyFileExists(File dir, File file) throws IOException {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = resolver.getResources(dir.toURL() + "/**/" + file.getName());
    if (resources == null) {
        return false;
    }//w ww .  j  a  v  a2  s . c o m
    for (int i = 0; i < resources.length; i++) {
        if (resources[i].exists()) {
            return true;
        }
    }
    return false;
}

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

/**
 * Convert.//w  ww  . ja  va 2 s  . c  o  m
 * 
 * @param fileSource the file source
 * @param destDir the dest dir
 */
public synchronized void convert(File fileSource, File destDir) {

    XComponent xComponent = null;
    OOOConnection oooConn = null;
    OOODocument oooDoc = null;

    try {
        oooConn = connect();

        // 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);

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

        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);

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

        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;

            String slideName = destDir.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 \"" + destDir.getAbsolutePath()
                    + "\" in the local directory");

        }
    } 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);
        }
    }
}

From source file:org.apache.tomcat.util.compat.JdkCompat.java

/**
 *  Return the URI for the given file. Originally created for
 *  o.a.c.loader.WebappClassLoader/*from  w w  w. j a va2 s. co  m*/
 *
 *  @param File to wrap into URI
 *  @return A URI as a URL
 */
public URL getURI(File file) throws MalformedURLException {

    File realFile = file;
    try {
        realFile = realFile.getCanonicalFile();
    } catch (IOException e) {
        // Ignore
    }

    return realFile.toURL();
}

From source file:org.mobicents.slee.container.management.console.server.deployableunits.DeployableUnitsInstallService.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    try {/*  w  w  w  .ja  va2 s. co m*/
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();

                File uploadedFile = new File(
                        System.getProperty("jboss.server.temp.dir") + File.separator + fileName);
                item.write(uploadedFile);

                sleeConnection.getSleeManagementMBeanUtils().getDeploymentMBeanUtils()
                        .install(uploadedFile.toURL().toString());
                uploadedFile.delete();
            }
        }
        out.print(DeployableUnitsService.SUCCESS_CODE);
    } catch (Exception e) {
        e.printStackTrace();
        out.print(e.getMessage());
    }
}

From source file:com.microsoft.tfs.core.internal.db.ConnectionConfiguration.java

public ConnectionConfiguration(final PersistenceStore cacheStore, final String pathId,
        final boolean verboseInput) {
    Check.notNull(cacheStore, "cacheStore"); //$NON-NLS-1$

    pathIdentifer = Metadata.SCHEMA_VERSION + "-" + pathId; //$NON-NLS-1$
    verbose = verboseInput;/*from www  .ja v  a2  s.c  o  m*/

    configuration = new Configuration(ConnectionConfiguration.class, "/" + DB_PROPS_FILE_NAME); //$NON-NLS-1$

    driverClass = configuration.getConfiguration(DRIVER_CONFIG_KEY, DRIVER_DEFAULT);
    url = configuration.getConfiguration(URL_CONFIG_KEY, URL_DEFAULT);
    username = configuration.getConfiguration(USERNAME_CONFIG_KEY, USERNAME_DEFAULT);
    password = configuration.getConfiguration(PASSWORD_CONFIG_KEY, PASSWORD_DEFAULT);

    final String extraClasspath = configuration.getConfiguration(CLASSPATH_CONFIG_KEY, null);

    if (url.equals(URL_DEFAULT)) {
        if (cacheStore instanceof VersionedVendorFilesystemPersistenceStore) {
            /*
             * This may still return null if no candidate areas were
             * lockable.
             */
            databaseDiskDirectory = getDirectoryForDiskDatabase(
                    (VersionedVendorFilesystemPersistenceStore) cacheStore, pathIdentifer);
        } else {
            log.warn(MessageFormat.format(
                    "The {0} used to create {1} is not a {2}, which is required to retarget HSQLDB storage (it can only use files).  The fallback URL of {3} will be used.", //$NON-NLS-1$
                    PersistenceStore.class.getName(), ConnectionConfiguration.class.getName(),
                    VersionedVendorFilesystemPersistenceStore.class.getName(), URL_FALLBACK));
        }

        if (databaseDiskDirectory == null) {
            url = URL_FALLBACK;
        } else {
            final File db = new File(databaseDiskDirectory, "teamexplorer"); //$NON-NLS-1$
            url = "jdbc:hsqldb:file:" + db.getAbsolutePath(); //$NON-NLS-1$
        }
    }

    ClassLoader jdbcLoader = getClass().getClassLoader();

    if (extraClasspath != null) {
        final File extraJar = new File(extraClasspath);
        try {
            jdbcLoader = new URLClassLoader(new URL[] { extraJar.toURL() }, jdbcLoader);
        } catch (final MalformedURLException ex) {
            throw new RuntimeException(ex);
        }
    }

    try {
        driver = (Driver) jdbcLoader.loadClass(driverClass).newInstance();
    } catch (final Throwable t) {
        throw new RuntimeException(MessageFormat.format("unable to load specified jdbc driver class [{0}]", //$NON-NLS-1$
                driverClass), t);
    }

    if (verbose) {
        System.out.println(MessageFormat.format("DB connection URL:     [{0}]", url)); //$NON-NLS-1$
        System.out.println(MessageFormat.format("DB driver class:       [{0}] (version {1}.{2})", //$NON-NLS-1$
                driver.getClass().getName(), Integer.toString(driver.getMajorVersion()),
                Integer.toString(driver.getMinorVersion())));

        System.out.println(MessageFormat.format("DB driver loaded from: [{0}]", //$NON-NLS-1$
                getDriverClassURL().toExternalForm()));
    }
}

From source file:org.wso2.carbon.server.CarbonLauncher.java

/**
 * buildInitialPropertyMap create the initial set of properties from the contents of launch.ini
 * and for a few other properties necessary to launch defaults are supplied if not provided.
 * The value '@null' will set the map value to null.
 *
 * @return a map containing the initial properties
 *//*w  w w . j ava2s.co m*/
private Map<String, String> buildInitialPropertyMap() {
    Map<String, String> initialPropertyMap = new HashMap<String, String>();
    String carbonHome = System.getProperty(LauncherConstants.CARBON_HOME);
    Properties launchProperties = Utils.loadProperties(carbonHome + File.separator + "repository"
            + File.separator + "conf" + File.separator + "etc" + File.separator + LauncherConstants.LAUNCH_INI);
    for (Object o : launchProperties.entrySet()) {
        Map.Entry entry = (Map.Entry) o;
        String key = (String) entry.getKey();
        String value = (String) entry.getValue();
        if (key.endsWith("*")) { //$NON-NLS-1$
            if (value.equals(NULL_IDENTIFIER)) {
                Utils.clearPrefixedSystemProperties(key.substring(0, key.length() - 1), initialPropertyMap);
            }
        } else if (value.equals(NULL_IDENTIFIER)) {
            initialPropertyMap.put(key, null);
        } else {
            initialPropertyMap.put((String) entry.getKey(), (String) entry.getValue());
        }
    }
    try {

        /**
        *  in order to support multiple profiling, the new install, configuration and workspace area got to move
        *  from ../components/ to ../components/ PROFILE_ID/
        */
        // install.area if not specified
        if (initialPropertyMap.get(OSGI_INSTALL_AREA) == null) {
            //specifying the install.area according to the running Profile
            File installDir = new File(platformDirectory, System.getProperty(LauncherConstants.PROFILE_ID));

            initialPropertyMap.put(OSGI_INSTALL_AREA, installDir.toURL().toExternalForm());
        }

        // configuration.area if not specified
        if (initialPropertyMap.get(OSGI_CONFIGURATION_AREA) == null) {
            File configurationDirectory = new File(platformDirectory,
                    System.getProperty(LauncherConstants.PROFILE_ID) + File.separator + "configuration");
            initialPropertyMap.put(OSGI_CONFIGURATION_AREA, configurationDirectory.toURL().toExternalForm());
        }

        // instance.area if not specified
        if (initialPropertyMap.get(OSGI_INSTANCE_AREA) == null) {
            File workspaceDirectory = new File(platformDirectory,
                    System.getProperty(LauncherConstants.PROFILE_ID) + File.separator + "workspace");
            initialPropertyMap.put(OSGI_INSTANCE_AREA, workspaceDirectory.toURL().toExternalForm());
        }

        // osgi.framework if not specified
        if (initialPropertyMap.get(OSGI_FRAMEWORK) == null) {
            // search for osgi.framework in osgi.install.area
            /*String installArea = initialPropertyMap.get(OSGI_INSTALL_AREA);
                    
            // only support file type URLs for install area
            if (installArea.startsWith(FILE_SCHEME)) {
            installArea = installArea.substring(FILE_SCHEME.length());
            }
                    
            String path = new File(installArea, "plugins").toString();*/
            String path = new File(platformDirectory, "plugins").toString();
            path = Utils.searchFor(FRAMEWORK_BUNDLE_NAME, path);
            if (path == null) {
                throw new RuntimeException("Could not find framework");
            }

            initialPropertyMap.put(OSGI_FRAMEWORK, new File(path).toURL().toExternalForm());
        }
        if (initialPropertyMap.get(P2_DATA_AREA) == null) {
            /*initialPropertyMap.put(P2_DATA_AREA, new File(platformDirectory, System.getProperty(LauncherConstants.PROFILE_ID) +
                                                           File.separator + "p2").toString());*/

            initialPropertyMap.put(P2_DATA_AREA, new File(platformDirectory, "p2").toString());
            //System.out.println("the data area: " + initialPropertyMap.get(P2_DATA_AREA));
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException("Error establishing location");
    }
    return initialPropertyMap;
}

From source file:org.freeplane.main.application.UserPropertiesUpdater.java

void importOldDefaultStyle() {
    final ModeController modeController = Controller.getCurrentController()
            .getModeController(MModeController.MODENAME);
    MFileManager fm = MFileManager.getController(modeController);
    final String standardTemplateName = fm.getStandardTemplateName();
    final File userDefault;
    final File absolute = new File(standardTemplateName);
    if (absolute.isAbsolute())
        userDefault = absolute;//from   w  w  w  . j a  va2  s .c o m
    else {
        final File userTemplates = fm.defaultUserTemplateDir();
        userDefault = new File(userTemplates, standardTemplateName);
    }
    if (userDefault.exists()) {
        return;
    }
    userDefault.getParentFile().mkdirs();
    if (!userDefault.getParentFile().exists()) {
        return;
    }
    MapModel defaultStyleMap = new MapModel();
    final File allUserTemplates = fm.defaultStandardTemplateDir();
    final File standardTemplate = new File(allUserTemplates, "standard.mm");
    try {
        fm.loadCatchExceptions(standardTemplate.toURL(), defaultStyleMap);
    } catch (Exception e) {
        LogUtils.warn(e);
        try {
            fm.loadCatchExceptions(
                    ResourceController.getResourceController().getResource("/styles/viewer_standard.mm"),
                    defaultStyleMap);
        } catch (Exception e2) {
            defaultStyleMap.createNewRoot();
            LogUtils.severe(e);
        }
    }
    final NodeStyleController nodeStyleController = NodeStyleController.getController(modeController);
    updateDefaultStyle(nodeStyleController, defaultStyleMap);
    updateNoteStyle(nodeStyleController, defaultStyleMap);

    try {
        fm.writeToFile(defaultStyleMap, userDefault);
    } catch (IOException e) {
    }

}

From source file:org.hyperic.hq.hqu.PluginWrapper.java

PluginWrapper(File pluginDir, ClassLoader parentLoader) {
    GroovyClassLoader groovyLoader = new GroovyClassLoader(parentLoader);

    _pluginDir = pluginDir;//from w w w. j  a  va2s.c o  m

    try {
        File tmpDir = getTempDir();
        File libDir = new File(_pluginDir, "lib");

        if (libDir.isDirectory()) {
            File[] files = libDir.listFiles();

            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile() && files[i].getName().endsWith(".jar")) {
                    String prefix = pluginDir.getName() + "-"
                            + files[i].getName().substring(0, files[i].getName().length() - 4);
                    File tmpJar = File.createTempFile(prefix, ".jar", tmpDir);
                    FileUtil.copyFile(files[i], tmpJar);
                    tmpJar.deleteOnExit();
                    groovyLoader.addURL(tmpJar.toURL());
                    _log.info("Added url [" + tmpJar.toURL() + "] to plugin [" + pluginDir + "]");
                }
            }
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    _loader = groovyLoader;
}