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(String s) 

Source Link

Document

Constructs a FileNotFoundException with the specified detail message.

Usage

From source file:architecture.common.xml.XmlProperties.java

/**
 * Creates a new XMLPropertiesTest object.
 *
 * @param file/*from  ww  w .  j a  v a 2  s  . c o  m*/
 *            the file that properties should be read from and written to.
 * @throws IOException
 *             if an error occurs loading the properties.
 */
public XmlProperties(File file) throws IOException {
    this.file = file;
    if (!file.exists()) {
        // Attempt to recover from this error case by seeing if the
        // tmp file exists. It's possible that the rename of the
        // tmp file failed the last time Jive was running,
        // but that it exists now.
        File tempFile;
        tempFile = new File(file.getParentFile(), file.getName() + ".tmp");
        if (tempFile.exists()) {
            log.error(L10NUtils.format("002157", file.getName()));
            tempFile.renameTo(file);
        }
        // There isn't a possible way to recover from the file not
        // being there, so throw an error.
        else {
            throw new FileNotFoundException(L10NUtils.format("002151", file.getName()));
        }
    }
    // Check read and write privs.
    if (!file.canRead()) {
        throw new IOException(L10NUtils.format("002152", file.getName()));
    }
    if (!file.canWrite()) {
        throw new IOException(L10NUtils.format("002153", file.getName()));
    }

    Reader reader = null;
    try {
        reader = new InputStreamReader(new FileInputStream(file), ApplicationConstants.DEFAULT_CHAR_ENCODING);
        buildDoc(reader);
    } catch (Exception e) {
        log.error(L10NUtils.format("002154", file.getName(), e.getMessage()));
        throw new IOException(e.getMessage());
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
            log.debug(e.getMessage(), e);
        }
    }

    // FileReader reader = new FileReader(file);
    // buildDoc(reader);
}

From source file:jp.tricreo.codegenerator.Application.java

private boolean parseCommandLine(String[] args) throws ParseException, FileNotFoundException {
    Options options = new Options();
    options.addOption("h", "help", false, "help");
    options.addOption("c", "config", true, "config.properties {.properties, .json}");
    options.addOption("o", "output-dir", true, "output dir");
    options.addOption("t", "template-dir", true, "template file dir");
    options.addOption("e", "template-engine", true, "template engine {F = freemarker, V = velocity}");

    CommandLine cl = createCommandLine(options, args);
    if (cl.hasOption('h')) {
        new HelpFormatter().printHelp("help tips", options);
        return false;
    }/*from   ww  w  . j a  va  2s  .  co m*/
    if (cl.hasOption("c")) {
        configFile = new File(cl.getOptionValue("c"));
    }
    if (cl.hasOption("o")) {
        exportDir = new File(cl.getOptionValue("o"));
    }
    if (cl.hasOption("t")) {
        templateDir = new File(cl.getOptionValue("t"));
    }
    if (cl.hasOption("e")) {
        if (cl.getOptionValue("e").equals("F")) {
            templateEngineType = TemplateEngineType.FREE_MAKER;
        } else if (cl.getOptionValue("e").equals("V")) {
            templateEngineType = TemplateEngineType.VELOCITY;
        }
    }
    if (!configFile.exists()) {
        throw new FileNotFoundException(configFile + "is not found.");
    }

    LOGGER.info(" = {}", configFile);
    LOGGER.info(" : {}", templateDir);
    LOGGER.info(" : {}", exportDir);
    LOGGER.info("? : {}", templateEngineType);

    return true;
}

From source file:org.jboss.windup.WindupEngine.java

/**
 * <p>//from w  ww. ja v  a2 s  .co m
 * Process a single file.
 * </p>
 * 
 * @param filePath
 * @throws IOException
 */
public FileMetadata processFile(File file) throws IOException {
    Validate.notNull(file, "File is required, but provided as null.");

    if (!settings.isSource()) {
        throw new RuntimeException("Windup Engine must be set to source mode to process single files.");
    }

    if (!file.exists()) {
        throw new FileNotFoundException("file does not exist: " + file);
    }

    if (!file.isFile()) {
        throw new FileNotFoundException("given file path does not reference a file: " + file.getAbsolutePath());
    }

    return fileInterrogationEngine.process(file);
}

From source file:com.braffdev.server.core.container.resourceloader.ResourceLoader.java

/**
 * Loads the file denoted by the given path from the hard drive.
 *
 * @param path the path to laod./* ww w.j  a  v a 2  s  .c  o  m*/
 * @return an InputStream pointing to the file to load.
 * @throws FileNotFoundException if the file cannot be found.
 */
private InputStream loadFromDisk(String path) throws FileNotFoundException {
    if (!path.startsWith(Constants.File.DIR_CONTAINER_WEB)) {
        path = Constants.File.DIR_CONTAINER_WEB + path;
    }

    // load from disk
    File requestedFile = new File(this.root, path);
    if (!requestedFile.exists()) {
        throw new FileNotFoundException(path);

    } else {
        // file exists - add to cace
        byte[] content = IOUtils.readFully(new BufferedInputStream(new FileInputStream(requestedFile)));
        this.cache.put(path, content);
    }

    ResourceInputStream in = new ResourceInputStream(new FileInputStream(requestedFile), this);
    this.addStream(in);

    return in;
}

From source file:io.apiman.tools.ldap.ApimanLdapServer.java

public static void injectLdifFiles(String... ldifFiles) throws Exception {
    if (ldifFiles != null && ldifFiles.length > 0) {
        for (String ldifFile : ldifFiles) {
            InputStream is = null;
            try {
                is = ApimanLdapServer.class.getClassLoader().getResourceAsStream(ldifFile);
                if (is == null) {
                    throw new FileNotFoundException("LDIF file '" + ldifFile + "' not found.");
                } else {
                    try {
                        LdifReader ldifReader = new LdifReader(is);
                        for (LdifEntry entry : ldifReader) {
                            injectEntry(entry);
                        }/*  ww  w  . ja v a  2  s.c o m*/
                        ldifReader.close();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
    }
}

From source file:io.wcm.caravan.commons.httpclient.impl.helpers.CertificateLoader.java

/**
 * Build TrustManagerFactory.//from w w w  .  j a v  a2  s  . co  m
 * @param trustStoreFilename Truststore file name
 * @param storeProperties store properties
 * @return TrustManagerFactory
 * @throws IOException
 * @throws GeneralSecurityException
 */
public static TrustManagerFactory getTrustManagerFactory(String trustStoreFilename,
        StoreProperties storeProperties) throws IOException, GeneralSecurityException {
    InputStream is = getResourceAsStream(trustStoreFilename);
    if (is == null) {
        throw new FileNotFoundException("Certificate file not found: " + getFilenameInfo(trustStoreFilename));
    }
    try {
        return getTrustManagerFactory(is, storeProperties);
    } finally {
        try {
            is.close();
        } catch (IOException ex) {
            // ignore
        }
    }
}

From source file:com.chiorichan.factory.FileInterpreter.java

public final void interpretParamsFromFile(File file) throws IOException {
    if (file == null)
        throw new FileNotFoundException("File path was null");

    FileInputStream is = null;//from   w  w  w.j a v a2 s  .  c  o  m
    try {
        cachedFile = file;

        annotations.put("file", file.getAbsolutePath());

        if (file.isDirectory())
            annotations.put("shell", "embedded");
        else {
            if (!annotations.containsKey("shell") || annotations.get("shell") == null) {
                String shell = determineShellFromName(file.getName());
                if (shell != null && !shell.isEmpty())
                    annotations.put("shell", shell);
            }

            is = new FileInputStream(file);

            ByteBuf buf = Unpooled.wrappedBuffer(IOUtils.toByteArray(is));
            boolean beginContent = false;
            int lastInx;
            int lineCnt = 0;

            data = Unpooled.buffer();

            do {
                lastInx = buf.readerIndex();
                String l = readLine(buf);
                if (l == null)
                    break;

                if (l.trim().startsWith("@"))
                    try {
                        lineCnt++;

                        /* Only solution I could think of for CSS files since they use @annotations too, so we share them. */
                        if (ContentTypes.getContentType(file).equalsIgnoreCase("text/css"))
                            data.writeBytes((l + "\n").getBytes());
                        /* Only solution I could think of for CSS files since they use @annotations too, so we share them. */

                        String key;
                        String val = "";

                        if (l.contains(" ")) {
                            key = l.trim().substring(1, l.trim().indexOf(" "));
                            val = l.trim().substring(l.trim().indexOf(" ") + 1);
                        } else
                            key = l;

                        if (val.endsWith(";"))
                            val = val.substring(0, val.length() - 1);

                        if (val.startsWith("'") && val.endsWith("'"))
                            val = val.substring(1, val.length() - 1);

                        annotations.put(key.toLowerCase(), val);
                        Log.get().finer("Setting param '" + key + "' to '" + val + "'");

                        if (key.equals("encoding"))
                            if (Charset.isSupported(val))
                                setEncoding(Charsets.toCharset(val));
                            else
                                Log.get()
                                        .severe("The file '" + file.getAbsolutePath() + "' requested encoding '"
                                                + val + "' but it's not supported by the JVM!");
                    } catch (NullPointerException | ArrayIndexOutOfBoundsException e) {

                    }
                else if (l.trim().isEmpty())
                    lineCnt++;
                // Continue reading, this line is empty.
                else {
                    // We encountered the beginning of the file content.
                    beginContent = true;
                    buf.readerIndex(lastInx); // This rewinds the buffer to the last reader index
                }
            } while (!beginContent);

            data.writeBytes(Strings.repeat('\n', lineCnt).getBytes());

            data.writeBytes(buf);
        }
    } finally {
        if (is != null)
            is.close();
    }
}

From source file:eu.stratosphere.nephele.jobmanager.web.WebInfoServer.java

/**
 * Creates a new web info server. The server runs the servlets that implement the logic
 * to list all present information concerning the job manager 
 * /*from   ww  w .  j  ava  2  s  .co m*/
 * @param nepheleConfig
 *        The configuration for the nephele job manager. 
 * @param port
 *        The port to launch the server on.
 * @throws IOException
 *         Thrown, if the server setup failed for an I/O related reason.
 */
public WebInfoServer(Configuration nepheleConfig, int port, JobManager jobmanager) throws IOException {
    this.port = port;

    // if no explicit configuration is given, use the global configuration
    if (nepheleConfig == null) {
        nepheleConfig = GlobalConfiguration.getConfiguration();
    }

    // get base path of Stratosphere installation
    String basePath = nepheleConfig.getString(ConfigConstants.STRATOSPHERE_BASE_DIR_PATH_KEY, "");
    String webDirPath = nepheleConfig.getString(ConfigConstants.JOB_MANAGER_WEB_ROOT_PATH_KEY,
            ConfigConstants.DEFAULT_JOB_MANAGER_WEB_ROOT_PATH);
    String logDirPath = nepheleConfig.getString(ConfigConstants.JOB_MANAGER_WEB_LOG_PATH_KEY,
            basePath + "/log");

    File webDir;
    if (webDirPath.startsWith("/")) {
        // absolute path
        webDir = new File(webDirPath);
    } else {
        // path relative to base dir
        webDir = new File(basePath + "/" + webDirPath);
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("Setting up web info server, using web-root directory '" + webDir.getAbsolutePath() + "'.");
        //LOG.info("Web info server will store temporary files in '" + tmpDir.getAbsolutePath());

        LOG.info("Web info server will display information about nephele job-manager on "
                + nepheleConfig.getString(ConfigConstants.JOB_MANAGER_IPC_ADDRESS_KEY, null) + ", port " + port
                + ".");
    }

    // ensure that the directory with the web documents exists
    if (!webDir.exists()) {
        throw new FileNotFoundException(
                "Cannot start jobmanager web info server. The directory containing the web documents does not exist: "
                        + webDir.getAbsolutePath());
    }

    server = new Server(port);

    // ----- the handlers for the servlets -----
    ServletContextHandler servletContext = new ServletContextHandler(ServletContextHandler.SESSIONS);
    servletContext.setContextPath("/");
    servletContext.addServlet(new ServletHolder(new JobmanagerInfoServlet(jobmanager)), "/jobsInfo");
    servletContext.addServlet(new ServletHolder(new LogfileInfoServlet(new File(logDirPath))), "/logInfo");

    // ----- the handler serving all the static files -----
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(false);
    resourceHandler.setResourceBase(webDir.getAbsolutePath());

    // ----- add the handlers to the list handler -----
    HandlerList handlers = new HandlerList();
    handlers.addHandler(servletContext);
    handlers.addHandler(resourceHandler);

    // ----- create the login module with http authentication -----

    File af = null;
    String authFile = nepheleConfig.getString(ConfigConstants.JOB_MANAGER_WEB_ACCESS_FILE_KEY, null);
    if (authFile != null) {
        af = new File(authFile);
        if (!af.exists()) {
            LOG.error("The specified file '" + af.getAbsolutePath()
                    + "' with the authentication information is missing. Starting server without HTTP authentication.");
            af = null;
        }
    }
    if (af != null) {
        HashLoginService loginService = new HashLoginService("Stratosphere Jobmanager Interface", authFile);
        server.addBean(loginService);

        Constraint constraint = new Constraint();
        constraint.setName(Constraint.__BASIC_AUTH);
        constraint.setAuthenticate(true);
        constraint.setRoles(new String[] { "user" });

        ConstraintMapping mapping = new ConstraintMapping();
        mapping.setPathSpec("/*");
        mapping.setConstraint(constraint);

        ConstraintSecurityHandler sh = new ConstraintSecurityHandler();
        sh.addConstraintMapping(mapping);
        sh.setAuthenticator(new BasicAuthenticator());
        sh.setLoginService(loginService);
        sh.setStrict(true);

        // set the handers: the server hands the request to the security handler,
        // which hands the request to the other handlers when authenticated
        sh.setHandler(handlers);
        server.setHandler(sh);
    } else {
        server.setHandler(handlers);
    }
}

From source file:com.fluidops.iwb.deepzoom.DZConvert.java

/**
 * @param args the command line arguments
 *///w ww . j av a  2  s.c  o  m
public static void main2(String[] args) {

    try {
        try {
            parseCommandLine(args);
            if (outputDir == null)
                outputDir = new File(".");
            if (debugMode) {
                System.out.printf("tileSize=%d ", tileSize);
                System.out.printf("tileOverlap=%d ", tileOverlap);
                System.out.printf("outputDir=%s%n", outputDir.getPath());
            }

        } catch (Exception e) {
            System.out.println("Invalid command line: " + e.getMessage());
            return;
        }

        if (!outputDir.exists())
            throw new FileNotFoundException("Output directory does not exist: " + outputDir.getPath());
        if (!outputDir.isDirectory())
            throw new FileNotFoundException("Output directory is not a directory: " + outputDir.getPath());

        Iterator<File> itr = inputFiles.iterator();
        while (itr.hasNext())
            processImageFile(itr.next(), outputDir);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:it.reexon.lib.files.FileUtils.java

/**
 * Utility method for copying file //w ww .jav a 2 s  .co m
 *  
 * @param srcFile - source file 
 * @param destFile - destination file 
 * @author A. Weinberger
 * 
 * @throws IOException              If the first byte cannot be read for any reason other than the end of the file, if the input stream has been closed, or if some other I/O error occurs.
 * @throws IllegalArgumentException If file are null
 * @throws FileNotFoundException    If srcFile doens't exist
 */
public static void copyFile(File srcFile, File destFile) throws IOException {
    if (srcFile == null || destFile == null)
        throw new IllegalArgumentException("Files cannot be null");
    if (!srcFile.exists())
        throw new FileNotFoundException("Start file must be exists");

    try (final InputStream in = new FileInputStream(srcFile);
            final OutputStream out = new FileOutputStream(destFile);) {
        long millis = System.currentTimeMillis();
        CRC32 checksum;
        if (VERIFY) {
            checksum = new CRC32();
            checksum.reset();
        }
        final byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = in.read(buffer);
        while (bytesRead >= 0) {
            if (VERIFY) {
                checksum.update(buffer, 0, bytesRead);
            }
            out.write(buffer, 0, bytesRead);
            bytesRead = in.read(buffer);
        }
        if (CLOCK) {
            millis = System.currentTimeMillis() - millis;
            if (LOGS)
                System.out.println("Copy file '" + srcFile.getPath() + "' on " + millis / 1000L + " second(s)");
        }
    } catch (IOException e) {
        throw e;
    }
}