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:com.vmware.qe.framework.datadriven.utils.XMLUtil.java

/**
 * Creates the parser instance based on dom parser factory Validates the xml file against the
 * XSD schema Return the documentElement of the xml document if validations succeeded
 * /* w w  w.  j  a  v  a 2  s.  c o  m*/
 * @param xmlFile - XML file to be parsed
 * @param xmlSchema - XSD that XML file should be validated against
 * @return documentElement of the XML file
 */
public static Document getXmlDocumentElement(String xmlFile, String xmlSchema) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setCoalescing(true);
    factory.setNamespaceAware(false);
    factory.setIgnoringElementContentWhitespace(true);
    factory.setValidating(true);
    factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource",
            XMLUtil.class.getResource(xmlSchema).getFile());
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setErrorHandler(new org.xml.sax.helpers.DefaultHandler());
    // Parse the document from the classpath.
    URL xmlFileUri = XMLUtil.class.getResource(xmlFile);
    if (null == xmlFileUri) {
        log.error("Unable to find file on classpath: " + xmlFile);
        return null;
    }
    return builder.parse(xmlFileUri.getFile());
}

From source file:de.alpharogroup.lang.PropertiesUtils.java

/**
 * Load the properties file from the given class object. The filename from the properties file
 * is the same as the simple name from the class object and it looks at the same path as the
 * given class object. If locale is not null than the language will be added to the filename
 * from the properties file.//from   w ww. ja  va2s  .  c  o m
 * 
 * @param clazz
 *            the clazz
 * @param locale
 *            the locale
 * @return the properties
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Properties loadPropertiesFromClassObject(final Class<?> clazz, final Locale locale)
        throws IOException {
    if (null == clazz) {
        throw new IllegalArgumentException("Class object must not be null!!!");
    }
    StringBuilder propertiesName = new StringBuilder();
    Properties properties = null;
    String language = null;
    String filename = null;
    String pathAndFilename = null;
    File propertiesFile = null;
    String absoluteFilename = null;
    final String packagePath = PackageUtils.getPackagePathWithSlash(clazz);
    final List<String> missedFiles = new ArrayList<>();
    if (null != locale) {
        propertiesName.append(clazz.getSimpleName());
        language = locale.getLanguage();
        if (null != language && !language.isEmpty()) {
            propertiesName.append("_").append(language);
        }

        final String country = locale.getCountry();
        if (null != country && !country.isEmpty()) {
            propertiesName.append("_").append(country);
        }
        propertiesName.append(FileExtension.PROPERTIES.getExtension());
        filename = propertiesName.toString().trim();
        pathAndFilename = packagePath + filename;
        URL url = ClassExtensions.getResource(clazz, filename);

        if (url != null) {
            absoluteFilename = url.getFile();
        } else {
            missedFiles.add("File with filename '" + filename + "' does not exists.");
        }

        if (null != absoluteFilename) {
            propertiesFile = new File(absoluteFilename);
        }

        if (null != propertiesFile && propertiesFile.exists()) {
            properties = PropertiesUtils.loadProperties(pathAndFilename);
        } else {
            propertiesName = new StringBuilder();
            if (null != locale) {
                propertiesName.append(clazz.getSimpleName());
                language = locale.getLanguage();
                if (null != language && !language.isEmpty()) {
                    propertiesName.append("_").append(language);
                }
                propertiesName.append(FileExtension.PROPERTIES.getExtension());
                filename = propertiesName.toString().trim();
                pathAndFilename = packagePath + filename;
                url = ClassExtensions.getResource(clazz, filename);

                if (url != null) {
                    absoluteFilename = url.getFile();
                } else {
                    missedFiles.add("File with filename '" + filename + "' does not exists.");
                }
                if (null != absoluteFilename) {
                    propertiesFile = new File(absoluteFilename);
                }
                if (null != propertiesFile && propertiesFile.exists()) {
                    properties = PropertiesUtils.loadProperties(pathAndFilename);
                }
            }
        }
    }

    if (null == properties) {
        propertiesName = new StringBuilder();
        propertiesName.append(clazz.getSimpleName()).append(FileExtension.PROPERTIES.getExtension());
        filename = propertiesName.toString().trim();
        pathAndFilename = packagePath + filename;
        final URL url = ClassExtensions.getResource(clazz, filename);

        if (url != null) {
            absoluteFilename = url.getFile();
        } else {
            properties = PropertiesUtils.loadProperties(pathAndFilename);
            missedFiles.add("File with filename '" + filename + "' does not exists.");
        }

        if (null != absoluteFilename) {
            propertiesFile = new File(absoluteFilename);
        }
        if (null != propertiesFile && propertiesFile.exists()) {
            properties = PropertiesUtils.loadProperties(pathAndFilename);
        }
    }
    if (properties == null) {
        for (final String string : missedFiles) {
            LOGGER.info(string);
        }
    }

    return properties;
}

From source file:com.depas.utils.FileUtils.java

public static File getResourceFile(String resourceName) {
    if (StringUtils.hasText(resourceName)) {
        URL url = getURLFromClasspath(resourceName);
        if (url != null) {
            String filePath = url.getFile();
            try {
                filePath = URLDecoder.decode(filePath, "UTF-8");
            } catch (Exception ex) {
                // Ignore
            }//from  w  ww  .j  a  v  a2s  . c  o  m
            return new File(filePath);
        }
    }
    return null;
}

From source file:de.alpharogroup.lang.ClassExtensions.java

/**
 * Gets the directories from the given path.
 *
 * @param path//from ww w  .  j a  va 2  s  . c  o  m
 *            the path
 * @param isPackage
 *            If the Flag is true than the given path is a package.
 * @return the directories from resources
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static List<File> getDirectoriesFromResources(String path, final boolean isPackage) throws IOException {
    if (isPackage) {
        path = path.replace('.', '/');
    }
    final List<URL> resources = ClassExtensions.getResources(path);
    final List<File> dirs = new ArrayList<>();
    for (final URL resource : resources) {
        dirs.add(new File(URLDecoder.decode(resource.getFile(), "UTF-8")));
    }
    return dirs;
}

From source file:cc.pp.analyzer.paoding.knife.PaodingMaker.java

private static File getFile(String path) {
    File file;//from   w w  w .  j  a v  a 2 s .  c o  m
    URL url;
    if (path.startsWith("classpath:")) {
        path = path.substring("classpath:".length());
        url = getClassLoader().getResource(path);
        final boolean fileExist = url != null;
        file = new File(fileExist ? url.getFile() : path) {
            private static final long serialVersionUID = 4009013298629147887L;

            @Override
            public boolean exists() {
                return fileExist;
            }
        };
    } else {
        file = new File(path);
    }
    return file;
}

From source file:kr.ac.kaist.wala.hybridroid.callgraph.AndroidHybridAnalysisScope.java

private static AndroidHybridAnalysisScope setUpJsAnalysisScope(String dir, AndroidHybridAnalysisScope scope,
        Set<URL> htmls) throws IllegalArgumentException, IOException {

    JavaScriptLoader.addBootstrapFile(WebUtil.preamble);
    if (SystemUtils.IS_OS_WINDOWS) {
        scope.addToScope(scope.getJavaScriptLoader(),
                new SourceURLModule(AndroidHybridAppModel.class.getResource("prologue.js")) {
                    @Override/* w w  w.  j  a  v a2 s  .c o m*/
                    public String getName() {
                        return "prologue.js";
                    }
                });
        scope.addToScope(scope.getJavaScriptLoader(),
                new SourceURLModule(AndroidHybridAppModel.class.getResource("preamble.js")) {
                    @Override
                    public String getName() {
                        return "preamble.js";
                    }
                });
    } else {
        scope.addToScope(scope.getJavaScriptLoader(),
                new SourceURLModule(AndroidHybridAppModel.class.getResource("prologue.js")) {
                    @Override
                    public String getName() {
                        return "prologue.js";
                    }
                });
        scope.addToScope(scope.getJavaScriptLoader(),
                new SourceURLModule(AndroidHybridAppModel.class.getResource("preamble.js")) {
                    @Override
                    public String getName() {
                        return "preamble.js";
                    }
                });
        //scope.addToScope(scope.getJavaScriptLoader(), JSCallGraphBuilderUtil.getPrologueFile("prologue.js"));
        //scope.addToScope(scope.getJavaScriptLoader(), JSCallGraphBuilderUtil.getPrologueFile("preamble.js"));
    }
    for (URL url : htmls) {
        try {
            File f = WebUtil.extractScriptFromHTML(url, DefaultSourceExtractor.factory).snd;
            scope.addToScope(scope.getJavaScriptLoader(), new SourceURLModule(f.toURI().toURL()));

            String jspath = f.getCanonicalPath();
            addScopeMap(Atom.findOrCreateAsciiAtom(url.toString()), Atom.findOrCreateAsciiAtom(
                    jspath.substring(jspath.lastIndexOf(File.separator) + 1, jspath.length())));
            if (DEBUG)
                System.err.println("#Loaded html: " + url.getFile());
        } catch (Error | RuntimeException e) {// | UnimplementedError |
            // Error e) {
            if (url.toString().startsWith("http")) {
                System.err.println("Cannot receive the response from the url: " + url);
            } else {
                String path = url.getPath();
                SourceModule dummy = new SourceURLModule(FileWriter
                        .makeHtmlFile(dir,
                                path.substring(path.lastIndexOf(File.separator) + 1, path.length() - 1), "")
                        .toURI().toURL());
                String dummypath = dummy.getName();
                if (DEBUG)
                    System.err.println("make dummy: " + dummypath);
                addScopeMap(Atom.findOrCreateAsciiAtom(url.toString()), Atom
                        .findOrCreateAsciiAtom(dummypath.substring(dummypath.lastIndexOf(File.separator) + 1)));
                scope.addToScope(scope.getJavaScriptLoader(), dummy);
            }
        }
    }

    return scope;
}

From source file:com.vmware.bdd.utils.CommonUtil.java

public static String readJsonFile(URL fileURL) {
    StringBuilder jsonBuff = new StringBuilder();
    if (fileURL != null) {
        String fileName = fileURL.getFile();
        InputStream in = null;/*from ww  w  .  j av  a 2 s.  co m*/
        try {
            in = new BufferedInputStream(fileURL.openStream());
            Reader rd = new InputStreamReader(in, "UTF-8");
            int c = 0;
            while ((c = rd.read()) != -1) {
                jsonBuff.append((char) c);
            }
        } catch (IOException e) {
            logger.error(e.getMessage() + "\n Can not find " + fileName + " or IO read error.");
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage() + "\n Can not close " + fileName + ".");
            }
        }
    }
    return jsonBuff.toString();
}

From source file:gate.DocumentFormat.java

/**
  * Return the fileSuffix or null if the url doesn't have a file suffix
  * If the url is null then the file suffix will be null also
  *///w  w  w . ja va  2 s. co m
@SuppressWarnings("unused")
private static String getFileSuffix(URL url) {
    String fileName = null;
    String fileSuffix = null;

    // GIGO test  (garbage in garbage out)
    if (url != null) {
        // get the file name from the URL
        fileName = url.getFile();

        // tokenize this file name with "." as separator...
        // the last token will be the file suffix
        StringTokenizer st = new StringTokenizer(fileName, ".");

        // fileSuffix is the last token
        while (st.hasMoreTokens())
            fileSuffix = st.nextToken();
        // here fileSuffix is the last token
    } // End if
    return fileSuffix;
}

From source file:com.asual.lesscss.ResourceUtils.java

public static byte[] readBinaryUrl(URL source) throws IOException {
    byte[] result;
    try {/* w  ww  .ja v  a  2  s  .co m*/
        URLConnection urlc = source.openConnection();
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        InputStream input = urlc.getInputStream();
        try {
            byte[] buffer = new byte[1024];
            int bytesRead = -1;
            while ((bytesRead = input.read(buffer)) != -1) {
                byteStream.write(buffer, 0, bytesRead);
            }
            result = byteStream.toByteArray();
        } finally {
            byteStream.close();
            input.close();
        }
    } catch (IOException e) {
        logger.error("Can't read '" + source.getFile() + "'.");
        throw e;
    }
    return result;
}

From source file:net.paoding.analysis.knife.PaodingMaker.java

private static String getUrlPath(URL url) {
    if (url == null)
        return null;
    String urlPath = null;//from ww w . j  a v  a  2s.  co m
    try {
        urlPath = url.toURI().getPath();
    } catch (URISyntaxException e) {
    }
    if (urlPath == null) {
        urlPath = url.getFile();
    }
    return urlPath;
}