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.ow2.proactive.resourcemanager.utils.PAAgentServiceRMStarter.java

/**
 * To define the default log4j configuration if log4j.configuration property has not been set.
 *///w  ww .  j  a  va2s .c o m
public static void checkLog4jConfiguration() {
    try {
        String log4jPath = System.getProperty("log4j.configuration");
        if (log4jPath == null) {
            //either sched-home/dist/lib/PA-RM.jar or sched-home/classes/resource-manager/
            File origin = new File(PAAgentServiceRMStarter.class.getProtectionDomain().getCodeSource()
                    .getLocation().getFile());
            File parent = origin.getParentFile();
            configuration: {
                while (parent != null && parent.isDirectory()) {
                    File[] childs = parent.listFiles();
                    for (File child : childs) {
                        if ("config".equals(child.getName())) {
                            //we have found the sched-home/config/ directory!
                            log4jPath = child.getAbsolutePath() + File.separator + "log4j" + File.separator
                                    + "log4j-defaultNode";
                            File log4j = new File(log4jPath);
                            if (log4j.exists()) {
                                URL log4jURL;
                                try {
                                    log4jURL = log4j.toURL();
                                    PropertyConfigurator.configure(log4jURL);
                                    System.setProperty("log4j.configuration", log4jPath);
                                    logger.trace("log4j.configuration not set, " + log4jPath
                                            + " defiined as default log4j configuration.");
                                } catch (MalformedURLException e) {
                                    logger.trace("Cannot configure log4j", e);
                                }
                            } else {
                                logger.trace("Log4J configuration not found. Cannot configure log4j");
                            }
                            break configuration;
                        }
                    }
                    parent = parent.getParentFile();
                }
            }
        } else {
            logger.trace("Does not override log4j.configuration");
        }
    } catch (Exception ex) {
        logger.trace("Cannot set log4j Configuration", ex);
    }
}

From source file:com.safi.workshop.application.ChooseSafiServerWorkspaceData.java

/**
 * The workspace data is stored in the well known file pointed to by the result of this
 * method./*  w ww  . jav a  2s .  c om*/
 * 
 * @param create
 *          If the directory and file does not exist this parameter controls whether it
 *          will be created.
 * @return An url to the file and null if it does not exist or could not be created.
 */
private static URL getPersistenceUrl(URL baseUrl, boolean create) {
    if (baseUrl == null) {
        return null;
    }

    try {
        // make sure the directory exists
        URL url = new URL(baseUrl, PERS_FOLDER);
        File dir = new File(url.getFile());
        if (!dir.exists() && (!create || !dir.mkdir())) {
            return null;
        }

        // make sure the file exists
        url = new URL(dir.toURL(), PERS_FILENAME);
        File persFile = new File(url.getFile());
        if (!persFile.exists() && (!create || !persFile.createNewFile())) {
            return null;
        }

        return persFile.toURL();
    } catch (IOException e) {
        // cannot log because instance area has not been set
        return null;
    }
}

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
 * ReportExporter/* ww w.ja  v a 2  s .  c o m*/
 *
 * @param templateID
 * @param datasource
 * @return
 */
static String prepareReportResponse(HttpServletResponse response, Integer templateID,
        Map<String, Object> contextMap, Map<String, Object> description, Object datasource,
        Map<String, Object> parameters, ServletContext servletContext, TPersonBean personBean, Locale locale) {
    URL baseURL = null;
    String logoFolder = null;
    URL completeURL = null;
    String baseFileName = null;
    if (templateID == null) {
        final String baseFolder = "/design/silver/";
        // direct pdf/xls from report overview
        try {
            // set the baseURL to take some standard icons from
            // "/design/silver/icons"
            // which ale already used by the report overview anyway
            baseURL = servletContext.getResource(baseFolder + "16x16");
            LOGGER.debug("baseURL: " + baseURL.toString());
        } catch (final MalformedURLException e) {
            LOGGER.error("Getting the baseURL for " + baseFolder + "16x16 failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
        // set the baseURL to take some standard icons from
        // "/design/silver/icons"
        // which ale already used by the report overview anyway
        logoFolder = HandleHome.getTrackplus_Home() + File.separator + HandleHome.LOGOS_DIR + File.separator;
    } else {
        // template exists
        final File template = ReportBL.getDirTemplate(templateID);
        final ILabelBean templateBean = ReportFacade.getInstance().getByKey(templateID);
        if (templateBean != null) {
            baseFileName = templateBean.getLabel();
        }
        try {
            baseURL = template.toURL();
            LOGGER.debug("baseURL: " + baseURL.toString());
        } catch (final MalformedURLException e) {
            LOGGER.error("Wrong template URL for " + template.getName() + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
            return null;
        }
        try {
            completeURL = new URL(baseURL.toExternalForm() /*
                                                           * +
                                                           * "/"File.separator
                                                           */
                    + description.get(IDescriptionAttributes.MASTERFILE));
            completeURL.openStream();
            LOGGER.debug("completeURL: " + completeURL.toString());
        } catch (final Exception me) {
            LOGGER.error(LocalizeUtil.getParametrizedString(
                    "report.reportExportManager.err.masterFileTemplateNotFound",
                    new String[] { me.getMessage() }, locale) + me);
            return null;
        }
    }
    if (parameters == null) {
        parameters = new HashMap<String, Object>();
    }
    parameters.put(JasperReportExporter.REPORT_PARAMETERS.BASE_URL, baseURL);
    if (logoFolder != null) {
        parameters.put(JasperReportExporter.REPORT_PARAMETERS.LOGO_FOLDER_URL, logoFolder);
    }
    if (completeURL != null) {
        parameters.put(JasperReportExporter.REPORT_PARAMETERS.COMPLETE_URL, completeURL);
    }
    if (baseFileName == null) {
        baseFileName = "TrackReport";
    }
    baseFileName += DateTimeUtils.getInstance().formatISODateTime(new Date());
    response.reset();
    final String format = (String) description.get(IDescriptionAttributes.FORMAT);
    if (ReportExporter.FORMAT_PDF.equals(format)) {
        response.setHeader("Content-Type", "application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".pdf\"");
    } else if (ReportExporter.FORMAT_RTF.equals(format)) {
        response.setHeader("Content-Type", "application/rtf");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".rtf\"");
    } else if (ReportExporter.FORMAT_XML.equals(format)) {
        response.setHeader("Content-Type", "text/xml");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".xml\"");
    } else if (ReportExporter.FORMAT_HTML.equals(format)) {
        response.setHeader("Content-Type", "text/html");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".html\"");
    } else if (ReportExporter.FORMAT_ZIP.equals(format)) {
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".zip\"");
    } else if (ReportExporter.FORMAT_XLS.equals(format)) {
        response.setHeader("Content-Type", "application/xls");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".xls\"");
    } else if (ReportExporter.FORMAT_CSV.equals(format)) {
        final String csvEncoding = personBean.getCsvEncoding();
        LOGGER.debug("csvEncoding is " + csvEncoding);
        if (csvEncoding != null) {
            response.setContentType("text/plain; " + csvEncoding);
        } else {
            response.setContentType("text/plain; charset=UTF-8");
        }
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".csv\"");
    } else if (ReportExporter.FORMAT_DOCX.equals(format)) {
        response.setHeader("Content-Type",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".docx\"");
    }
    DownloadUtil.prepareCacheControlHeader(ServletActionContext.getRequest(), response);
    OutputStream outputStream = null;
    try {
        outputStream = response.getOutputStream();
    } catch (final IOException e) {
        LOGGER.error("Getting the output stream failed with " + e.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    try {
        LOGGER.debug("Exporter type is " + description.get(IDescriptionAttributes.TYPE) + " exporter format is "
                + description.get(IDescriptionAttributes.FORMAT));
        final ReportExporter exporter = ReportExecuteBL
                .getExporter((String) description.get(IDescriptionAttributes.TYPE));
        exporter.exportReport((Document) datasource, personBean, locale, parameters, outputStream, contextMap,
                description);
        LOGGER.debug("Export done...");
    } catch (final ReportExportException e) {
        LOGGER.error("Exporting the report failed with " + e.getMessage());
        String actionMessage = "";
        if (e.getCause() != null) {
            actionMessage = LocalizeUtil.getParametrizedString(e.getMessage(),
                    new String[] { e.getCause().getMessage() }, locale);
        } else {
            actionMessage = LocalizeUtil.getLocalizedTextFromApplicationResources(e.getMessage(), locale);
        }
        LOGGER.error(actionMessage);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    } catch (final Exception e) {
        LOGGER.error("Exporting the report failed with throwable " + e.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    return null;
}

From source file:org.apache.servicemix.jbi.deployer.descriptor.DescriptorFactory.java

/**
 * Build a jbi descriptor from a file archive.
 *
 * @param descriptorFile path to the jbi descriptor, or to the root directory
 * @return the Descriptor object//from ww w . j ava2  s .  c  om
 */
public static Descriptor buildDescriptor(File descriptorFile) {
    if (descriptorFile.isDirectory()) {
        descriptorFile = new File(descriptorFile, DESCRIPTOR_FILE);
    }
    if (descriptorFile.isFile()) {
        try {
            return buildDescriptor(descriptorFile.toURL());
        } catch (MalformedURLException e) {
            throw new RuntimeException("There is a bug here...", e);
        }
    }
    return null;
}

From source file:org.apache.servicemix.jbi.deployer.descriptor.DescriptorFactory.java

/**
 * Retrieves the jbi descriptor as a string
 *
 * @param descriptorFile path to the jbi descriptor, or to the root directory
 * @return the contents of the jbi descriptor
 *///from   w w  w . java 2  s.c  om
public static String getDescriptorAsText(File descriptorFile) {
    if (descriptorFile.isDirectory()) {
        descriptorFile = new File(descriptorFile, DESCRIPTOR_FILE);
    }
    if (descriptorFile.isFile()) {
        try {
            return getDescriptorAsText(descriptorFile.toURL());
        } catch (MalformedURLException e) {
            //log.debug("Error reading jbi descritor: " + descriptorFile, e);
        }
    }
    return null;
}

From source file:org.apache.sentry.service.thrift.SentryService.java

@SuppressWarnings("deprecation")
public static Configuration loadConfig(String configFileName) throws MalformedURLException {
    File configFile = null;
    if (configFileName == null) {
        throw new IllegalArgumentException(
                "Usage: " + ServiceConstants.ServiceArgs.CONFIG_FILE_LONG + " path/to/sentry-service.xml");
    } else if (!((configFile = new File(configFileName)).isFile() && configFile.canRead())) {
        throw new IllegalArgumentException("Cannot read configuration file " + configFile);
    }//from  ww w.j  a va2s  .  c  o m
    Configuration conf = new Configuration(false);
    conf.addResource(configFile.toURL());
    return conf;
}

From source file:org.apache.axis2.jaxws.runtime.description.marshal.impl.PackageSetBuilder.java

private static Definition getWSDLDefinition(String wsdlLoc) {
    Definition wsdlDefinition = null;// w  w w. j av a  2 s . c o  m
    final String wsdlLocation = wsdlLoc;
    if (wsdlLocation != null && wsdlLocation.trim().length() > 0) {
        try {
            wsdlDefinition = (Definition) AccessController.doPrivileged(new PrivilegedExceptionAction() {
                public Object run() throws MalformedURLException, IOException, WSDLException {
                    String baseDir = new File(System.getProperty("basedir", ".")).getCanonicalPath();
                    String wsdlLocationPath = new File(baseDir + File.separator + wsdlLocation)
                            .getAbsolutePath();
                    File file = new File(wsdlLocationPath);
                    URL url = file.toURL();
                    if (log.isDebugEnabled()) {
                        log.debug("Reading WSDL from URL:" + url.toString());
                    }
                    // This is a temporary wsdl and we use it to dig into the schemas,
                    // Thus the memory limit is set to false.  It will be discarded after it is used
                    // by the PackageSetBuilder implementation.
                    WSDLWrapper wsdlWrapper = new WSDL4JWrapper(url, false, 0);
                    return wsdlWrapper.getDefinition();
                }
            });
        } catch (PrivilegedActionException e) {
            // Swallow and continue
            if (log.isDebugEnabled()) {
                log.debug("Exception getting wsdlLocation: " + e.getException());
            }
        }
    }

    return wsdlDefinition;
}

From source file:com.krawler.runtime.utils.URLClassLoaderUtil.java

public void addFile(File f) throws Exception {
    this.addJarURL(f.toURL());
}

From source file:org.ops4j.pax.runner.platform.internal.AbsoluteFilePathStrategy.java

/**
 * {@inheritDoc}//from ww w  . ja  v  a  2 s.  c  om
 */
public String normalizeAsUrl(final File file) {
    try {
        return file.toURL().toExternalForm();
    } catch (MalformedURLException e) {
        // actually this should never occur
        return "file:/" + file.getAbsolutePath().replace(File.separatorChar, '/');
    }
}

From source file:org.talend.mdm.commmon.util.datamodel.management.SecurityEntityResolver.java

public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    if (systemId != null) {
        Pattern httpUrl = Pattern.compile("(http|https|ftp):(\\//|\\\\)(.*):(.*)"); //$NON-NLS-1$
        Matcher match = httpUrl.matcher(systemId);
        if (match.matches()) {
            StringBuilder buffer = new StringBuilder();
            String credentials = Base64.encodeBase64String("admin:talend".getBytes()); //$NON-NLS-1$
            URL url = new URL(systemId);
            URLConnection conn = url.openConnection();
            conn.setAllowUserInteraction(true);
            conn.setDoOutput(true);/*  w  w  w. j  ava 2  s.  c o  m*/
            conn.setDoInput(true);
            conn.setRequestProperty("Authorization", "Basic " + credentials); //$NON-NLS-1$
            conn.setRequestProperty("Expect", "100-continue"); //$NON-NLS-1$
            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:///"); //$NON-NLS-1$
            String path = systemId.substring((mark != -1 ? mark + "file:///".length() : 0)); //$NON-NLS-1$
            File file = new File(path);
            return new InputSource(file.toURL().openStream());
        }

    }
    return null;
}