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:co.cask.common.security.server.ExternalAuthenticationServerSSLTest.java

@BeforeClass
public static void beforeClass() throws Exception {
    URL certUrl = ExternalAuthenticationServerSSLTest.class.getClassLoader().getResource("cert.jks");
    Assert.assertNotNull(certUrl);/*from  www  .j a v a  2  s  .co  m*/

    String authHandlerConfigBase = Constants.AUTH_HANDLER_CONFIG_BASE;

    SecurityConfiguration cConf = SecurityConfiguration.create();
    cConf.set(Constants.SSL_ENABLED, "true");
    cConf.set(authHandlerConfigBase.concat("useLdaps"), "true");
    cConf.set(authHandlerConfigBase.concat("ldapsVerifyCertificate"), "false");
    cConf.set(Constants.AuthenticationServer.SSL_KEYSTORE_PATH, certUrl.getPath());
    configuration = cConf;

    String keystorePassword = cConf.get(Constants.AuthenticationServer.SSL_KEYSTORE_PASSWORD);
    KeyStoreKeyManager keyManager = new KeyStoreKeyManager(certUrl.getFile(), keystorePassword.toCharArray());
    SSLUtil sslUtil = new SSLUtil(keyManager, new TrustAllTrustManager());
    ldapListenerConfig = InMemoryListenerConfig.createLDAPSConfig("LDAP", InetAddress.getByName("127.0.0.1"),
            ldapPort, sslUtil.createSSLServerSocketFactory(), sslUtil.createSSLSocketFactory());

    setup();
}

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 DOM
 * to XML converter// w w w .  j ava  2 s. c  o  m
 *
 * @param pluggableDatasouce
 * @param datasource
 * @return
 */
static String prepareDatasourceResponse(HttpServletResponse response, Integer templateID,
        IPluggableDatasource pluggableDatasouce, Map<String, Object> description, Object datasource) {
    // otherwise prepare an XML result
    DownloadUtil.prepareResponse(ServletActionContext.getRequest(), response, "TrackReport.xml", "text/xml");
    try {
        final OutputStream outputStream = response.getOutputStream();
        final String xslt = (String) description.get("xslt");
        if ((datasource != null) && (xslt != null) && (templateID != null)) {
            final File template = ReportBL.getDirTemplate(templateID);
            URL baseURL = null;
            try {
                baseURL = template.toURL();
            } catch (final MalformedURLException e) {
                LOGGER.error("Wrong template URL for " + template.getName() + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
            if (baseURL != null) {
                final String absolutePathXslt = baseURL.getFile() + xslt;
                try {
                    datasource = XsltTransformer.getInstance().transform((Document) datasource,
                            absolutePathXslt);
                } catch (final Exception e) {
                    LOGGER.warn("Tranforming the datasource with " + absolutePathXslt + " failed with "
                            + e.getMessage());
                    LOGGER.debug(ExceptionUtils.getStackTrace(e));
                }
            }
        }
        if (pluggableDatasouce == null) {
            // the default datasource (ReportBeans from last executed query)
            // serialize the DOM object into an XML stream
            ReportBeansToXML.convertToXml(outputStream, (Document) datasource);
        } else {
            // datasource specific serialization
            pluggableDatasouce.serializeDatasource(outputStream, datasource);
        }
    } catch (final Exception e) {
        LOGGER.error("Serializing the datasource to output stream failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));

    }
    return null;
}

From source file:com.microsoftopentechnologies.windowsazurestorage.WAStorageClient.java

/**
 * Downloads from Azure blob//from w  ww.  j a v a 2s . c  o m
 *
 * @param run environment of build
 * @param launcher env vars for remote builds
 * @param listener logging
 * @param strAcc storage account
 * @param blobs blobs from build
 * @param includePattern pattern to download
 * @param excludePattern pattern to not download
 * @param downloadDirLoc dir to download to
 * @param flattenDirectories if directories are flattened
 * @param workspace workspace of build
 * @return filesDownloaded number of files that are downloaded
 * @throws WAStorageException throws exception
 */
public static int download(Run<?, ?> run, Launcher launcher, TaskListener listener, StorageAccountInfo strAcc,
        List<AzureBlob> blobs, String includePattern, String excludePattern, String downloadDirLoc,
        boolean flattenDirectories, FilePath workspace) throws WAStorageException {

    int filesDownloaded = 0;

    for (AzureBlob blob : blobs) {
        try {
            FilePath workspacePath = new FilePath(launcher.getChannel(), workspace.getRemote());

            FilePath downloadDir = getDownloadDir(workspacePath, downloadDirLoc);

            listener.getLogger().println(Messages.AzureStorageBuilder_downloading());

            URL blobURL = new URL(blob.getBlobURL());
            String filePath = blobURL.getFile();

            CloudBlobContainer container = WAStorageClient.getBlobContainerReference(strAcc,
                    filePath.split("/")[1], false, true, null);

            if (shouldDownload(includePattern, excludePattern, blob.getBlobName())) {
                filesDownloaded += downloadBlobs(container, blob, downloadDir, flattenDirectories, listener);
            }

        } catch (Exception e) {
            throw new WAStorageException(e.getMessage(), e.getCause());
        }
    }
    return filesDownloaded;
}

From source file:JarMaker.java

public static void RealPackUtilityJar(String s_src, String s_dest) throws IOException {

    URL _src, _dest;

    File f_src = new File(s_src);
    if (!f_src.isDirectory())
        throw new IOException(s_src + " is not a directory");
    _src = f_src.toURL();/* www.j a v  a  2 s  . c o m*/
    _dest = new File(s_dest).toURL();

    int path_l = s_dest.lastIndexOf("/");
    if (path_l > 0) {
        File dir = new File(s_dest.substring(0, path_l));
        if (!dir.exists())
            dir.mkdirs();
    }

    JarOutputStream jout = new JarOutputStream(new FileOutputStream(_dest.getFile()));
    // put all into the jar...
    add(jout, new File(_src.getFile()), "");
    jout.close();
}

From source file:br.bireme.tb.URLS.java

/**
 * Loads all cvs links from a root html page if possible otherwise find then
 * recursively. Then the csv s will be loaded and the table cells will be
 * saved at files./*from  ww  w. j  a v a  2 s  .c om*/
 * @param html
 * @param postParam
 * @param tableOptions
 * @param tableNum
 * @param level
 * @param setUrls
 * @param history
 * @param root
 * @return array of int { number of the last table generated, number of csv files read }
 * @throws IOException 
 */
private static int[] loadCsvFromHtml(final URL html, final String postParam,
        final Map<String, String> tableOptions, final int tableNum, final int level, final Set<String> setUrls,
        final Set<URL> history, final File root) throws IOException {
    assert html != null;
    assert tableNum >= 0;
    assert level >= 0;
    assert setUrls != null;
    assert history != null;
    assert root != null;

    int[] ret = new int[] { tableNum, 0 };

    if ((postParam != null) || (!history.contains(html))) {
        if (level <= MAX_LEVEL) {
            history.add(html);

            final String[] page;
            try {
                page = (postParam == null) ? loadPageGet(html) : loadPagePost(html, postParam);
            } catch (IOException ioe) {
                Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE,
                        "error loading file: [" + html + "] params: [" + postParam + "]", ioe);
                return ret;
            }
            final String content = page[1];
            final Matcher mat = CSV_PATTERN.matcher(content);

            if (mat.find()) { // Found a cvs link in that page  
                final Matcher mat2 = QUALIF_REC_PATTERN.matcher(content);
                if (mat2.find()) {
                    final UrlElem elem = new UrlElem();
                    elem.father = html;
                    elem.fatherParams = postParam;
                    elem.tableOptions = tableOptions;
                    elem.csv = withDomain(html, mat.group(1));
                    elem.qualifRec = withDomain(html, mat2.group(1));
                    try {
                        final String[] csvpage = loadPageGet(elem.csv);
                        final CSV_File csv = new CSV_File();
                        final Table table = csv.parse(csvpage[1], CSV_SEPARATOR);

                        genCellsFromTable(table, elem, root, setUrls, ++ret[0]);
                        ret[1] = 1;
                    } catch (Exception ex) {
                        Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE,
                                "skipping file: " + elem.csv, ex);
                    }
                }
            } else { // Did not find a cvs link in that page
                if (postParam != null) {
                    Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE,
                            " skipping loadCsvFromHtml/Def file: " + html + " params:" + postParam
                                    + "\nCSV link not found into def page [" + findErrorMessage(content) + "]");
                }
                final Set<URL> urls = getPageDefHtmlUrls(new URL(page[0]), content, history);
                for (URL url : urls) {
                    try {
                        final String file = url.getFile();
                        final int[] aux;
                        if (file.endsWith(".def")) {
                            aux = loadCsvFromDef(url, ret[0], setUrls, history, root);
                        } else {
                            aux = loadCsvFromHtml(url, null, null, ret[0], level + 1, setUrls, history, root);
                        }
                        ret[0] = aux[0];
                        ret[1] += aux[1];
                    } catch (IOException ioe) {
                        Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE,
                                "skipping loadCsvFromHtml/Def file: " + url, ioe);
                        //throw ioe;
                    }
                }
            }
        }
    }

    return ret;
}

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

public static byte[] readTextUrl(URL source, String encoding) throws IOException {
    byte[] result;
    try {/*from   w  w  w  .ja  v  a2  s .c o m*/
        URLConnection urlc = source.openConnection();
        StringBuffer sb = new StringBuffer(1024);
        InputStream input = urlc.getInputStream();
        UnicodeReader reader = new UnicodeReader(input, encoding);
        try {
            char[] cbuf = new char[32];
            int r;
            while ((r = reader.read(cbuf, 0, 32)) != -1) {
                sb.append(cbuf, 0, r);
            }
            result = sb.toString().getBytes(reader.getEncoding());
        } finally {
            reader.close();
            input.close();
        }
    } catch (IOException e) {
        logger.error("Can't read '" + source.getFile() + "'.");
        throw e;
    }
    return result;
}

From source file:net.librec.util.FileUtil.java

/**
 * Get resource path, supporting file and url io path
 *
 * @param filePath  file path//from ww w  .  j  av  a 2s . c om
 * @return path to the file
 */
public static String getResource(String filePath) {
    if (FileUtil.exist(filePath))
        return filePath;

    String path = makeDirPath(new String[] { "src", "main", "resources" }) + filePath;
    if (FileUtil.exist(path))
        return path;

    URL is = Class.class.getResource(filePath);
    if (is != null)
        return is.getFile();

    is = Class.class.getResource(path);
    if (is != null)
        return is.getFile();

    return null;
}

From source file:edu.du.penrose.systems.fedoraApp.util.FedoraAppUtil.java

/**
 * Returns strings of the type 'institution'_'batchSet' ie 'codu_ectd' to show the institution and batch set for batch sets 
 * that have been configured for background tasks ingest's, with a institution_batchSet_TASK.properties file, they may or not be 
 * enabled in the taskEnable.properties file.
 * // ww  w. j  a  v  a2 s . c o m
 * @return string of type 'codu_ectd'
 * @throws Exception
 */
public static Set<String> getTaskConfiguredInstitutions() throws Exception {
    Set<String> taskEnabledInstutions = new HashSet<String>();

    File institutionDirectory = null;
    String institutionDirectoryPath = ProgramProperties
            .getInstance(FedoraAppConstants.getServletContextListener().getProgramPropertiesURL())
            .getProperty(FedoraAppConstants.BATCH_INGEST_TOP_FOLDER_URL_PROPERTY);
    URL institutionURL = new URL(institutionDirectoryPath);
    if (institutionURL.getProtocol().toLowerCase().equals("file")) { // TBD only file protocol currently supported.

        institutionDirectory = new File(institutionURL.getFile());
    } else {
        throw new FatalException("Unsupported Protocol for top batch ingest folder (institution directory");
    }

    File[] dirNames = institutionDirectory.listFiles();
    for (int i = 0; i < dirNames.length; i++) {
        if (dirNames[i].isDirectory()) {
            File dirTemp = dirNames[i];
            File[] batchSetList = dirTemp.listFiles();
            for (int j = 0; j < batchSetList.length; j++) {
                if (batchSetList[j].isDirectory()) {
                    File configFile = new File(batchSetList[j] + "/" + batchSetList[j].getName()
                            + FedoraAppConstants.BACKGROUND_TASK_NAME_SUFFIX + ".properties");
                    if (configFile.exists()) {
                        // this will create a worker name of type 'codu_ectd_REMOTE'
                        String workerName = dirNames[i].getName() + "_" + batchSetList[j].getName()
                                + FedoraAppConstants.BACKGROUND_TASK_NAME_SUFFIX;
                        taskEnabledInstutions.add(workerName);
                    }
                }
            }
        }
    }

    return taskEnabledInstutions;
}

From source file:com.sun.tools.xjc.addon.xew.XmlElementWrapperPluginTest.java

/**
 * Standard test for XSD examples./*from www.j a  v a 2 s  .  c o  m*/
 * 
 * @param testName
 *            the prototype of XSD file name / package name
 * @param extraXewOptions
 *            to be passed to plugin
 * @param generateEpisode
 *            generate episode file and check the list of classes included into it
 * @param classesToCheck
 *            expected classes/files in target directory; these files content is checked if it is present in
 *            resources directory; {@code ObjectFactory.java} is automatically included
 */
static void assertXsd(String testName, String[] extraXewOptions, boolean generateEpisode,
        String... classesToCheck) throws Exception {
    String resourceXsd = testName + ".xsd";
    String packageName = testName.replace('-', '_');

    // Force plugin to reinitialize the logger:
    System.clearProperty(XmlElementWrapperPlugin.COMMONS_LOGGING_LOG_LEVEL_PROPERTY_KEY);

    URL xsdUrl = XmlElementWrapperPluginTest.class.getResource(resourceXsd);

    File targetDir = new File(GENERATED_SOURCES_PREFIX);

    targetDir.mkdirs();

    PrintStream loggingPrintStream = new PrintStream(
            new LoggingOutputStream(logger, LoggingOutputStream.LogLevel.INFO, "[XJC] "));

    String[] opts = ArrayUtils.addAll(extraXewOptions, "-no-header", "-extension", "-Xxew", "-d",
            targetDir.getPath(), xsdUrl.getFile());

    String episodeFile = new File(targetDir, "episode.xml").getPath();

    // Episode plugin should be triggered after Xew, see https://github.com/dmak/jaxb-xew-plugin/issues/6
    if (generateEpisode) {
        opts = ArrayUtils.addAll(opts, "-episode", episodeFile);
    }

    assertTrue("XJC compilation failed. Checked console for more info.",
            Driver.run(opts, loggingPrintStream, loggingPrintStream) == 0);

    if (generateEpisode) {
        // FIXME: Episode file actually contains only value objects
        Set<String> classReferences = getClassReferencesFromEpisodeFile(episodeFile);

        if (Arrays.asList(classesToCheck).contains("package-info")) {
            classReferences.add(packageName + ".package-info");
        }

        assertEquals("Wrong number of classes in episode file", classesToCheck.length, classReferences.size());

        for (String className : classesToCheck) {
            assertTrue(className + " class is missing in episode file;",
                    classReferences.contains(packageName + "." + className));
        }
    }

    targetDir = new File(targetDir, packageName);

    Collection<String> generatedJavaSources = new HashSet<String>();

    // *.properties files are ignored:
    for (File targetFile : FileUtils.listFiles(targetDir, new String[] { "java" }, true)) {
        // This is effectively the path of targetFile relative to targetDir:
        generatedJavaSources
                .add(targetFile.getPath().substring(targetDir.getPath().length() + 1).replace('\\', '/'));
    }

    // This class is added and checked by default:
    classesToCheck = ArrayUtils.add(classesToCheck, "ObjectFactory");

    assertEquals("Wrong number of generated classes " + generatedJavaSources + ";", classesToCheck.length,
            generatedJavaSources.size());

    for (String className : classesToCheck) {
        className = className.replace('.', '/') + ".java";

        assertTrue(className + " is missing in target directory", generatedJavaSources.contains(className));
    }

    // Check the contents for those files which exist in resources:
    for (String className : classesToCheck) {
        className = className.replace('.', '/') + ".java";

        File sourceFile = new File(PREGENERATED_SOURCES_PREFIX + packageName, className);

        if (sourceFile.exists()) {
            // To avoid CR/LF conflicts:
            assertEquals("For " + className, FileUtils.readFileToString(sourceFile).replace("\r", ""),
                    FileUtils.readFileToString(new File(targetDir, className)).replace("\r", ""));
        }
    }

    JAXBContext jaxbContext = compileAndLoad(packageName, targetDir, generatedJavaSources);

    URL xmlTestFile = XmlElementWrapperPluginTest.class.getResource(testName + ".xml");

    if (xmlTestFile != null) {
        StringWriter writer = new StringWriter();

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(schemaFactory.newSchema(xsdUrl));

        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        Object bean = unmarshaller.unmarshal(xmlTestFile);
        marshaller.marshal(bean, writer);

        XMLUnit.setIgnoreComments(true);
        XMLUnit.setIgnoreWhitespace(true);
        Diff xmlDiff = new Diff(IOUtils.toString(xmlTestFile), writer.toString());

        assertXMLEqual("Generated XML is wrong: " + writer.toString(), xmlDiff, true);
    }
}

From source file:edu.du.penrose.systems.fedoraApp.util.FedoraAppUtil.java

/**
 * Returns strings of the type 'institution'_'batchSet' ie 'codu_ectd' to show the institution and batch set for batch sets 
 * that have been configured for remote ingest's, with a institution_batchSet_REMOTE.properties file, they may or not be 
 * enabled in the taskEnable.properties file.
 * /*from   ww  w . jav a 2 s.com*/
 * @return string of type 'codu_ectd'
 * @throws Exception
 */
public static Set<String> getRemoteConfiguredInstitutions() throws Exception {
    Set<String> remoteEnabledInstutions = new HashSet<String>();

    File institutionDirectory = null;
    String institutionDirectoryPath = ProgramProperties
            .getInstance(FedoraAppConstants.getServletContextListener().getProgramPropertiesURL())
            .getProperty(FedoraAppConstants.BATCH_INGEST_TOP_FOLDER_URL_PROPERTY);
    //   logger.info( "topInstitutionPath=" + institutionDirectoryPath );

    URL institutionURL = new URL(institutionDirectoryPath);
    if (institutionURL.getProtocol().toLowerCase().equals("file")) { // TBD only file protocol currently supported.

        institutionDirectory = new File(institutionURL.getFile());
    } else {
        throw new FatalException("Unsupported Protocol for top batch ingest folder (institution directory");
    }

    File[] dirNames = institutionDirectory.listFiles();
    for (int i = 0; i < dirNames.length; i++) {
        //   logger.info( "processFileOrDirectory=" + dirNames[i] );
        if (dirNames[i].isDirectory()) {
            //   logger.info( "processDirectory=" + dirNames[i] );
            File dirTemp = dirNames[i];
            File[] batchSetList = dirTemp.listFiles();
            if (batchSetList == null) {
                continue;
            }
            for (int j = 0; j < batchSetList.length; j++) {
                //   logger.info( "processFileOrDirectory=" + batchSetList[j] );
                if (batchSetList[j].isDirectory()) {
                    //      logger.info( "processDirectory=" + batchSetList[j] );
                    File configFile = new File(batchSetList[j] + "/" + batchSetList[j].getName()
                            + FedoraAppConstants.REMOTE_TASK_NAME_SUFFIX + ".properties");
                    if (configFile.exists()) {
                        //      logger.info( "Add worker for "+configFile.getName() );
                        // this will create a worker name of type 'codu_ectd_REMOTE'
                        String workerName = dirNames[i].getName() + "_" + batchSetList[j].getName()
                                + FedoraAppConstants.REMOTE_TASK_NAME_SUFFIX;
                        remoteEnabledInstutions.add(workerName);
                    }
                }
            }
        }
    }

    return remoteEnabledInstutions;
}