Example usage for java.io File toString

List of usage examples for java.io File toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns the pathname string of this abstract pathname.

Usage

From source file:org.jasig.portlet.announcements.Importer.java

private void importAnnouncements() {
    try {//from w w  w .java 2 s. co m
        JAXBContext jc = JAXBContext.newInstance(Announcement.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();

        File[] files = dataDirectory.listFiles(new AnnouncementImportFileFilter());

        if (files == null) {
            errors.add("Directory " + dataDirectory + " is not a valid directory");
        } else {

            for (File f : files) {
                log.info("Processing file " + f.toString());
                StreamSource xml = new StreamSource(f.getAbsoluteFile());
                try {
                    JAXBElement<Announcement> je1 = unmarshaller.unmarshal(xml, Announcement.class);
                    Announcement announcement = je1.getValue();
                    if (StringUtils.isBlank(announcement.getTitle())) {
                        String msg = "Error parsing " + f.toString() + "; did not get valid record:\n"
                                + announcement.toString();
                        log.error(msg);
                        errors.add(msg);
                    } else if (announcement.getParent() == null
                            || StringUtils.isBlank(announcement.getParent().getTitle())) {
                        String msg = "Announcement in file " + f.toString()
                                + " does not reference a topic with a title";
                        log.error(msg);
                        errors.add(msg);
                    } else {
                        Topic topic = findTopicForAnnouncement(announcement);
                        announcement.setParent(topic);
                        announcementService.addOrSaveAnnouncement(announcement);
                        log.info("Successfully imported announcement '" + announcement.getTitle() + "'");
                    }
                } catch (ImportException e) {
                    log.error(e.getMessage());
                    errors.add(e.getMessage());
                } catch (JAXBException e) {
                    String msg = "JAXB exception " + e.getCause().getMessage() + " processing file "
                            + f.toString();
                    log.error(msg, e);
                    errors.add(msg + ". See stack trace");
                } catch (HibernateException e) {
                    String msg = "Hibernate exception " + e.getCause().getMessage() + " processing file "
                            + f.toString();
                    log.error(msg, e);
                    errors.add(msg + ". See stack trace");
                }
            }
        }
    } catch (JAXBException e) {
        String msg = "Fatal JAXBException in importAnnouncements - no Announcements imported";
        log.fatal(msg, e);
        errors.add(msg + ".  See stack trace");
    }
}

From source file:au.org.ala.delta.util.LocalConfigFiles.java

public File getSettingsDirectory() {
    String userHome = System.getProperty("user.home");
    if (userHome == null) {
        throw new IllegalStateException("user.home==null");
    }//w  ww. j  av a  2 s .c o m
    File home = new File(userHome);
    File settingsDirectory = new File(home, String.format(".open-delta%s.%s", File.separator, _appKey));
    if (!settingsDirectory.exists()) {
        if (!settingsDirectory.mkdirs()) {
            throw new IllegalStateException(settingsDirectory.toString());
        }
    }
    return settingsDirectory;
}

From source file:com.photon.phresco.framework.param.impl.DynamicFetchSqlImpl.java

private void fetchSqlFilePath(PossibleValues possibleValues, ApplicationInfo applicationInfo,
        String sqlFilePath, String dbname, List<Configuration> configurations, String rootModulePath,
        String subModuleName) throws PhrescoException {
    String dbVersion = "";
    String sqlFileName = "";
    String path = "";
    for (Configuration configuration : configurations) {
        String dbType = configuration.getProperties().getProperty(DB_TYPE).toLowerCase();
        if (dbType.equals(dbname)) {
            dbVersion = configuration.getProperties().getProperty(DB_VERSION);
            ProjectInfo info = Utility.getProjectInfo(rootModulePath, "");
            File srcFolderLocation = Utility.getSourceFolderLocation(info, rootModulePath, subModuleName);
            StringBuilder sb = new StringBuilder(srcFolderLocation.toString());
            sb.append(File.separator).append(sqlFilePath).append(dbname).append(File.separator)
                    .append(dbVersion);/*w w w  .  j  a va  2 s  .c  o  m*/

            File[] dbSqlFiles = new File(sb.toString()).listFiles(new DumpFileNameFilter());
            for (int i = 0; i < dbSqlFiles.length; i++) {
                if (!dbSqlFiles[i].isDirectory()) {
                    Value value = new Value();
                    sqlFileName = dbSqlFiles[i].getName();
                    path = sqlFilePath + dbname + "/" + dbVersion + "/" + sqlFileName;
                    value.setKey(dbname);
                    value.setValue(path);
                    possibleValues.getValue().add(value);
                }
            }
        }
    }
}

From source file:psiprobe.controllers.certificates.ListCertificatesControllerTest.java

@Test
public void testGetCertificates() throws Exception {
    ListCertificatesController controller = new ListCertificatesController();

    String storeType = "jks";
    File storeFile = ctx.getResource("classpath:certs/localhost-truststore.jks").getFile();
    String storePassword = "123456";

    List<Cert> certs = controller.getCertificates(storeType, storeFile.toString(), storePassword);

    assertThat(certs, notNullValue());//w w  w . j a va  2  s .  c  om
    assertThat(certs.size(), is(2));
    assertThat(certs.get(0).getAlias(), is("google internet authority g2"));
    assertThat(certs.get(1).getAlias(), is("*.google.com"));
}

From source file:com.linkedin.pinot.core.segment.store.SegmentDirectoryPathsTest.java

@Test
public void testFindMetadataFile() throws IOException {
    File tempDirectory = null;/*from  w  ww.j  a va2  s  . c  o m*/
    try {
        // setup temp dir, v3 subdir and create metadata.properties in both
        tempDirectory = new File(SegmentDirectoryPaths.class.toString());
        tempDirectory.deleteOnExit();
        FileUtils.forceMkdir(tempDirectory);
        File v3Dir = new File(tempDirectory, "v3");
        FileUtils.forceMkdir(v3Dir);
        File metaFile = new File(tempDirectory, V1Constants.MetadataKeys.METADATA_FILE_NAME);
        try (FileOutputStream outputStream = new FileOutputStream(metaFile)) {
            outputStream.write(10);
        }
        File v3MetaFile = new File(v3Dir, V1Constants.MetadataKeys.METADATA_FILE_NAME);
        FileUtils.copyFile(metaFile, v3MetaFile);

        {
            File testMetaFile = SegmentDirectoryPaths.findMetadataFile(tempDirectory);
            Assert.assertNotNull(testMetaFile);
            Assert.assertEquals(testMetaFile.toString(), metaFile.toString());

            testMetaFile = SegmentDirectoryPaths.findMetadataFile(tempDirectory, SegmentVersion.v1);
            Assert.assertNotNull(testMetaFile);
            Assert.assertEquals(testMetaFile.toString(), metaFile.toString());

            testMetaFile = SegmentDirectoryPaths.findMetadataFile(tempDirectory, SegmentVersion.v3);
            Assert.assertNotNull(testMetaFile);
            Assert.assertEquals(testMetaFile.toString(), v3MetaFile.toString());
        }
        {
            // drop v1 metadata file
            FileUtils.forceDelete(metaFile);
            File testMetaFile = SegmentDirectoryPaths.findMetadataFile(tempDirectory);
            Assert.assertNotNull(testMetaFile);
            Assert.assertEquals(testMetaFile.toString(), v3MetaFile.toString());

            testMetaFile = SegmentDirectoryPaths.findMetadataFile(tempDirectory, SegmentVersion.v1);
            Assert.assertNull(testMetaFile);

            testMetaFile = SegmentDirectoryPaths.findMetadataFile(tempDirectory, SegmentVersion.v3);
            Assert.assertNotNull(testMetaFile);
            Assert.assertEquals(testMetaFile.toString(), v3MetaFile.toString());
        }
        {
            // drop v3 metadata file
            FileUtils.forceDelete(v3MetaFile);
            File testMetaFile = SegmentDirectoryPaths.findMetadataFile(tempDirectory);
            Assert.assertNull(testMetaFile);

            testMetaFile = SegmentDirectoryPaths.findMetadataFile(tempDirectory, SegmentVersion.v1);
            Assert.assertNull(testMetaFile);

            testMetaFile = SegmentDirectoryPaths.findMetadataFile(tempDirectory, SegmentVersion.v3);
            Assert.assertNull(testMetaFile);
        }
    } finally {
        if (tempDirectory != null) {
            FileUtils.deleteQuietly(tempDirectory);
        }
    }
}

From source file:com.datasalt.pangool.solr.TupleSolrOutputFormat.java

private static void createZip(File dir, File out) throws IOException {
    HashSet<File> files = new HashSet<File>();
    // take only conf/ and lib/
    for (String allowedDirectory : SolrRecordWriter.getAllowedConfigDirectories()) {
        File configDir = new File(dir, allowedDirectory);
        boolean configDirExists;
        /** If the directory does not exist, and is required, bail out */
        if (!(configDirExists = configDir.exists())
                && SolrRecordWriter.isRequiredConfigDirectory(allowedDirectory)) {
            throw new IOException(String.format("required configuration directory %s is not present in %s",
                    allowedDirectory, dir));
        }//from   w  ww .j av  a2s .com
        if (!configDirExists) {
            continue;
        }
        listFiles(configDir, files); // Store the files in the existing, allowed
                                     // directory configDir, in the list of files
                                     // to store in the zip file
    }

    out.delete();
    int subst = dir.toString().length();
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(out));
    byte[] buf = new byte[1024];
    for (File f : files) {
        ZipEntry ze = new ZipEntry(f.toString().substring(subst));
        zos.putNextEntry(ze);
        InputStream is = new FileInputStream(f);
        int cnt;
        while ((cnt = is.read(buf)) >= 0) {
            zos.write(buf, 0, cnt);
        }
        is.close();
        zos.flush();
        zos.closeEntry();
    }
    zos.close();
}

From source file:com.google.caja.precajole.StaticPrecajoleMap.java

public StaticPrecajoleMap(File baseDir) {
    this(baseDir.toString());
}

From source file:mediathekplugin.MediathekProgramItem.java

private void openStream() {
    Thread streamThread = new Thread("Stream copy") {
        ProgressMonitor monitor = null;

        @Override/*from  w  w  w .  j  a va  2  s  .  c o m*/
        public void run() {
            try {
                monitor = new ProgressMonitor(MediathekPlugin.getInstance().getFrame(),
                        mLocalizer.msg("store", "Getting local stream copy..."), " ", 0, 3);
                monitor.setMillisToDecideToPopup(0);
                setNote(0, mLocalizer.ellipsisMsg("temp", "Starting flvstreamer"));
                File tempFile = File.createTempFile("mediathek", ".flv");
                String fileName = tempFile.toString();
                tempFile.delete();
                String streamParams = mUrl + " --flv " + fileName;
                ExecutionHandler streamer = new ExecutionHandler(streamParams, "flvstreamer");
                streamer.execute();
                DecimalFormat format = new DecimalFormat("0.00");
                setNote(1, mLocalizer.ellipsisMsg("wait", "Waiting for flvstreamer to get some data ({0} MB)",
                        format.format(0.0)));
                int time = 0;
                long fileSize = 0;
                try {
                    while (time < 20 && fileSize < 10 * 1024 * 1024 && !monitor.isCanceled()) {
                        Thread.sleep(500);
                        time++;
                        fileSize = tempFile.length();
                        double mb = fileSize / 1048576.0;
                        setNote(1, mLocalizer.ellipsisMsg("wait",
                                "Waiting for flvstreamer to get some data ({0} MB)", format.format(mb)));
                    }
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (!monitor.isCanceled()) {
                    setNote(2, mLocalizer.ellipsisMsg("player", "Starting player"));
                    ExecutionHandler player = new ExecutionHandler(fileName, "vlc");
                    player.execute();
                    setNote(3, "");
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (monitor != null) {
                monitor.close();
            }
        }

        private void setNote(final int progress, final String note) {
            try {
                UIThreadRunner.invokeAndWait(new Runnable() {

                    public void run() {
                        monitor.setProgress(progress);
                        monitor.setNote(note);
                    }
                });
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
    streamThread.start();
}

From source file:com.digitalgeneralists.assurance.model.merge.BidirectionalMergeEngine.java

@Override
public void mergeResult(ComparisonResult result, IProgressMonitor monitor) {
    File sourceFile = result.getSource().getFile();
    File targetFile = result.getTarget().getFile();

    if (monitor != null) {
        StringBuilder message = new StringBuilder(512);
        monitor.publish(message.append("Merging ").append(targetFile.toString()).append(" to ")
                .append(sourceFile.toString()).toString());
        message.setLength(0);/*from  w w w.j  av  a2s . c o m*/
        message = null;
    }

    if (sourceFile.exists()) {
        try {
            if (sourceFile.isDirectory()) {
                FileUtils.copyDirectory(sourceFile, targetFile);
            } else {
                FileUtils.copyFile(sourceFile, targetFile);
            }
            result.setResolution(AssuranceResultResolution.REPLACE_TARGET);
        } catch (IOException e) {
            logger.error("An error occurred when replacing the target with the source.");
            result.setResolution(AssuranceResultResolution.PROCESSING_ERROR_ENCOUNTERED);
            result.setResolutionError(e.getMessage());
        }
    } else {
        if (targetFile.exists()) {
            try {
                if (targetFile.isDirectory()) {
                    FileUtils.copyDirectory(targetFile, sourceFile);
                } else {
                    FileUtils.copyFile(targetFile, sourceFile);
                }
                result.setResolution(AssuranceResultResolution.REPLACE_SOURCE);
            } catch (IOException e) {
                logger.error("An error occurred when replacing the source with the target.");
                result.setResolution(AssuranceResultResolution.PROCESSING_ERROR_ENCOUNTERED);
                result.setResolutionError(e.getMessage());
            }
        }
    }

    sourceFile = null;
    targetFile = null;
}

From source file:com.norconex.collector.http.crawler.BasicFeaturesTest.java

@Test
public void testKeepDownload() throws IOException {
    HttpCollector collector = newHttpCollector1Crawler("/test/a$dir/blah?case=keepDownloads");
    HttpCrawler crawler = (HttpCrawler) collector.getCrawlers()[0];
    crawler.getCrawlerConfig().setMaxDepth(0);
    crawler.getCrawlerConfig().setKeepDownloads(true);
    //        String url = crawler.getCrawlerConfig().getStartURLs()[0];
    collector.start(false);/*from w  ww.  ja va2  s  .c o  m*/

    File downloadDir = new File(crawler.getCrawlerConfig().getWorkDir(), "downloads");
    final Mutable<File> downloadedFile = new MutableObject<>();
    FileUtil.visitAllFiles(downloadDir, new IFileVisitor() {
        @Override
        public void visit(File file) {
            if (downloadedFile.getValue() != null) {
                return;
            }
            if (file.toString().contains("downloads")) {
                downloadedFile.setValue(file);
            }
        }
    });
    String content = FileUtils.readFileToString(downloadedFile.getValue());
    Assert.assertTrue("Invalid or missing download file.", content
            .contains("<b>This</b> file <i>must</i> be saved as is, " + "with this <span>formatting</span>"));
}