Example usage for java.io File exists

List of usage examples for java.io File exists

Introduction

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

Prototype

public boolean exists() 

Source Link

Document

Tests whether the file or directory denoted by this abstract pathname exists.

Usage

From source file:localhost.potlatchserver.AutoGrading.java

public static void main(String[] args) throws Exception {

    // Ensure that this application is run within the correct working directory
    File f = new File("./src/main/java/localhost/potlatchserver/Application.java");
    if (!f.exists()) {
        System.out.println(WordUtils.wrap("You must run the AutoGrading application from the root of the "
                + "project directory containing src/main/java. If you right-click->Run As->Java Application "
                + "in Eclipse, it will automatically use the correct classpath and working directory "
                + "(assuming that you have Gradle and the project setup correctly).", 80));
        System.exit(1);// w  w w  . j a v a 2 s . c  o m
    }

    // Ensure that the server is running and accessible on port 8443
    try {
        HttpClient client = UnsafeHttpsClient.createUnsafeClient();
        HttpResponse response = client.execute(new HttpHost("127.0.0.1", 8443),
                new BasicHttpRequest("GET", "/"));

        response.getStatusLine();
    } catch (NoHttpResponseException e) {
        // The server may have returned some JSON object
    } catch (Exception e) {
        System.out.println(WordUtils.wrap(
                "Unable to connect to your server on https://localhost:8443. Are you sure the server is running? "
                        + "In order to run the autograder, you must first launch your application "
                        + "by right-clicking on the Application class in Eclipse, and"
                        + "choosing Run As->Java Application. If you have already done this, make sure that"
                        + " you can access your server by opening the https://localhost:8443 url in a browser. "
                        + "If you can't access the server in a browser, it probably indicates you have a firewall "
                        + "or some other issue that is blocking access to port 8080 on localhost.",
                80));
        System.exit(1);
    }

    HandinUtil.generateHandinPackage("Asgn2", new File("./"), InternalAutoGradingTest.class);
}

From source file:org.craftercms.search.util.SearchIndexUpdater.java

public static void main(String... args) throws IOException {
    OptionParser parser = new OptionParser();
    parser.accepts("h", "prints the help");
    parser.accepts("s", "the Crafter site name").withRequiredArg();
    parser.accepts("u", "the Crafter Search server URL").withRequiredArg();
    parser.accepts("p", "the Crafter site path").withRequiredArg();

    OptionSet options = parser.parse(args);

    if (options.has("h")) {
        parser.printHelpOn(System.out);
    } else {/*w  ww . j  av a2s . co m*/
        checkForRequiredOption(options, "s");
        checkForRequiredOption(options, "u");
        checkForRequiredOption(options, "p");

        RestClientSearchService searchService = new RestClientSearchService();
        searchService.setServerUrl(options.valueOf("u").toString());

        String sitePath = options.valueOf("p").toString();
        File siteRoot = new File(sitePath);

        if (!siteRoot.exists()) {
            throw new IllegalArgumentException(
                    "The specified document's path [" + sitePath + "] doesn't exist");
        }
        if (!siteRoot.isDirectory()) {
            throw new IllegalArgumentException(
                    "The specified document's path [" + sitePath + "] is not a " + "directory");
        }

        SearchIndexUpdater searchIndexUpdater = new SearchIndexUpdater();
        searchIndexUpdater.setSiteName(options.valueOf("s").toString());
        searchIndexUpdater.setSiteRoot(siteRoot);
        searchIndexUpdater.setSearchService(searchService);

        searchIndexUpdater.updateIndex();
    }
}

From source file:de.alpharogroup.scheduler.system.ApplicationJettyRunner.java

/**
 * The main method starts a jetty server with the rest services for the resource-bundle-data.
 *
 * @param args//from ww  w  .  j  a va  2 s  . c  o m
 *            the arguments
 * @throws Exception
 *             the exception
 */
public static void main(final String[] args) throws Exception {
    final int sessionTimeout = 1800;// set timeout to 30min(60sec * 30min=1800sec)...
    final String projectname = getProjectName();
    final File projectDirectory = PathFinder.getProjectDirectory();
    final File webapp = PathFinder.getRelativePath(projectDirectory, projectname, "src", "main", "webapp");

    final String filterPath = "/*";

    final File logfile = new File(projectDirectory, "application.log");
    if (logfile.exists()) {
        try {
            DeleteFileExtensions.delete(logfile);
        } catch (final IOException e) {
            Logger.getRootLogger().error("logfile could not deleted.", e);
        }
    }
    // Add a file appender to the logger programatically
    LoggerExtensions.addFileAppender(Logger.getRootLogger(),
            LoggerExtensions.newFileAppender(logfile.getAbsolutePath()));

    final ServletContextHandler servletContextHandler = ServletContextHandlerFactory
            .getNewServletContextHandler(ServletContextHandlerConfiguration.builder()
                    .servletHolderConfiguration(ServletHolderConfiguration.builder()
                            .servletClass(CXFServlet.class).pathSpec(filterPath).build())
                    .contextPath("/").webapp(webapp).maxInactiveInterval(sessionTimeout).filterPath(filterPath)
                    .initParameter("contextConfigLocation", "classpath:application-context.xml").build());
    servletContextHandler.addEventListener(new ContextLoaderListener());
    final Jetty9RunConfiguration configuration = Jetty9RunConfiguration.builder()
            .servletContextHandler(servletContextHandler).httpPort(8080).httpsPort(8443).build();
    final Server server = new Server();
    Jetty9Runner.runServletContextHandler(server, configuration);

}

From source file:org.magnum.mobilecloud.video.AutoGrading.java

public static void main(String[] args) throws Exception {

    // Ensure that this application is run within the correct working directory
    File f = new File("./src/main/java/org/magnum/mobilecloud/video/Application.java");
    if (!f.exists()) {
        System.out.println(WordUtils.wrap("You must run the AutoGrading application from the root of the "
                + "project directory containing src/main/java. If you right-click->Run As->Java Application "
                + "in Eclipse, it will automatically use the correct classpath and working directory "
                + "(assuming that you have Gradle and the project setup correctly).", 80));
        System.exit(1);/*from   w  w w . j a va 2  s  . co m*/
    }

    // Ensure that the server is running and accessible on port 8443
    try {
        HttpClient client = UnsafeHttpsClient.createUnsafeClient();
        HttpResponse response = client.execute(new HttpHost("127.0.0.1", 8443),
                new BasicHttpRequest("GET", "/"));

        response.getStatusLine();
    } catch (NoHttpResponseException e) {
        // The server may have returned some JSON object
    } catch (Exception e) {
        System.out.println(WordUtils.wrap(
                "Unable to connect to your server on https://localhost:8443. Are you sure the server is running? "
                        + "In order to run the autograder, you must first launch your application "
                        + "by right-clicking on the Application class in Eclipse, and"
                        + "choosing Run As->Java Application. If you have already done this, make sure that"
                        + " you can access your server by opening the https://localhost:8443 url in a browser. "
                        + "If you can't access the server in a browser, it probably indicates you have a firewall "
                        + "or some other issue that is blocking access to port 8080 on localhost.",
                80));
        System.exit(1);
    }

    HandinUtil.generateHandinPackage("Asgn2", new File("./"), InternalAutoGradingTest.class);
}

From source file:com.github.thesmartenergy.sparql.generate.generator.CMDGenerator.java

public static void main(String[] args) {

    List<String> formats = Arrays.asList("TTL", "TURTLE", "NTRIPLES", "TRIG", "RDFXML", "JSONLD");

    try {/* w ww  . ja v  a  2s.  com*/
        CommandLine cl = CMDConfigurations.parseArguments(args);

        String query = "";
        String outputFormat = "TTL";

        if (cl.getArgList().size() == 0) {
            CMDConfigurations.displayHelp();
            return;
        }

        fileManager = FileManager.makeGlobal();
        if (cl.hasOption('l')) {
            Enumeration<String> loggers = LogManager.getLogManager().getLoggerNames();
            while (loggers.hasMoreElements()) {
                java.util.logging.Logger element = LogManager.getLogManager().getLogger(loggers.nextElement());
                element.setLevel(Level.OFF);
            }
            Logger.getRootLogger().setLevel(org.apache.log4j.Level.OFF);

        }
        LOG = Logger.getLogger(CMDGenerator.class);

        //get query file path
        //check if the file exists
        if (cl.hasOption("qf")) {
            String file_path = cl.getOptionValue("qf");
            File f = new File(file_path);
            if (f.exists() && !f.isDirectory()) {
                FileInputStream fisTargetFile = new FileInputStream(f);
                query = IOUtils.toString(fisTargetFile, "UTF-8");
                LOG.debug("\n\nRead SPARQL-Generate Query ..\n" + query + "\n\n");
            } else {
                LOG.error("File " + file_path + " not found.");
            }
        }

        //get query string
        if (cl.hasOption("qs")) {
            query = cl.getOptionValue("qs");
        }
        System.out.println("Query:" + query);

        //get and validate the output format
        if (cl.hasOption("f")) {
            String format = cl.getOptionValue("f");
            if (formats.contains(format)) {
                outputFormat = format;
            } else {
                LOG.error("Invalid output format," + cl.getOptionProperties("f").getProperty("description"));
                return;
            }
        }

        Model configurationModel = null;
        String conf = "";
        if (cl.hasOption("c")) {
            conf = cl.getOptionValue("c");
            configurationModel = ProcessQuery.generateConfiguration(conf);
        }

        String output = ProcessQuery.process(query, conf, outputFormat);
        System.out.println(output);

    } catch (org.apache.commons.cli.ParseException ex) {
        LOG.error(ex);
    } catch (FileNotFoundException ex) {
        LOG.error(ex);
    } catch (IOException ex) {
        LOG.error(ex);
    }

}

From source file:de.alpharogroup.message.system.ApplicationJettyRunner.java

/**
 * The main method starts a jetty server with the rest services for the resource-bundle-data.
 *
 * @param args/*from   ww  w  . j a  v a 2 s.  c  o  m*/
 *            the arguments
 * @throws Exception
 *             the exception
 */
public static void main(final String[] args) throws Exception {
    final int sessionTimeout = 1800;// set timeout to 30min(60sec *
    // 30min=1800sec)...
    final String projectname = getProjectName();
    final File projectDirectory = PathFinder.getProjectDirectory();
    final File webapp = PathFinder.getRelativePath(projectDirectory, projectname, "src", "main", "webapp");

    final String filterPath = "/*";

    final File logfile = new File(projectDirectory, "application.log");
    if (logfile.exists()) {
        try {
            DeleteFileExtensions.delete(logfile);
        } catch (final IOException e) {
            Logger.getRootLogger().error("logfile could not deleted.", e);
        }
    }
    // Add a file appender to the logger programatically
    LoggerExtensions.addFileAppender(Logger.getRootLogger(),
            LoggerExtensions.newFileAppender(logfile.getAbsolutePath()));

    final ServletContextHandler servletContextHandler = ServletContextHandlerFactory
            .getNewServletContextHandler(ServletContextHandlerConfiguration.builder()
                    .servletHolderConfiguration(ServletHolderConfiguration.builder()
                            .servletClass(CXFServlet.class).pathSpec(filterPath).build())
                    .contextPath("/").webapp(webapp).maxInactiveInterval(sessionTimeout).filterPath(filterPath)
                    .initParameter("contextConfigLocation", "classpath:application-context.xml").build());
    servletContextHandler.addEventListener(new ContextLoaderListener());
    final Jetty9RunConfiguration configuration = Jetty9RunConfiguration.builder()
            .servletContextHandler(servletContextHandler).httpPort(8080).httpsPort(8443).build();
    final Server server = new Server();
    Jetty9Runner.runServletContextHandler(server, configuration);

}

From source file:de.alpharogroup.phone.data.management.system.ApplicationJettyRunner.java

/**
 * The main method starts a jetty server with the rest services for the resource-bundle-data.
 *
 * @param args// w w w  .j a va  2  s  .  co m
 *            the arguments
 * @throws Exception
 *             the exception
 */
public static void main(final String[] args) throws Exception {
    final int sessionTimeout = 1800;// set timeout to 30min(60sec *
    // 30min=1800sec)...
    final String projectname = getProjectName();
    final File projectDirectory = PathFinder.getProjectDirectory();
    final File webapp = PathFinder.getRelativePath(projectDirectory, projectname, "src", "main", "webapp");

    final String filterPath = "/*";

    final File logfile = new File(projectDirectory, "application.log");
    if (logfile.exists()) {
        try {
            DeleteFileExtensions.delete(logfile);
        } catch (final IOException e) {
            Logger.getRootLogger().error("logfile could not deleted.", e);
        }
    }
    // Add a file appender to the logger programatically
    LoggerExtensions.addFileAppender(Logger.getRootLogger(),
            LoggerExtensions.newFileAppender(logfile.getAbsolutePath()));

    final ServletContextHandler servletContextHandler = ServletContextHandlerFactory
            .getNewServletContextHandler(ServletContextHandlerConfiguration.builder()
                    .servletHolderConfiguration(ServletHolderConfiguration.builder()
                            .servletClass(CXFServlet.class).pathSpec(filterPath).build())
                    .contextPath("/").webapp(webapp).maxInactiveInterval(sessionTimeout).filterPath(filterPath)
                    .initParameter("contextConfigLocation", "classpath:application-context.xml").build());
    servletContextHandler.addEventListener(new ContextLoaderListener());
    final Jetty9RunConfiguration configuration = Jetty9RunConfiguration.builder()
            .servletContextHandler(servletContextHandler).httpPort(11080).httpsPort(11443).build();
    final Server server = new Server();
    Jetty9Runner.runServletContextHandler(server, configuration);

}

From source file:cc.twittertools.util.ExtractSubcollection.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("source collection directory")
            .create(COLLECTION_OPTION));
    options.addOption(//from   www. j av  a2 s.  co  m
            OptionBuilder.withArgName("file").hasArg().withDescription("list of tweetids").create(ID_OPTION));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(COLLECTION_OPTION) || !cmdline.hasOption(ID_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ExtractSubcollection.class.getName(), options);
        System.exit(-1);
    }

    String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION);

    LongOpenHashSet tweetids = new LongOpenHashSet();
    File tweetidsFile = new File(cmdline.getOptionValue(ID_OPTION));
    if (!tweetidsFile.exists()) {
        System.err.println("Error: " + tweetidsFile + " does not exist!");
        System.exit(-1);
    }
    LOG.info("Reading tweetids from " + tweetidsFile);

    FileInputStream fin = new FileInputStream(tweetidsFile);
    BufferedReader br = new BufferedReader(new InputStreamReader(fin));

    String s;
    while ((s = br.readLine()) != null) {
        tweetids.add(Long.parseLong(s));
    }
    br.close();
    fin.close();
    LOG.info("Read " + tweetids.size() + " tweetids.");

    File file = new File(collectionPath);
    if (!file.exists()) {
        System.err.println("Error: " + file + " does not exist!");
        System.exit(-1);
    }

    PrintStream out = new PrintStream(System.out, true, "UTF-8");
    StatusStream stream = new JsonStatusCorpusReader(file);
    Status status;
    while ((status = stream.next()) != null) {
        if (tweetids.contains(status.getId())) {
            out.println(status.getJsonObject().toString());
        }
    }
    stream.close();
    out.close();
}

From source file:Blobs.java

public static void main(String args[]) {
    if (args.length != 1) {
        System.err.println("Syntax: <java Blobs [driver] [url] " + "[uid] [pass] [file]");
        return;/*w  w w  .  j a  v a2 s .  c  om*/
    }
    try {
        Class.forName(args[0]).newInstance();
        Connection con = DriverManager.getConnection(args[1], args[2], args[3]);
        File f = new File(args[4]);
        PreparedStatement stmt;

        if (!f.exists()) {
            // if the file does not exist
            // retrieve it from the database and write it to the named file
            ResultSet rs;

            stmt = con.prepareStatement("SELECT blobData " + "FROM BlobTest " + "WHERE fileName = ?");

            stmt.setString(1, args[0]);
            rs = stmt.executeQuery();
            if (!rs.next()) {
                System.out.println("No such file stored.");
            } else {
                Blob b = rs.getBlob(1);
                BufferedOutputStream os;

                os = new BufferedOutputStream(new FileOutputStream(f));
                os.write(b.getBytes(0, (int) b.length()), 0, (int) b.length());
                os.flush();
                os.close();
            }
        } else {
            // otherwise read it and save it to the database
            FileInputStream fis = new FileInputStream(f);
            byte[] tmp = new byte[1024];
            byte[] data = null;
            int sz, len = 0;

            while ((sz = fis.read(tmp)) != -1) {
                if (data == null) {
                    len = sz;
                    data = tmp;
                } else {
                    byte[] narr;
                    int nlen;

                    nlen = len + sz;
                    narr = new byte[nlen];
                    System.arraycopy(data, 0, narr, 0, len);
                    System.arraycopy(tmp, 0, narr, len, sz);
                    data = narr;
                    len = nlen;
                }
            }
            if (len != data.length) {
                byte[] narr = new byte[len];

                System.arraycopy(data, 0, narr, 0, len);
                data = narr;
            }
            stmt = con.prepareStatement("INSERT INTO BlobTest(fileName, " + "blobData) VALUES(?, ?)");
            stmt.setString(1, args[0]);
            stmt.setObject(2, data);
            stmt.executeUpdate();
            f.delete();
        }
        con.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.FormFileUploaderClientApplication.java

/**
 * Run the program./*  w w w .j  a va 2 s  .co  m*/
 * 
 * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value.
 */
public static void main(String[] args) {
    // takes file path from first program's argument
    if (args.length < 1) {
        logger.error("****** Path to input file must be first argument to program! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    String filePath = args[0];
    File uploadFile = new File(filePath);
    if (!uploadFile.exists()) {
        logger.error("****** File does not exist at expected locations! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    if (args.length > 1) {
        serverUrl = args[1];
    }

    logger.info("File to upload: " + filePath);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(serverUrl);
        FileBody bin = new FileBody(uploadFile);
        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart(FORM_FIELD_DATAFILE, bin).build();
        httppost.setEntity(reqEntity);

        logger.info("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            logger.info("HTTP Response Status Line: " + response.getStatusLine());
            // Expecting a 200 Status Code
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                String reason = response.getStatusLine().getReasonPhrase();
                logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode()
                        + "] -- Reason (if available): " + reason);
            } else {
                HttpEntity resEntity = response.getEntity();
                InputStream is = resEntity.getContent();
                BufferedReader in = new BufferedReader(new InputStreamReader(is));

                String output;
                StringBuilder sb = new StringBuilder("Response data received:");
                while ((output = in.readLine()) != null) {
                    sb.append(System.getProperty("line.separator"));
                    sb.append(output);
                }
                logger.info(sb.toString());
                in.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        logger.error("Caught exception: " + e.getMessage(), e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            logger.warn("Exception closing HTTP client: " + e.getMessage(), e);
        }
        logger.info("DONE");
    }
}