Example usage for java.io File getCanonicalPath

List of usage examples for java.io File getCanonicalPath

Introduction

In this page you can find the example usage for java.io File getCanonicalPath.

Prototype

public String getCanonicalPath() throws IOException 

Source Link

Document

Returns the canonical pathname string of this abstract pathname.

Usage

From source file:eu.annocultor.utils.XmlUtils.java

/**
 * //from  w w  w  .  ja va  2 s . co  m
 * @param fileStream
 * @param handler
 * @param validating
 * @return <code>true</code> on success.
 * @throws Exception
 */
public static int parseXmlFileSAX(File sourceFile, ConverterHandler handler, boolean validating)
        throws Exception {
    // Create a builder factory
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(validating);
    factory.setNamespaceAware(true);

    InputStream fileStream = new BufferedInputStream(new FileInputStream(sourceFile), 1024 * 1024);

    if (fileStream == null) {
        throw new Exception("Null input XML file stream");
    }
    if (handler == null) {
        throw new Exception("Null XML handler");
    }
    try {
        // Create the builder and parse the file
        SAXParser newSAXParser = factory.newSAXParser();
        if (newSAXParser == null) {
            throw new Exception("null SAX parser");
        }
        newSAXParser.parse(fileStream, handler);
    } catch (Exception e) {
        System.err.println("\n" + "*****************************************************\n"
                + "EXCEPTION OCCURRED in file " + sourceFile.getCanonicalPath() + "\n" + "at line "
                + handler.getDocumentLocator().getLineNumber() + ", column "
                + handler.getDocumentLocator().getColumnNumber());
        e.printStackTrace();
        System.err.println("\n" + "TRYING TO CLOSE FILES GRACEFULLY \n"
                + "*****************************************************\n");
        return -1;
    }
    return 0;
}

From source file:eu.eubrazilcc.lvl.oauth2.LinkedInJsonTest.java

@Test
public void test() {
    System.out.println("LinkedInJsonTest.test()");
    try {/*from ww  w  .  java 2s. co  m*/

        // test read from JSON message
        int total = 0, withNoIndustry = 0, withNoPositions = 0;
        final Collection<File> files = getLinkedInJsonFiles();
        for (final File file : files) {
            System.out.println(" >> JSON file: " + file.getCanonicalPath());
            final String payload = readFileToString(file);
            assertThat("payload is not null", payload, notNullValue());
            assertThat("payload is not empty", isNotBlank(payload), equalTo(true));

            final LinkedInMapper linkedInMapper = createLinkedInMapper().readObject(payload);
            final String userId = linkedInMapper.getUserId();
            assertThat("user Id is not null", userId, notNullValue());
            assertThat("user Id is not empty", isNotBlank(userId), equalTo(true));
            final String emailAddress = linkedInMapper.getEmailAddress();
            assertThat("email address is not null", emailAddress, notNullValue());
            assertThat("email address is not empty", isNotBlank(emailAddress), equalTo(true));
            final String firstName = linkedInMapper.getFirstName();
            assertThat("firstname is not null", firstName, notNullValue());
            assertThat("firstname is not empty", isNotBlank(firstName), equalTo(true));
            final String lastName = linkedInMapper.getLastName();
            assertThat("lastname is not null", lastName, notNullValue());
            assertThat("lastname is not empty", isNotBlank(lastName), equalTo(true));
            final String industry = linkedInMapper.getIndustry().or(INDUSTRY_DEFAULT);
            assertThat("industry is not null", industry, notNullValue());
            assertThat("industry is not empty", isNotBlank(industry), equalTo(true));
            if (INDUSTRY_DEFAULT.equals(industry))
                withNoIndustry++;
            final Set<String> positions = linkedInMapper.getPositions().or(POSITION_DEFAULT);
            assertThat("positions is not null", positions, notNullValue());
            assertThat("positions is not empty", positions.isEmpty(), equalTo(false));
            if (POSITION_DEFAULT.equals(positions))
                withNoPositions++;
            total++;
            /* uncomment for additional output */
            System.out.println(" >> LinkedIn profile: usedid='" + userId + "', email='" + emailAddress
                    + "', firstname='" + firstName + "', lastname='" + lastName + "', industry='" + industry
                    + "', possitions='" + join(positions, ',') + "'");
        }
        assertThat("total number of read JSON messages coincides with expected", total,
                allOf(greaterThan(0), equalTo(files.size())));
        assertThat("records with no industry coincides with expected", withNoIndustry,
                allOf(greaterThanOrEqualTo(1), lessThan(total)));
        assertThat("records with no positions coincides with expected", withNoPositions,
                allOf(greaterThanOrEqualTo(1), lessThan(total)));

    } catch (Exception e) {
        e.printStackTrace(System.err);
        fail("LinkedInJsonTest.test() failed: " + e.getMessage());
    } finally {
        System.out.println("LinkedInJsonTest.test() has finished");
    }
}

From source file:azkaban.database.AzkabanDatabaseSetupTest.java

@Ignore
@Test//from   w w w .  j a va 2  s.  c om
public void testH2Query() throws Exception {
    File dbDir = temp.newFolder("h2dbtest");
    Props h2Props = getH2Props(dbDir.getCanonicalPath(), sqlScriptsDir);
    AzkabanDatabaseSetup setup = new AzkabanDatabaseSetup(h2Props);

    // First time will create the tables
    setup.loadTableInfo();
    setup.printUpgradePlan();
    setup.updateDatabase(true, true);
    assertTrue(setup.needsUpdating());

    // Second time will update some tables. This is only for testing purpose and
    // obviously we wouldn't set things up this way.
    setup.loadTableInfo();
    setup.printUpgradePlan();
    setup.updateDatabase(true, true);
    assertTrue(setup.needsUpdating());

    // Nothing to be done
    setup.loadTableInfo();
    setup.printUpgradePlan();
    assertFalse(setup.needsUpdating());
}

From source file:es.tid.fiware.rss.service.CdrsManager.java

/**
 * Get File where save cdrs./*from w w w.j  a  v  a 2s  .co  m*/
 * 
 * @return
 * @throws IOException
 */
public File getFile() throws IOException {
    Date date = Calendar.getInstance().getTime();
    DateFormat formatter = new SimpleDateFormat("yyyyMMdd_hhmmss");
    String dateFormatted = formatter.format(date);
    String path = (String) rssProps.get("cdrfilepath");
    File cdrFile = new File(path + "fiwarecdr_" + dateFormatted + ".xml");
    cdrFile.createNewFile();
    logger.debug("File created: " + cdrFile.getCanonicalPath());
    return cdrFile;
}

From source file:org.apache.solr.client.solrj.embedded.JettyWebappTest.java

@Override
public void setUp() throws Exception {
    super.setUp();
    System.setProperty("solr.solr.home", SolrJettyTestBase.legacyExampleCollection1SolrHome());
    System.setProperty("tests.shardhandler.randomSeed", Long.toString(random().nextLong()));
    System.setProperty("solr.tests.doContainerStreamCloseAssert", "false");

    File dataDir = createTempDir().toFile();
    dataDir.mkdirs();/*from w ww . jav  a 2s.c  om*/

    System.setProperty("solr.data.dir", dataDir.getCanonicalPath());
    String path = ExternalPaths.WEBAPP_HOME;

    server = new Server(port);
    // insecure: only use for tests!!!!
    server.setSessionIdManager(new HashSessionIdManager(new Random(random().nextLong())));
    new WebAppContext(server, path, context);

    ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory());
    connector.setIdleTimeout(1000 * 60 * 60);
    connector.setSoLingerTime(-1);
    connector.setPort(0);
    server.setConnectors(new Connector[] { connector });
    server.setStopAtShutdown(true);

    server.start();
    port = connector.getLocalPort();
}

From source file:eu.eubrazilcc.lvl.core.GbSeqXmlFileTest.java

@Test
public void test() {
    System.out.println("GbSeqXmlFileTest.test()");
    try {/*from  w  ww.j a  v a 2s  .  co m*/
        File output = null;
        String payload = null;

        // test writing individual FASTA files (uncompressed)
        final Collection<File> files = getGBSeqXMLFiles();
        for (final File file : files) {
            System.out.println(" >> Sequence file: " + file.getCanonicalPath());
            output = new File(TEST_OUTPUT_DIR, "sequence.fasta");
            toFasta(file, output.getCanonicalPath(), false);
            assertThat("fasta sequence file exists: " + output.getCanonicalPath(), output.canRead(),
                    equalTo(true));
            payload = readFileToString(output);
            assertThat("fasta sequence is not null", payload, notNullValue());
            assertThat("fasta sequence is not empty", isNotBlank(payload), equalTo(true));
            /* uncomment for additional output */
            System.out.println(" >> FASTA sequence \n" + payload);
        }

        // test writing a single FASTA file (uncompressed)
        output = new File(TEST_OUTPUT_DIR, "sequences.fasta");
        toFasta(files, output.getCanonicalPath(), false);
        assertThat("fasta sequences file exists: " + output.getCanonicalPath(), output.canRead(),
                equalTo(true));
        payload = readFileToString(output);
        assertThat("fasta sequences is not null", payload, notNullValue());
        assertThat("fasta sequences is not empty", isNotBlank(payload), equalTo(true));
        /* uncomment for additional output */
        System.out.println(" >> FASTA sequences \n" + payload);

        // test writing a FASTA file (compressed)
        final List<File> list = newArrayList(files);
        Collections.shuffle(list);
        final File file = list.get(0);
        output = new File(TEST_OUTPUT_DIR, "sequence.fasta.gz");
        toFasta(file, output.getCanonicalPath(), false);
        assertThat("fasta GZIP compressed file exists: " + output.getCanonicalPath(), output.canRead(),
                equalTo(true));
        assertThat("fasta GZIP compressed file is not empty", output.length() > 0l, equalTo(true));

    } catch (Exception e) {
        e.printStackTrace(System.err);
        fail("GbSeqXmlFileTest.test() failed: " + e.getMessage());
    } finally {
        System.out.println("GbSeqXmlFileTest.test() has finished");
    }
}

From source file:ejava.projects.edmv.xml.EDmvParserTest.java

public void testParser() throws Exception {
    File inDir = new File(inputDir);
    File[] files = inDir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return (name.startsWith("dmv-") && name.endsWith(".xml"));
        }/*from www .  j  a  v  a 2s  .  c  om*/
    });
    for (File file : files) {
        testParser(file.getCanonicalPath());
    }
}

From source file:com.solace.data.BaseTest.java

/**
 * /*w  ww . ja v  a  2 s.c  o  m*/
 * @param from
 * @param to
 * @throws Exception
 */
protected void copyFile(String from, String to) throws Exception {

    // /src/test/resources

    File dir = new File(".");

    String d = dir.getCanonicalPath();

    System.out.println("dir: " + d);

    // if ( !(new File(d + from)).exists() )
    // d += "/src/test/resources";

    File src = new File(d + from);

    if (!src.exists())
        throw new ArgumentException(String.format("{} does not exist", src.getCanonicalPath()));

    File dest = new File(d + to);

    LOGGER.debug("copying {} to {}", src.getCanonicalPath(), dest.getCanonicalPath());

    if (dest.exists())
        dest.delete();

    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dest);

    StringBuffer content = new StringBuffer();

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        content.append(new String(buf));
        out.write(buf, 0, len);
        buf = new byte[1024];
    }
    LOGGER.debug("content: \n" + content.toString());
    in.close();
    out.flush();
    out.close();

    if (!dest.exists())
        throw new ArgumentException(String.format("{} was not copied", dest.getCanonicalPath()));

    files.add(dest);
}

From source file:com.jsquant.util.FileCache.java

public void put(String key, String value) throws IOException {
    File f = new File(cacheDir, key);
    synchronized (this) {
        memCache.put(key, value);//  w  w  w . j a v  a2s  .  c o  m
        if (!f.exists()) {
            log.info("writing cachePath=" + f.getCanonicalPath());
            FileUtils.writeFile(f, value);
            //Files.write(value.getBytes(Charsets.UTF_8), f);
        }
    }
}

From source file:com.adaptris.core.LogHandlerTest.java

@Test
public void testFileLogHandlerCleanNonExistent() throws Exception {
    FileLogHandler fh = new FileLogHandler();
    fh.setPeriod(1);/*  w w w.ja v a  2 s. co m*/
    fh.setLogFile("adapter.log");
    File tmpDir = File.createTempFile("TMP", "");
    fh.setLogDirectory(tmpDir.getCanonicalPath());
    fh.clean();
    FileUtils.deleteQuietly(tmpDir);
}