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.aurel.track.admin.customize.category.report.execute.DocxReportExporter.java

/**
 * Export the items in the given output/*  w ww  .j ava  2 s  .  c o m*/
 * 
 * @param document W3C XML DOM document
 * @param personBean current user
 * @param locale
 *            current locale
 * @param parameters
 *            the directory of the DOCX template enriched with special placeholders
 * @param os
 *            the output stream to write to
 * @param contextMap
 * @param description
 */
@Override
public void exportReport(Document document, TPersonBean personBean, Locale locale,
        Map<String, Object> parameters, OutputStream os, Map<String, Object> contextMap,
        Map<String, Object> description) throws ReportExportException {

    String format = (String) description.get(IDescriptionAttributes.FORMAT);

    if (format == null || !format.equals(FORMAT_DOCX)) {
        throw new ReportExportException(ERROR_UNKNOWN_FORMAT);
    }

    /* Caution! Because the me
     * based on the template file name, the template has to be uploaded in the wiki!
     */
    String docxTemplatePath = null;
    URL completeURL = (URL) parameters.get(JasperReportExporter.REPORT_PARAMETERS.COMPLETE_URL);
    if (completeURL != null) {
        docxTemplatePath = completeURL.getFile();
        WordprocessingMLPackage wpMLP = AssembleWordprocessingMLPackage.getWordMLPackage(
                MeetingDatasource.WORK_ITEM_BEAN, MeetingDatasource.REPORT_BEANS, docxTemplatePath,
                personBean.getObjectID(), locale);
        try {
            Docx4J.save(wpMLP, os, Docx4J.FLAG_NONE);
        } catch (Exception e) {
            LOGGER.error("Exporting the docx failed with throwable " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }

}

From source file:m.dekmak.License.java

public String validate() {
    String msg = "";
    URL location = License.class.getProtectionDomain().getCodeSource().getLocation();
    String url = location.getFile();
    String path = url.substring(0, url.length() - 38);
    String licensePath = path + "license";
    File f = new File(licensePath);
    if (f.exists() && !f.isDirectory()) {
        JSONParser parser = new JSONParser();
        try {//from   www .j  a va 2  s.  c  om
            Object obj = parser.parse(new FileReader(licensePath));
            JSONObject jsonObject = (JSONObject) obj;
            String client = (String) jsonObject.get("client");
            if (client == null || client.equals("")) {
                msg = "Invalid license (client not defined)";
            } else {
                String product = (String) jsonObject.get("product");
                if (product == null || product.equals("")) {
                    msg = "Invalid license (product not defined)";
                } else {
                    String nbOfUsers = (String) jsonObject.get("nbOfUsers");
                    if (nbOfUsers == null || nbOfUsers.equals("")) {
                        msg = "Invalid license (Nb Of Users not defined)";
                    } else {
                        String expiresOn = (String) jsonObject.get("expiresOn");
                        if (expiresOn == null || expiresOn.equals("")) {
                            msg = "Invalid license (Expires on date not defined)";
                        } else {
                            Encryptor encr = new Encryptor(client);
                            String license = (String) jsonObject.get("license");
                            if (license == null || license.equals("")) {
                                msg = "Invalid license (license not defined)";
                            } else {
                                product = encr.decrypt(product);
                                nbOfUsers = encr.decrypt(nbOfUsers);
                                expiresOn = encr.decrypt(expiresOn);
                                license = encr.decrypt(license);
                                if (license.equals(client)) {
                                    setExpiresOn(expiresOn);
                                    setNbOfUsers(nbOfUsers);
                                    setClient(client);
                                    setProduct(product);
                                    msg = "success";
                                } else {
                                    msg = "Invalid license";
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            msg = "Invalid license for given client";
        }
    } else {
        msg = "License file not exists";
    }

    return msg;
}

From source file:ch.astina.hesperid.web.services.dbmigration.impl.ClasspathMigrationResolver.java

public Set<Migration> resolve() {
    Set<Migration> migrations = new HashSet<Migration>();

    try {/*from   w w w .ja  v  a  2s  .  co m*/
        Enumeration<URL> enumeration = getClass().getClassLoader().getResources(classPath);

        while (enumeration.hasMoreElements()) {

            URL url = enumeration.nextElement();

            if (url.toExternalForm().startsWith("jar:")) {
                String file = url.getFile();

                file = file.substring(0, file.indexOf("!"));
                file = file.substring(file.indexOf(":") + 1);

                InputStream is = new FileInputStream(file);

                ZipInputStream zip = new ZipInputStream(is);

                ZipEntry ze;

                while ((ze = zip.getNextEntry()) != null) {
                    if (!ze.isDirectory() && ze.getName().startsWith(classPath)
                            && ze.getName().endsWith(".sql")) {

                        Resource r = new UrlResource(getClass().getClassLoader().getResource(ze.getName()));

                        String version = versionExtractor.extractVersion(r.getFilename());
                        migrations.add(migrationFactory.create(version, r));
                    }
                }
            } else {
                File file = new File(url.getFile());

                for (String s : file.list()) {
                    Resource r = new UrlResource(getClass().getClassLoader().getResource(classPath + "/" + s));

                    String version = versionExtractor.extractVersion(r.getFilename());
                    migrations.add(migrationFactory.create(version, r));
                }
            }
        }
    } catch (Exception e) {
        logger.error("Error while resolving migrations", e);
    }

    return migrations;
}

From source file:CWLClientTest.java

/**
 * This test demonstrates how to parse a CWL document using CWL tool.
 * @throws Exception/*from  w  w w  . j a  v a2s.c o  m*/
 */
@Test
public void parseCWL() throws Exception {
    final URL resource = Resources.getResource("cwl.json");
    final CWL cwl = new CWL();
    final ImmutablePair<String, String> output = cwl.parseCWL(resource.getFile());
    assertTrue(!output.getLeft().isEmpty() && output.getLeft().contains("cwlVersion"));
    assertTrue(!output.getRight().isEmpty() && output.getRight().contains("cwltool"));
}

From source file:com.linkedin.pinot.broker.routing.RandomRoutingTableTest.java

@Test
public void testHelixExternalViewBasedRoutingTable() throws Exception {
    URL resourceUrl = getClass().getClassLoader().getResource("SampleExternalView.json");
    Assert.assertNotNull(resourceUrl);//from  w  w w.j a  v  a2 s.c o  m
    String fileName = resourceUrl.getFile();

    byte[] externalViewBytes = IOUtils.toByteArray(new FileInputStream(fileName));
    ExternalView externalView = new ExternalView(
            (ZNRecord) new ZNRecordSerializer().deserialize(externalViewBytes));
    String tableName = externalView.getResourceName();
    List<InstanceConfig> instanceConfigs = getInstanceConfigs(externalView);
    int numSegmentsInEV = externalView.getPartitionSet().size();
    int numServersInEV = instanceConfigs.size();

    HelixExternalViewBasedRouting routing = new HelixExternalViewBasedRouting(null, null,
            new BaseConfiguration());
    routing.markDataResourceOnline(generateTableConfig(tableName), externalView, instanceConfigs);

    for (int i = 0; i < NUM_ROUNDS; i++) {
        Map<String, List<String>> routingTable = routing
                .getRoutingTable(new RoutingTableLookupRequest(tableName));
        Assert.assertEquals(routingTable.size(), numServersInEV);
        int numSegments = 0;
        for (List<String> segmentsForServer : routingTable.values()) {
            int numSegmentsForServer = segmentsForServer.size();
            Assert.assertTrue(numSegmentsForServer >= MIN_NUM_SEGMENTS_PER_SERVER
                    && numSegmentsForServer <= MAX_NUM_SEGMENTS_PER_SERVER);
            numSegments += numSegmentsForServer;
        }
        Assert.assertEquals(numSegments, numSegmentsInEV);
    }
}

From source file:com.logisima.selenium.netty.NettyServerTest.java

@Before
public void setUp() throws MojoExecutionException, MalformedURLException {
    // copy selenium application
    File seleniumTarget = new File(FileUtils.getTempDirectoryPath() + "/selenium");
    TestRunnerUtils.copySeleniumToDir(seleniumTarget);

    // get the "src/test" path of the project
    URL url2 = SeleniumParserTest.class.getResource("/selenium.test.html");
    File script = new File(url2.getFile());
    String projectTestPath = script.getParentFile().getParentFile().getParentFile().toString() + "/src/test";
    projectTestPathFile = new File(projectTestPath);
    URL url = new URL("http://localhost:7777");

    // starting server
    server = new NettyServer(7777, seleniumTarget.getPath(), url, projectTestPathFile.getAbsolutePath(),
            FileUtils.getTempDirectoryPath() + "/selenium", 5);
    server.start();//  w ww . j  av a2  s .c  o m
    try {
        server.join();
    } catch (InterruptedException e) {
    }

    // get firephoque
    firephoque = TestRunnerUtils.getWebClient();
    firephoque.setTimeout(1000);
}

From source file:CWLClientTest.java

/**
 * This test demonstrates how to extract information from a CWL file.
 * @throws Exception// ww  w  .  j  a v a  2  s. c o m
 */
@Test
public void extractCWLTypes() throws Exception {
    final URL resource = Resources.getResource("cwl.json");
    final CWL cwl = new CWL();
    final ImmutablePair<String, String> output = cwl.parseCWL(resource.getFile());
    final Map<String, String> typeMap = cwl.extractCWLTypes(output.getLeft());
    assertTrue(typeMap.size() == 3);
    assertTrue("int".equals(typeMap.get("mem_gb")));
    assertTrue("File".equals(typeMap.get("bam_input")));
}

From source file:atg.tools.dynunit.nucleus.NucleusUtils.java

/**
 * A crazily ugly and elaborate method where we try to discover
 * DYNAMO_ROOT by various means. This is mostly made complicated
 * by the ROAD DUST environment being so different from devtools.
 *//* www  .  j a  v  a 2 s .  co  m*/
private static String findDynamoRoot() {
    // now let's try to find dynamo home...
    String dynamoRootStr = DynamoEnv.getProperty("atg.dynamo.root");

    if (dynamoRootStr == null) {
        // let's try to look at an environment variable, just to
        // see....
        dynamoRootStr = CommandProcessor.getProcEnvironmentVar("DYNAMO_ROOT");
    }

    if (dynamoRootStr == null) {
        // try dynamo home
        String dynamoHomeStr = DynamoEnv.getProperty("atg.dynamo.home");
        if (StringUtils.isEmpty(dynamoHomeStr)) {
            dynamoHomeStr = null;
        }

        if (dynamoHomeStr == null) {
            dynamoHomeStr = CommandProcessor.getProcEnvironmentVar("DYNAMO_HOME");

            if (StringUtils.isEmpty(dynamoHomeStr)) {
                dynamoHomeStr = null;
            }

            if (dynamoHomeStr != null) {
                // make sure home is set as a property
                DynamoEnv.setProperty("atg.dynamo.home", dynamoHomeStr);
            }
        }

        if (dynamoHomeStr != null) {
            dynamoRootStr = dynamoHomeStr.trim() + File.separator + "..";
        }
    }

    if (dynamoRootStr == null) {
        // okay, start searching upwards for something that looks like
        // a dynamo directory, which should be the case for devtools
        File currentDir = new File(new File(".").getAbsolutePath());
        String strDynamoHomeLocalConfig = "Dynamo" + File.separator + "home" + File.separator + "localconfig";

        while (currentDir != null) {
            File filePotentialHomeLocalconfigDir = new File(currentDir, strDynamoHomeLocalConfig);
            if (filePotentialHomeLocalconfigDir.exists()) {
                dynamoRootStr = new File(currentDir, "Dynamo").getAbsolutePath();
                logger.debug("Found dynamo root via parent directory: " + dynamoRootStr);
                break;
            }
            currentDir = currentDir.getParentFile();
        }
    }

    if (dynamoRootStr == null) {
        // okay, we are not devtools-ish, so let's try using our ClassLoader
        // to figure things out.

        URL urlClass = NucleusUtils.class.getClassLoader().getResource("atg/nucleus/Nucleus.class");

        // okay... this should be jar URL...
        if ((urlClass != null) && "jar".equals(urlClass.getProtocol())) {
            String strFile = urlClass.getFile();
            int separator = strFile.indexOf('!');
            strFile = strFile.substring(0, separator);

            File fileCur = null;
            try {
                fileCur = urlToFile(new URL(strFile));
            } catch (MalformedURLException e) {
                // ignore
            }

            if (fileCur != null) {
                String strSubPath = "DAS/taglib/dspjspTaglib/1.0".replace('/', File.separatorChar);
                while ((fileCur != null) && fileCur.exists()) {
                    if (new File(fileCur, strSubPath).exists()) {
                        dynamoRootStr = fileCur.getAbsolutePath();
                        logger.debug("Found dynamo root by Nucleus.class location: " + dynamoRootStr);

                        break;
                    }
                    fileCur = fileCur.getParentFile();
                }
            }
        }
    }

    return dynamoRootStr;
}

From source file:com.stevpet.sonar.plugins.dotnet.mscover.codecoverage.command.WindowsCodeCoverageCommand.java

private void extractBinaries(String tempFolder) {
    try {//from   w w w . j a v  a2s  .c  o  m

        URL executableURL = WindowsCodeCoverageCommand.class.getResource(binaryFolder);
        String archivePath = StringUtils.substringBefore(executableURL.getFile().replace("%20", " "), "!")
                .substring(5);
        ZipUtils.extractArchiveFolderIntoDirectory(archivePath, binaryName, tempFolder);
    } catch (IOException e) {
        throw new MsCoverException("Could not extract the embedded executable: " + e.getMessage(), e);
    }
}

From source file:CWLClientTest.java

/**
 * This test demonstrates how to extract metadata from a CWL file.
 * @throws Exception//from w w  w.ja v a  2 s .c  o m
 */
@Test
public void extractMetadata() throws Exception {
    final URL resource = Resources.getResource("cwl.json");
    final CWL cwl = new CWL();
    final ImmutablePair<String, String> output = cwl.parseCWL(resource.getFile());
    final Map map = cwl.cwlJson2Map(output.getLeft());
    assertTrue(map.size() == 1 && ((Map) map.get("http://purl.org/dc/terms/creator")).size() == 3);
    String key = (String) ((Map) map.get("http://purl.org/dc/terms/creator"))
            .get("http://xmlns.com/foaf/0.1/name");
    assertTrue(Objects.equals(key, "Brian O'Connor"));
}