Example usage for java.net URL getFile

List of usage examples for java.net URL getFile

Introduction

In this page you can find the example usage for java.net URL getFile.

Prototype

public String getFile() 

Source Link

Document

Gets the file name of this URL .

Usage

From source file:net.ontopia.topicmaps.xml.AbstractCanonicalExporterTests.java

/**
 * INTERNAL: Performs the actual canonicalization.
 *///ww w.  ja va  2s  .c om
protected void canonicalize(URL infile, File tmpfile, File outfile) throws IOException {
    // Get store factory
    TopicMapStoreFactoryIF sfactory = getStoreFactory();

    // Read document
    TopicMapIF source1 = sfactory.createStore().getTopicMap();
    if (infile.getFile().endsWith(".xtm")) {
        XTMTopicMapReader reader = new XTMTopicMapReader(infile);
        reader.setValidation(false);
        reader.importInto(source1);
    } else {
        throw new OntopiaRuntimeException("Unknown syntax: " + infile);
    }

    // Export topic map, then read it back in
    TopicMapIF source2 = exportAndReread(source1, tmpfile);
    source1.getStore().close();

    // Canonicalize reimported document
    CanonicalTopicMapWriter cwriter = new CanonicalTopicMapWriter(outfile);
    cwriter.setBaseLocator(new URILocator(tmpfile));
    cwriter.write(source2);

    // Clean up
    source2.getStore().close();
}

From source file:eu.impact_project.wsclient.SOAPresults.java

private String useXslt(String xml, String xsltPath) throws TransformerException {
    InputStream soapStream = new ByteArrayInputStream(xml.getBytes());

    System.getProperty("javax.xml.parsers.DocumentBuilderFactory", "net.sf.saxon.TransformerFactoryImpl");

    Source xmlSource = new StreamSource(soapStream);

    URL urlxsl = getClass().getResource(xsltPath);
    File xsltFile = new File(urlxsl.getFile());

    Source xsltSource = new StreamSource(xsltFile);

    TransformerFactory transFact = TransformerFactory.newInstance();
    Transformer trans = transFact.newTransformer(xsltSource);

    ByteArrayOutputStream htmlOut = new ByteArrayOutputStream();
    Result res = new StreamResult(htmlOut);

    trans.transform(xmlSource, res);/*from  w w w  . j a v  a2 s  . c om*/

    return htmlOut.toString();

}

From source file:com.hypersocket.upgrade.UpgradeServiceImpl.java

private List<UpgradeOp> buildUpgradeOps() throws IOException {
    List<UpgradeOp> ops = new ArrayList<UpgradeOp>();
    for (Resource script : scripts) {
        URL url = script.getURL();

        url.getFile();

        String name = url.getPath();
        int idx;//from   w ww.  j  a  va 2s. co  m
        if ((idx = name.lastIndexOf("/")) > -1) {
            name = name.substring(idx + 1);
        }

        // Java identifiers (i.e. .java upgrade 'scripts') may only contain
        // _ and currency symbols. So we use $ for a dash (-) and  for dot
        // (.) as underscore is already used
        name = name.replace("_DASH_", "-");
        name = name.replace("_DOT_", ".");

        int moduleIdx = name.indexOf('_');
        String moduleName = name.substring(0, moduleIdx);
        name = name.substring(moduleIdx + 1);
        idx = name.lastIndexOf('.');
        ops.add(new UpgradeOp(new Version(name.substring(0, idx)), url, moduleName, name.substring(idx + 1)));
    }
    Collections.sort(ops);
    return ops;
}

From source file:net.sf.jasperreports.samples.wizards.SampleNewWizard.java

@Override
protected void createProject(IProgressMonitor monitor, IProject prj) throws CoreException, JavaModelException {
    Set<String> cpaths = new HashSet<String>();
    Set<String> lpaths = new HashSet<String>();
    super.createProject(monitor, prj);
    File copyto = prj.getLocation().toFile();
    Set<URL> paths = Activator.getSamplesManager().getURLs();
    Enumeration<?> en = Activator.getDefault().getBundle().findEntries("resources", "*", true); //$NON-NLS-1$ //$NON-NLS-2$
    while (en.hasMoreElements())
        paths.add((URL) en.nextElement());
    en = JasperReportsPlugin.getDefault().getBundle().findEntries("lib", "*.jar", true); //$NON-NLS-1$ //$NON-NLS-2$
    while (en.hasMoreElements())
        paths.add((URL) en.nextElement());
    for (URL url : paths) {
        OutputStream out = null;//  w w w. j a v  a2  s .  c  o  m
        InputStream in = null;
        if (url.getFile().endsWith(".zip")) {
            File zip = null;
            try {
                in = new BufferedInputStream(url.openStream(), 1024);
                zip = File.createTempFile("arc", ".zip", copyto);
                out = new BufferedOutputStream(new FileOutputStream(zip));
                FileUtils.copyInputStream(in, out);
                unpackArchive(zip, copyto, monitor, cpaths, lpaths);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                FileUtils.closeStream(in);
                FileUtils.closeStream(out);
                if (zip != null)
                    zip.delete();
            }
        } else {
            String path = url.getPath();
            File file = new File(copyto, File.separator + path);
            new File(file.getParent()).mkdirs();
            String fname = file.getName();
            try {
                org.apache.commons.io.FileUtils.copyURLToFile(url, file);
                if (file.getParentFile().getName().equals("src"))
                    cpaths.add(path.substring(0, path.lastIndexOf("/")));
                if (file.getParentFile().getParentFile().getName().equals("lib")
                        && (fname.endsWith(".jar") || fname.endsWith(".zip")))
                    lpaths.add(path);
                if (file.getParentFile().getName().equals("lib")
                        && (fname.endsWith(".jar") || fname.endsWith(".zip")))
                    lpaths.add(path);
            } catch (Exception e) {
                // e.printStackTrace();
            }
        }
        if (monitor.isCanceled())
            return;
    }
    IJavaProject project = JavaCore.create(prj);
    addSourceFolders(cpaths, project, monitor);
    addLibraries(lpaths, project, monitor);
    prj.refreshLocal(IProject.DEPTH_INFINITE, monitor);
    prj.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
    prj.close(monitor);
    prj.open(monitor);
}

From source file:com.googlecode.flyway.core.util.scanner.ClassPathScanner.java

/**
 * Finds the resources names present at this location and below on the classpath starting with this prefix and
 * ending with this suffix.//from w  w  w .  j  a va2s .  c  om
 *
 * @param location The location on the classpath to scan.
 * @param prefix   The filename prefix to match.
 * @param suffix   The filename suffix to match.
 * @return The resource names.
 * @throws IOException when scanning this location failed.
 */
private Set<String> findResourceNames(String location, String prefix, String suffix) throws IOException {
    Set<String> resourceNames = new TreeSet<String>();

    String normalizedLocation = normalizeLocation(location);

    Enumeration<URL> locationsUrls = getClassLoader().getResources(normalizedLocation);
    if (!locationsUrls.hasMoreElements()) {
        LOG.debug("Unable to determine URL for classpath location: " + normalizedLocation + " (ClassLoader: "
                + getClassLoader() + ")");
    }
    while (locationsUrls.hasMoreElements()) {
        URL locationUrl = locationsUrls.nextElement();
        LOG.debug("Scanning URL: " + locationUrl.toExternalForm());

        String scanRoot = URLDecoder.decode(locationUrl.getFile(), "UTF-8");
        if (scanRoot.endsWith("/")) {
            scanRoot = scanRoot.substring(0, scanRoot.length() - 1);
        }

        String protocol = locationUrl.getProtocol();
        LocationScanner locationScanner = createLocationScanner(protocol);
        if (locationScanner == null) {
            LOG.warn("Unable to scan location: " + scanRoot + " (unsupported protocol: " + protocol + ")");
        } else {
            resourceNames.addAll(locationScanner.findResourceNames(normalizedLocation, scanRoot));
        }
    }

    return filterResourceNames(resourceNames, prefix, suffix);
}

From source file:com.intellijob.BaseTester.java

/**
 * Reload collection users.//from w ww. j  a v a  2 s  .  c om
 * <p>
 * Drop collection if exist, create a new collection and load data.
 * Read data from collection_users.json
 *
 * @throws IOException exception.
 */
protected void reloadCollectionUsers() throws Exception {
    userRepository.deleteAll();
    URL collectionUserURL = Thread.currentThread().getContextClassLoader()
            .getResource("imports/collection_users.json");

    User user = new ObjectMapper().readValue(new File(collectionUserURL.getFile()), User.class);
    userRepository.save(user);
}

From source file:de.richsource.gradle.plugins.typescript.TypeScriptGradlePluginTest.java

private List<File> readPluginClasspath(URL pluginClasspathResource) throws IOException {
    File pluginClasspathManifest = new File(pluginClasspathResource.getFile());
    BufferedReader reader = new BufferedReader(new FileReader(pluginClasspathManifest));
    String line;/*  www .ja v  a2  s. c  om*/
    List<File> files = new ArrayList<File>();
    while ((line = reader.readLine()) != null) {
        files.add(new File(line));
    }
    return files;
}

From source file:com.vmware.qe.framework.datadriven.config.DDConfig.java

/**
 * Uses the current configuration data passed in as argument and does the following: <br>
 * 1. Look for config.properties file on class path and load it if present.<br>
 * 2. Look for config.path in CLI params. If present, load it and overwrite any existing
 * properties.<br>/*from  w  w  w  .j a  v  a  2s.co  m*/
 * 3. Overwrite existing data with whatever was specified via cli. <br>
 * 
 * @param testData test configuration data
 * @return processed test configuration data
 */
private synchronized Configuration prepareData(Configuration testData) {
    Configuration resultData = null;
    // step 1. config.properties on classpath
    URL cfgFile = this.getClass().getResource(DD_CONFIG_FILE_NAME);
    if (cfgFile != null) {
        log.info("Loading Configuration File: {}", cfgFile);
        resultData = getConfigFileData(cfgFile.getFile());
    } else {
        log.warn("Config file not found! " + DD_CONFIG_FILE_NAME);
    }
    if (resultData != null) {
        log.debug("Loaded data from " + DD_CONFIG_FILE_NAME + " on classpath");
    }
    // step 2. config file specified on cli
    if (testData.containsKey(TESTINPUT_CONFIG_PATH)) {
        String filePath = testData.getString(TESTINPUT_CONFIG_PATH);
        if (checkFilePath(filePath)) {
            Configuration tmpData = getConfigFileData(filePath);
            resultData = overrideConfigProperties(resultData, tmpData);
            log.debug("Loaded data from config file '{}'", filePath);
        }
    }
    log.debug("Overriding using properties specified via commandline arguments");
    resultData = overrideConfigProperties(resultData, testData);
    if (resultData == null) {
        String error = "Configuration data can not be null. Please specify test "
                + "configuration information via config file on classpath or filesystem or via cli";
        log.error(error);
        throw new DDException(error);
    }
    log.debug("DDConfig: {}", ConfigurationUtils.toString(resultData));
    return resultData;
}

From source file:com.oakhole.Generate.java

/**
 * ??@Entity/*from  w w  w.  ja  v a  2 s  . c om*/
 * @param packageToScan
 * @return
 * @throws java.io.IOException
 */
private Set<Class<?>> autoScan(String packageToScan) throws IOException {

    Set<Class<?>> entities = Sets.newConcurrentHashSet();

    Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader()
            .getResources(packageToScan.replace('.', '/'));
    while (dirs.hasMoreElements()) {

        URL url = dirs.nextElement();

        // ?@Entity
        if ("file".endsWith(url.getProtocol())) {
            String filePath = URLDecoder.decode(url.getFile(), "utf-8");
            fetchEntities(packageToScan, filePath, entities);
        }
    }

    return entities;
}