Example usage for java.io FileNotFoundException FileNotFoundException

List of usage examples for java.io FileNotFoundException FileNotFoundException

Introduction

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

Prototype

public FileNotFoundException() 

Source Link

Document

Constructs a FileNotFoundException with null as its error detail message.

Usage

From source file:edu.stanford.muse.index.PDFHandler.java

/** handles a pdf file. philosophy: create png files and text file in topLevelFromDir
 * and copy them to webappTopLevelDir.//from w w w. j a v  a  2  s  . co m
 * because webappTopLevelDir could get wiped out when the web server restarts.
 * always copies pdf and png's.
 * updates docCache with contents and header if needed. */
private PDFDocument handlePDF(DocCache docCache, String topLevelFromDir, String webappTopLevelDir,
        String libDir, String userKey, String datasetTitle, int num, String description, String section,
        File pdfFile) {

    // x.pdf: text goes to x.pdf.txt, and page images to go x.pdf.1.png, x.pdf.2.png, etc
    String filename = pdfFile.getName(); // not full path, just the name of the file
    String topLevelToDir = webappTopLevelDir + File.separator + datasetTitle;
    String txtFilename = filename + ".txt";
    String pagePNGPrefix = filename + ".";

    // working dirs are just <top level>/<section>
    String workingFromDir = topLevelFromDir + File.separator + section;
    String workingToDir = topLevelToDir + File.separator + section;

    // create the working dir for this section if it doesn't exist
    new File(workingToDir + File.separator + "dummy").mkdirs();

    // given the pdf, create a .txt and .png files for each page.
    // copy the pdf and png's to the todir because the browser may need to access them directly
    // the txt file never needs to be directly accessible.
    try {
        if (!pdfFile.exists())
            throw new FileNotFoundException();

        // copy the pdf
        Util.copyFileIfItDoesntExist(workingFromDir, workingToDir, filename);

        String txtFileFromFullPath = workingFromDir + File.separator + txtFilename;
        String cp = libDir + File.separator + "log4j-1.2.15.jar" + File.pathSeparator;
        cp += libDir + File.separator + "pdfbox-1.1.0.jar" + File.pathSeparator;
        cp += libDir + File.separator + "fontbox-1.1.0.jar" + File.pathSeparator;
        cp += libDir + File.separator + "commons-logging-1.1.1.jar" + File.pathSeparator;

        // generate the txt file if it doesn't exist
        // we launch in a separate vm because it has a tendency to crash the VM
        if (!docCache.hasContents(datasetTitle, num)) {
            String cmd = "java -cp " + cp + " org.apache.pdfbox.ExtractText " + filename + " " + txtFilename;
            Util.run_command(cmd, workingFromDir);
            if (!new File(txtFileFromFullPath).exists()) {
                // create a dummy file
                FileOutputStream fos = new FileOutputStream(txtFileFromFullPath);
                fos.close();
            }

            String contents = Util.getFileContents(workingFromDir + File.separator + txtFilename);
            docCache.saveContents(contents, datasetTitle, num);
        }

        // handle images
        File dirFile = new File(workingFromDir);
        File files[] = dirFile
                .listFiles(new Util.MyFilenameFilter(workingFromDir + File.separator + pagePNGPrefix, ".png"));
        if (files.length == 0) {
            // png files not generated
            // resolution 200 makes the images readable
            String cmd = "java -cp " + cp + " org.apache.pdfbox.PDFToImage -imageType png -outputPrefix "
                    + pagePNGPrefix + " -resolution 100 " + filename;
            Util.run_command(cmd, workingFromDir);
            files = dirFile.listFiles(
                    new Util.MyFilenameFilter(workingFromDir + File.separator + pagePNGPrefix, ".png"));
            if (files.length == 0) {
                // if still no files, something must have failed. copy a sorry file.

                String dummyFile = workingFromDir + pagePNGPrefix + ".0.png";
                Util.copy_file(webappTopLevelDir + File.separator + "images" + File.separator + "sorry.png",
                        dummyFile);
                files = new File[1];
                files[0] = new File(dummyFile);
            }
        }

        Util.sortFilesByTime(files);

        // copy over PNG Files
        for (File f : files)
            Util.copyFileIfItDoesntExist(workingFromDir, workingToDir, f.getName());

        // note it's important to escape url's below.
        // this is because the dataset or section etc can contain special chars like '#'
        // but we can't use URLEncoder.encode because that causes problems by converting each space to a +.
        // this breaks the relative URL in the browser.
        // therefore, we reuse the "light encoding" of Util.URLEncodeFilePath
        // may need fixing if other special chars pop up
        List<String> relativeURLsForImages = new ArrayList<String>();
        for (@SuppressWarnings("unused")
        File f : files) {
            String relativeURL = userKey + "/" + datasetTitle + "/" + section + "/" + filename;
            //            relativeURL = URLEncoder.encode(relativeURL, "UTF-8");
            relativeURL = Util.URLEncodeFilePath(relativeURL);
            relativeURLsForImages.add(relativeURL);
        }
        String relativeURLForPDF = userKey + "/" + datasetTitle + "/" + section + "/" + filename;
        //      relativeURLForPDF = URLEncoder.encode(relativeURLForPDF, "UTF-8");
        relativeURLForPDF = Util.URLEncodeFilePath(relativeURLForPDF);

        PDFDocument doc = new PDFDocument(num, "PDF", section, relativeURLForPDF, relativeURLsForImages);
        // text contents will remain in topLevelFromDir
        // sanitize path to ensure we escape odd chars like # and ? in the file path
        doc.url = docCache.getContentURL(datasetTitle, num);
        if (!docCache.hasHeader(datasetTitle, num))
            docCache.saveHeader(doc, datasetTitle, num);
        return doc;

        //         cmd = "java -cp " + cp + "/ org.apache.pdfbox.ExtractImages -prefix " + filename + " " + filename;
        //         Util.run_command(cmd, workingDir);
    } catch (Exception e) {
        Util.print_exception(e, log);
        return null;
    }
}

From source file:com.xxg.jdeploy.util.FileUtil.java

public static StringBuffer readTextFile(File file, boolean newline) throws FileNotFoundException, IOException {
    if (!file.exists()) {
        throw new FileNotFoundException();
    }//  ww w  .j  a  v a 2s  . c  om

    StringBuffer buf = new StringBuffer();
    BufferedReader in = null;
    try {
        in = new BufferedReader(new FileReader(file));
        //in = new BufferedReader(new InputStreamReader(new FileInputStream(file), Charsets.toCharset("UTF-8")));
        //in = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        //InputStreamReader read = new InputStreamReader(new FileInputStream(file));
        //System.out.println("File Encoding:["+ read.getEncoding());

        String str;
        while ((str = in.readLine()) != null) {
            buf.append(str);
            if (newline) {
                buf.append(System.getProperty("line.separator"));
            }
        }
    } catch (IOException e) {
        throw e;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                throw e;
            }
        }
    }

    return buf;
}

From source file:eu.scape_project.resource.connector.Files.java

/**
 * Exposes an HTTP GET end point witch returns the current version binary
 * content of a {@link File} or if references are used for files a HTTP
 * redirect a from the Connector API implementation
 * /* ww  w.j ava2 s  .c om*/
 * @param entityId
 *            the {@link IntellectualEntity}'s id
 * @param repId
 *            the {@link Representation}'s id
 * @param fileId
 *            the {@link File}'s id
 * @return A {@link Response} with the binary content or a HTTP redirect
 * @throws RepositoryException
 *             if an error occurred while fetching the binary content
 */
@GET
@Path("{entity-id}/{rep-id}/{file-id}")
public Response retrieveFile(@PathParam("entity-id") final String entityId,
        @PathParam("rep-id") final String repId, @PathParam("file-id") final String fileId)
        throws RepositoryException {
    if (connectorService.isReferencedContent()) {
        IntellectualEntity e = connectorService.fetchEntity(session, entityId);
        for (Representation r : e.getRepresentations()) {
            if (r.getIdentifier().getValue().equals(repId)) {
                for (File f : r.getFiles()) {
                    if (f.getIdentifier().getValue().equals(fileId)) {
                        return Response.temporaryRedirect(f.getUri()).build();
                    }
                }
            }
        }
        throw new RepositoryException(new FileNotFoundException());
    } else {
        final ContentTypeInputStream src = connectorService.fetchBinaryFile(this.session, entityId, repId,
                fileId, null);
        return Response.ok().entity(src).type(src.getContentType()).build();
    }
}

From source file:cc.kune.core.server.manager.file.ImageUtilsDefault.java

/**
 * Check exist./*from   ww w .jav  a  2s.  c o  m*/
 * 
 * @param fileOrig
 *          the file orig
 * @throws FileNotFoundException
 *           the file not found exception
 */
private static void checkExist(final String fileOrig) throws FileNotFoundException {
    final File file = new File(fileOrig);
    if (!file.exists()) {
        throw new FileNotFoundException();
    }
}

From source file:com.ccoe.build.alerts.pfdash.PfDashJob.java

public void run(File file) {
    String[] location = ServiceConfig.get("pfdash.db.host").split(";");
    List<String> locationList = Arrays.asList(location);
    int port = ServiceConfig.getInt("pfdash.db.port");
    String dbname = ServiceConfig.get("pfdash.db.name");
    DB db = null;//  w w  w . j  a  va  2s.c  o  m

    Date date = new Date();
    Date currentStartTime = DateUtils.getUTCOneDayBack(date);
    Date currentEndTime = DateUtils.getUTCMidnightZero(date);
    Condition current = new Condition();
    current.setStartDate(currentStartTime);
    current.setEndDate(currentEndTime);

    Date previousStartTime = DateUtils.getUTCOneWeekBack(currentStartTime);
    Date previousEndTime = DateUtils.getUTCOneWeekBack(currentEndTime);
    Condition previous = new Condition();
    previous.setStartDate(previousStartTime);
    previous.setEndDate(previousEndTime);
    File parentDirectory = null;

    Time time = new Time();
    TimeZone timeZone = TimeZone.getDefault();
    TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
    time.setQueryStart(DateUtils.getDateTimeString(currentStartTime, utcTimeZone));
    time.setQueryEnd(DateUtils.getDateTimeString(currentEndTime, utcTimeZone));
    boolean warning = false;
    EmailSender rlb = null;
    try {

        db = Connector.connectDB(locationList, port, dbname);
        db.slaveOk();
        parentDirectory = new File(PfDashJob.class.getResource("/").toURI());
        File xmlFile = new File(parentDirectory, "alert_kpi_threshold.xml");
        if (!xmlFile.exists()) {
            throw new FileNotFoundException();
        }
        Compare com = new Compare(xmlFile, db);
        AlertResult ar = com.judgeRules(current, previous);
        time.setSend(DateUtils.getDateTimeString(date, timeZone));
        System.out.println("Email sentTime: " + date);
        rlb = new EmailSender(ar, time);

        for (SingleResult singleResult : ar.getResultlist()) {
            if (!"#CACACA".equals(singleResult.getColor())) {
                warning = true;
            }
        }

        rlb.sendMail(file, warning);
    } catch (Exception e) {
        e.printStackTrace();
        String trace = ExceptionUtils.getStackTrace(e);
        rlb = new EmailSender();
        rlb.sendMail(trace, warning);
        System.out.println("[INFO]: Fail to send pfDash alert email, and an exception email has been send. ");
    }

}

From source file:com.clican.pluto.transaction.resources.memory.XAFileResourceMemoryImpl.java

public InputStream getInputStream() throws XAException, FileNotFoundException {
    if (xidThreadLocal.get() == null) {
        throw new XAException();
    }//  w  ww . j ava  2  s.com
    byte[] data = oldDataMapping.get(xidThreadLocal.get());
    if (data == null) {
        throw new FileNotFoundException();
    }
    return new ByteArrayInputStream(data);
}

From source file:jenkins.plugins.git.GitSCMFile.java

@NonNull
@Override//from   w  w  w.jav  a 2 s.c o m
public Iterable<SCMFile> children() throws IOException, InterruptedException {
    return fs.invoke(new GitSCMFileSystem.FSFunction<List<SCMFile>>() {
        @Override
        public List<SCMFile> invoke(Repository repository) throws IOException, InterruptedException {
            try (RevWalk walk = new RevWalk(repository)) {
                RevCommit commit = walk.parseCommit(fs.getCommitId());
                RevTree tree = commit.getTree();
                if (isRoot()) {
                    try (TreeWalk tw = new TreeWalk(repository)) {
                        tw.addTree(tree);
                        tw.setRecursive(false);
                        List<SCMFile> result = new ArrayList<SCMFile>();
                        while (tw.next()) {
                            result.add(new GitSCMFile(fs, GitSCMFile.this, tw.getNameString()));
                        }
                        return result;
                    }
                } else {
                    try (TreeWalk tw = TreeWalk.forPath(repository, getPath(), tree)) {
                        if (tw == null) {
                            throw new FileNotFoundException();
                        }
                        FileMode fileMode = tw.getFileMode(0);
                        if (fileMode == FileMode.MISSING) {
                            throw new FileNotFoundException();
                        }
                        if (fileMode != FileMode.TREE) {
                            throw new IOException("Not a directory");
                        }
                        tw.enterSubtree();
                        List<SCMFile> result = new ArrayList<SCMFile>();
                        while (tw.next()) {
                            result.add(new GitSCMFile(fs, GitSCMFile.this, tw.getNameString()));
                        }
                        return result;
                    }
                }
            }
        }
    });
}

From source file:AmazonKinesisFirehoseToRedshiftSample.java

/**
 * Load the input parameters from properties file.
 *
 * @throws FileNotFoundException/*  ww w.j  a  va  2 s  .  c  o m*/
 * @throws IOException
 */
private static void loadConfig() throws FileNotFoundException, IOException {
    try (InputStream configStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(CONFIG_FILE)) {
        if (configStream == null) {
            throw new FileNotFoundException();
        }

        properties = new Properties();
        properties.load(configStream);
    }

    // Read properties
    accountId = properties.getProperty("customerAccountId");
    createS3Bucket = Boolean.valueOf(properties.getProperty("createS3Bucket"));
    s3RegionName = properties.getProperty("s3RegionName");
    s3BucketName = properties.getProperty("s3BucketName").trim();
    s3BucketARN = getBucketARN(s3BucketName);
    s3ObjectPrefix = properties.getProperty("s3ObjectPrefix").trim();

    String sizeInMBsProperty = properties.getProperty("destinationSizeInMBs");
    s3DestinationSizeInMBs = StringUtils.isNullOrEmpty(sizeInMBsProperty) ? null
            : Integer.parseInt(sizeInMBsProperty.trim());
    String intervalInSecondsProperty = properties.getProperty("destinationIntervalInSeconds");
    s3DestinationIntervalInSeconds = StringUtils.isNullOrEmpty(intervalInSecondsProperty) ? null
            : Integer.parseInt(intervalInSecondsProperty.trim());

    clusterJDBCUrl = properties.getProperty("clusterJDBCUrl");
    username = properties.getProperty("username");
    password = properties.getProperty("password");
    dataTableName = properties.getProperty("dataTableName");
    copyOptions = properties.getProperty("copyOptions");

    deliveryStreamName = properties.getProperty("deliveryStreamName");
    firehoseRegion = properties.getProperty("firehoseRegion");
    iamRoleName = properties.getProperty("iamRoleName");
    iamRegion = properties.getProperty("iamRegion");

    // Update Delivery Stream Destination related properties
    enableUpdateDestination = Boolean.valueOf(properties.getProperty("updateDestination"));
    updatedCopyOptions = properties.getProperty("updatedCopyOptions");
}

From source file:control.services.DownloadPortraitsHttpServiceImpl.java

@Override
public File downloadPortraisFile(String portraitsFileName, String portraitsFolderName)
        throws FileNotFoundException {
    File file = null;//from   w  w  w .  ja  v a2  s  .  c  o m
    try {
        URL website = new URL(PROTOCOL_HOST + CLASH_HOST + PORTRAITS_PATH + portraitsFileName);
        //https://www.colorado.edu/conflict/peace/download/peace.zip
        // speedtest.ftp.otenet.gr/files/test10Mb.db
        //  URL website = new URL("https://www.colorado.edu/conflict/peace/download/peace.zip");
        file = new File(portraitsFolderName + File.separator + portraitsFileName);
        ReadableByteChannel rbc = Channels.newChannel(website.openStream());

        FileOutputStream fos = new FileOutputStream(file);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();

    } catch (IOException ex) {
        LOG.error(ex);
        throw new FileNotFoundException();
    }
    return file;
}

From source file:AmazonKinesisFirehoseToS3Sample.java

/**
 * Load the input parameters from properties file.
 *
 * @throws FileNotFoundException/*  w ww.  ja  v  a  2s  .  c  o  m*/
 * @throws IOException
 */
private static void loadConfig() throws FileNotFoundException, IOException {
    try (InputStream configStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(CONFIG_FILE)) {
        if (configStream == null) {
            throw new FileNotFoundException();
        }

        properties = new Properties();
        properties.load(configStream);
    }

    // Read properties
    accountId = properties.getProperty("customerAccountId");
    createS3Bucket = Boolean.valueOf(properties.getProperty("createS3Bucket"));
    s3RegionName = properties.getProperty("s3RegionName");
    s3BucketName = properties.getProperty("s3BucketName").trim();
    s3BucketARN = getBucketARN(s3BucketName);
    s3ObjectPrefix = properties.getProperty("s3ObjectPrefix").trim();

    String sizeInMBsProperty = properties.getProperty("destinationSizeInMBs");
    s3DestinationSizeInMBs = StringUtils.isNullOrEmpty(sizeInMBsProperty) ? null
            : Integer.parseInt(sizeInMBsProperty.trim());
    String intervalInSecondsProperty = properties.getProperty("destinationIntervalInSeconds");
    s3DestinationIntervalInSeconds = StringUtils.isNullOrEmpty(intervalInSecondsProperty) ? null
            : Integer.parseInt(intervalInSecondsProperty.trim());

    deliveryStreamName = properties.getProperty("deliveryStreamName");
    s3DestinationAWSKMSKeyId = properties.getProperty("destinationAWSKMSKeyId");
    firehoseRegion = properties.getProperty("firehoseRegion");
    iamRoleName = properties.getProperty("iamRoleName");
    iamRegion = properties.getProperty("iamRegion");

    // Update Delivery Stream Destination related properties
    enableUpdateDestination = Boolean.valueOf(properties.getProperty("updateDestination"));
    updateS3ObjectPrefix = properties.getProperty("updateS3ObjectPrefix").trim();
    String updateSizeInMBsProperty = properties.getProperty("updateSizeInMBs");
    updateSizeInMBs = StringUtils.isNullOrEmpty(updateSizeInMBsProperty) ? null
            : Integer.parseInt(updateSizeInMBsProperty.trim());
    String updateIntervalInSecondsProperty = properties.getProperty("updateIntervalInSeconds");
    updateIntervalInSeconds = StringUtils.isNullOrEmpty(updateIntervalInSecondsProperty) ? null
            : Integer.parseInt(updateIntervalInSecondsProperty.trim());
}