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:jcurl.core.io.SetupSaxDeSer.java

public static SetupBuilder parse(final URL file) throws SAXException, IOException {
    if (file.getFile().endsWith("z"))
        return parse(new GZIPInputStream(file.openStream()));
    return parse(file.openStream());
}

From source file:com.vangent.hieos.services.xds.bridge.utils.JUnitHelper.java

/**
 * Method description/* w ww .j av  a  2s .  co m*/
 *
 *
 * @param file
 *
 * @return
 *
 * @throws Exception
 */
public static OMElement fileToOMElement(String file) throws Exception {

    ClassLoader cl = JUnitHelper.class.getClassLoader();
    URL testfile = cl.getResource(file);

    assertNotNull(String.format("[%s] does not exist.", file), testfile);

    OMElement request = XMLParser.fileToOM(new File(testfile.getFile()));

    assertNotNull(request);

    logger.debug(DebugUtils.toPrettyString(request));

    return request;
}

From source file:elaborate.util.StringUtil.java

/**
 * change ULRs in <code>textWithURLs</code> to links
 * // ww  w .  ja va2 s .c  o m
 * @param textWithURLs
 *          text with URLs
 * @return text with links
 */
public static String activateURLs(String textWithURLs) {
    StringTokenizer tokenizer = new StringTokenizer(textWithURLs, "<> ", true);
    StringBuilder replaced = new StringBuilder(textWithURLs.length());
    while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken();
        // Log.info("token={}", token);
        try {
            URL url = new URL(token);
            // If possible then replace with anchor...
            String linktext = token;
            String file = url.getFile();
            if (StringUtils.isNotBlank(file)) {
                linktext = file;
            }
            String protocol = url.getProtocol();
            if (hostProtocols.contains(protocol)) {
                linktext = url.getHost() + linktext;
            }
            replaced.append("<a target=\"_blank\" href=\"" + url + "\">" + linktext + "</a>");
        } catch (MalformedURLException e) {
            replaced.append(token);
        }
    }

    return replaced.toString();
}

From source file:com.surenpi.autotest.suite.SuiteRunnerLauncher.java

/**
* @param urlList/*from   w  ww .  j a  v a 2 s . co  m*/
* @throws IOException 
* @throws UnsupportedEncodingException 
*/
private static void runnerRead(List<URL> urlList) throws UnsupportedEncodingException, IOException {
    InputStream inputA = SuiteRunnerLauncher.class.getResourceAsStream("/");
    if (inputA == null) {
        return;
    }

    BufferedReader reader = new BufferedReader(new InputStreamReader(inputA));
    String line = null;
    while ((line = reader.readLine()) != null) {
        URL itemUrl = SuiteRunnerLauncher.class.getResource("/" + line);
        if (itemUrl == null) {
            continue;
        }
        String path = URLDecoder.decode(itemUrl.getFile(), "utf-8");
        if (!path.endsWith(".xml")) {
            continue;
        }

        try (InputStream input = itemUrl.openStream()) {
            byte[] content = IOUtils.toByteArray(input);
            if (SuiteUtils.isSuiteXml(content)) {
                urlList.add(itemUrl);
            }
        }
    }
}

From source file:com.rapid7.diskstorage.dynamodb.TestGraphUtil.java

public static Configuration loadProperties() {
    ClassLoader classLoader = Client.class.getClassLoader();
    URL resource = classLoader.getResource("META-INF/dynamodb_store_manager_test.properties");
    PropertiesConfiguration storageConfig;
    try {/*  ww w  . j a  v  a  2  s .c o m*/
        storageConfig = new PropertiesConfiguration(resource.getFile());
    } catch (ConfigurationException e) {
        throw new RuntimeException(e);
    }
    return storageConfig;
}

From source file:io.dstream.tez.utils.HadoopUtils.java

/**
 * Will provision current classpath to YARN and return an array of
 * {@link Path}s representing provisioned resources
 * If 'generate-jar' system property is set it will also generate the JAR for the current
 * working directory (mainly used when executing from IDE)
 *//* w ww .  j av a 2  s.c  o m*/
private static Path[] provisionClassPath(FileSystem fs, String applicationName, String[] classPathExclusions) {
    String genJarProperty = System.getProperty(TezConstants.GENERATE_JAR);
    boolean generateJar = genJarProperty != null && Boolean.parseBoolean(genJarProperty);
    List<Path> provisionedPaths = new ArrayList<Path>();
    List<File> generatedJars = new ArrayList<File>();

    boolean confFromHadoopConfDir = generateConfigJarFromHadoopConfDir(fs, applicationName, provisionedPaths,
            generatedJars);

    TezConfiguration tezConf = new TezConfiguration(fs.getConf());
    boolean provisionTez = true;
    if (tezConf.get("tez.lib.uris") != null) {
        provisionTez = false;
    }
    URL[] classpath = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs();
    for (URL classpathUrl : classpath) {
        File f = new File(classpathUrl.getFile());
        if (f.isDirectory()) {
            if (generateJar) {
                String jarFileName = ClassPathUtils.generateJarFileName("application");
                f = doGenerateJar(f, jarFileName, generatedJars, "application");
            } else if (f.getName().equals("conf") && !confFromHadoopConfDir) {
                String jarFileName = ClassPathUtils.generateJarFileName("conf_application");
                f = doGenerateJar(f, jarFileName, generatedJars, "configuration");
            } else {
                f = null;
            }
        }
        if (f != null) {
            if (f.getName().startsWith("tez-") && !provisionTez) {
                logger.info("Skipping provisioning of " + f.getName()
                        + " since Tez libraries are already provisioned");
                continue;
            }
            String destinationFilePath = applicationName + "/" + f.getName();
            Path provisionedPath = new Path(fs.getHomeDirectory(), destinationFilePath);
            if (shouldProvision(provisionedPath.getName(), classPathExclusions)) {
                try {
                    provisioinResourceToFs(fs, new Path(f.getAbsolutePath()), provisionedPath);
                    provisionedPaths.add(provisionedPath);
                } catch (Exception e) {
                    logger.warn("Failed to provision " + provisionedPath + "; " + e.getMessage());
                    if (logger.isDebugEnabled()) {
                        logger.trace("Failed to provision " + provisionedPath, e);
                    }
                }
            }
        }

    }

    for (File generatedJar : generatedJars) {
        try {
            generatedJar.delete();
        } catch (Exception e) {
            logger.warn("Failed to delete generated jars", e);
        }
    }
    return provisionedPaths.toArray(new Path[] {});
}

From source file:org.shept.util.JarUtils.java

/**
 * Copy resources from a classPath, typically within a jar file 
 * to a specified destination, typically a resource directory in
 * the projects webApp directory (images, sounds, e.t.c. )
 * //  w ww .  j a v  a  2  s. co  m
 * Copies resources only if the destination file does not exist and
 * the specified resource is available.
 * 
 * The ClassPathResource will be scanned for all resources in the path specified by the resource.
 * For example  a path like:
 *    new ClassPathResource("resource/images/pager/", SheptBaseController.class);
 * takes all the resources in the path 'resource/images/pager' (but not in sub-path)
 * from the specified clazz 'SheptBaseController'
 * 
 * @param cpr ClassPathResource specifying the source location on the classPath (maybe within a jar)
 * @param webAppDestPath Full path String to the fileSystem destination directory   
 * @throws IOException when copying on copy error
 * @throws URISyntaxException 
 */
public static void copyResources(ClassPathResource cpr, String webAppDestPath)
        throws IOException, URISyntaxException {
    String dstPath = webAppDestPath; //  + "/" + jarPathInternal(cpr.getURL());
    File dir = new File(dstPath);
    dir.mkdirs();

    URL url = cpr.getURL();
    // jarUrl is the URL of the containing lib, e.g. shept.org in this case
    URL jarUrl = ResourceUtils.extractJarFileURL(url);
    String urlFile = url.getFile();
    String resPath = "";
    int separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
    if (separatorIndex != -1) {
        // just copy the the location path inside the jar without leading separators !/
        resPath = urlFile.substring(separatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length());
    } else {
        return; // no resource within jar to copy
    }

    File f = new File(ResourceUtils.toURI(jarUrl));
    JarFile jf = new JarFile(f);

    Enumeration<JarEntry> entries = jf.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String path = entry.getName();
        if (path.startsWith(resPath) && entry.getSize() > 0) {
            String fileName = path.substring(path.lastIndexOf("/"));
            File dstFile = new File(dstPath, fileName); //  (StringUtils.applyRelativePath(dstPath, fileName));
            Resource fileRes = cpr.createRelative(fileName);
            if (!dstFile.exists() && fileRes.exists()) {
                FileOutputStream fos = new FileOutputStream(dstFile);
                FileCopyUtils.copy(fileRes.getInputStream(), fos);
                logger.info("Successfully copied file " + fileName + " from " + cpr.getPath() + " to "
                        + dstFile.getPath());
            }
        }
    }

    if (jf != null) {
        jf.close();
    }

}

From source file:org.jboss.as.test.integration.security.loginmodules.common.Utils.java

public static void setPropertiesFile(Map<String, String> props, URL propFile) {
    File userPropsFile = new File(propFile.getFile());
    try {/* w  w  w .ja  v  a  2  s  . c  o m*/
        Writer writer = new FileWriter(userPropsFile);
        for (Map.Entry<String, String> entry : props.entrySet()) {
            writer.write(entry.getKey() + "=" + entry.getValue() + "\n");
        }
        writer.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:com.sldeditor.ui.detail.config.symboltype.externalgraphic.RelativePath.java

/**
 * Convert URL to absolute/relative path.
 *
 * @param externalFileURL the external file URL
 * @param useRelativePaths the use relative paths
 * @return the string//  w w  w. j a  va 2s  . com
 */
public static String convert(URL externalFileURL, boolean useRelativePaths) {
    String path = "";
    if (externalFileURL != null) {
        if (isLocalFile(externalFileURL)) {
            if (useRelativePaths) {
                File f = new File(externalFileURL.getFile());
                File folder = null;
                SLDDataInterface sldData = SLDEditorFile.getInstance().getSLDData();
                if ((sldData != null) && (sldData.getSLDFile() != null)) {
                    folder = sldData.getSLDFile().getParentFile();
                }

                if (folder == null) {
                    folder = new File(System.getProperty("user.dir"));
                }
                path = getRelativePath(f, folder);
            } else {
                path = externalFileURL.toExternalForm();
            }
        } else {
            path = externalFileURL.toExternalForm();
        }
    }
    return path;
}

From source file:net.ontopia.utils.TestFileUtils.java

public static List<Object[]> getTestInputURLs(ResourcesFilterIF filter, String... pathParts) {
    String path = testdataInputRoot;
    for (String part : pathParts) {
        path += part + File.separator;
    }/* ww  w .  j a  v a  2  s  .c o  m*/
    ResourcesDirectoryReader directoryReader = (filter == null ? new ResourcesDirectoryReader(path)
            : new ResourcesDirectoryReader(path, filter));
    Collection<Object[]> collected = org.apache.commons.collections4.CollectionUtils
            .collect(directoryReader.getResources(), new Transformer<URL, Object[]>() {
                @Override
                public Object[] transform(URL input) {
                    Object[] o = new Object[2];
                    o[0] = input;
                    o[1] = input.getFile().substring(input.getFile().lastIndexOf("/") + 1);
                    return o;
                }
            });
    return new ArrayList<>(collected);
}