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:com.joseflavio.unhadegato.Concentrador.java

/**
 * @param args [0] = Diretrio de configuraes.
 *//*from   w  ww . ja va2s.com*/
public static void main(String[] args) {

    log.info(Util.getMensagem("unhadegato.iniciando"));

    try {

        /***********************/

        if (args.length > 0) {
            if (!args[0].isEmpty()) {
                configuracao = new File(args[0]);
                if (!configuracao.isDirectory()) {
                    String msg = Util.getMensagem("unhadegato.diretorio.incorreto");
                    System.out.println(msg);
                    log.error(msg);
                    System.exit(1);
                }
            }
        }

        if (configuracao == null) {
            configuracao = new File(System.getProperty("user.home") + File.separator + "unhadegato");
            configuracao.mkdirs();
        }

        log.info(Util.getMensagem("unhadegato.diretorio.endereco", configuracao.getAbsolutePath()));

        /***********************/

        File confGeralArq = new File(configuracao, "unhadegato.conf");

        if (!confGeralArq.exists()) {
            try (InputStream is = Concentrador.class.getResourceAsStream("/unhadegato.conf");
                    OutputStream os = new FileOutputStream(confGeralArq);) {
                IOUtils.copy(is, os);
            }
        }

        Properties confGeral = new Properties();

        try (FileInputStream fis = new FileInputStream(confGeralArq)) {
            confGeral.load(fis);
        }

        String prop_porta = confGeral.getProperty("porta");
        String prop_porta_segura = confGeral.getProperty("porta.segura");
        String prop_seg_pri = confGeral.getProperty("seguranca.privada");
        String prop_seg_pri_senha = confGeral.getProperty("seguranca.privada.senha");
        String prop_seg_pri_tipo = confGeral.getProperty("seguranca.privada.tipo");
        String prop_seg_pub = confGeral.getProperty("seguranca.publica");
        String prop_seg_pub_senha = confGeral.getProperty("seguranca.publica.senha");
        String prop_seg_pub_tipo = confGeral.getProperty("seguranca.publica.tipo");

        if (StringUtil.tamanho(prop_porta) == 0)
            prop_porta = "8885";
        if (StringUtil.tamanho(prop_porta_segura) == 0)
            prop_porta_segura = "8886";
        if (StringUtil.tamanho(prop_seg_pri) == 0)
            prop_seg_pri = "servidor.jks";
        if (StringUtil.tamanho(prop_seg_pri_senha) == 0)
            prop_seg_pri_senha = "123456";
        if (StringUtil.tamanho(prop_seg_pri_tipo) == 0)
            prop_seg_pri_tipo = "JKS";
        if (StringUtil.tamanho(prop_seg_pub) == 0)
            prop_seg_pub = "cliente.jks";
        if (StringUtil.tamanho(prop_seg_pub_senha) == 0)
            prop_seg_pub_senha = "123456";
        if (StringUtil.tamanho(prop_seg_pub_tipo) == 0)
            prop_seg_pub_tipo = "JKS";

        /***********************/

        File seg_pri = new File(prop_seg_pri);
        if (!seg_pri.isAbsolute())
            seg_pri = new File(configuracao.getAbsolutePath() + File.separator + prop_seg_pri);

        if (seg_pri.exists()) {
            System.setProperty("javax.net.ssl.keyStore", seg_pri.getAbsolutePath());
            System.setProperty("javax.net.ssl.keyStorePassword", prop_seg_pri_senha);
            System.setProperty("javax.net.ssl.keyStoreType", prop_seg_pri_tipo);
        }

        File seg_pub = new File(prop_seg_pub);
        if (!seg_pub.isAbsolute())
            seg_pub = new File(configuracao.getAbsolutePath() + File.separator + prop_seg_pub);

        if (seg_pub.exists()) {
            System.setProperty("javax.net.ssl.trustStore", seg_pub.getAbsolutePath());
            System.setProperty("javax.net.ssl.trustStorePassword", prop_seg_pub_senha);
            System.setProperty("javax.net.ssl.trustStoreType", prop_seg_pub_tipo);
        }

        /***********************/

        new Thread() {

            File arquivo = new File(configuracao, "copaibas.conf");

            long ultimaData = -1;

            @Override
            public void run() {

                while (true) {

                    long data = arquivo.lastModified();

                    if (data > ultimaData) {
                        executarCopaibas(arquivo);
                        ultimaData = data;
                    }

                    try {
                        Thread.sleep(5 * 1000);
                    } catch (InterruptedException e) {
                        return;
                    }

                }

            }

        }.start();

        /***********************/

        log.info(Util.getMensagem("unhadegato.conexao.esperando"));

        log.info(Util.getMensagem("copaiba.porta.normal.abrindo", prop_porta));
        Portal portal1 = new Portal(new SocketServidor(Integer.parseInt(prop_porta), false, true));

        log.info(Util.getMensagem("copaiba.porta.segura.abrindo", prop_porta_segura));
        Portal portal2 = new Portal(new SocketServidor(Integer.parseInt(prop_porta_segura), true, true));

        portal1.start();
        portal2.start();

        portal1.join();

        /***********************/

    } catch (Exception e) {

        log.error(e.getMessage(), e);

    } finally {

        for (CopaibaGerenciador gerenciador : gerenciadores.values())
            gerenciador.encerrar();
        gerenciadores.clear();
        gerenciadores = null;

    }

}

From source file:com.appeligo.responsetest.ServerResponseChecker.java

/**
 * @param args/*from  ww  w.  ja  v  a 2 s .  c o  m*/
 */
public static void main(String[] args) {

    PatternLayout pattern = new PatternLayout("%d{ISO8601} %-5p [%-c{1} - %t] - %m%n");
    ConsoleAppender consoleAppender = new ConsoleAppender(pattern);
    LevelRangeFilter infoFilter = new LevelRangeFilter();
    infoFilter.setLevelMin(Level.INFO);
    consoleAppender.addFilter(infoFilter);
    BasicConfigurator.configure(consoleAppender);

    String configFile = "/etc/flip.tv/responsetest.xml";

    if (args.length > 0) {
        if (args.length == 2 && args[0].equals("-config")) {
            configFile = args[1];
        } else {
            log.error("Usage: java " + ServerResponseChecker.class.getName() + " [-config <xmlfile>]");
            System.exit(1);
        }
    }

    try {
        XMLConfiguration config = new XMLConfiguration(configFile);

        logFile = config.getString("logFile", logFile);
        servlet = config.getString("servlet", servlet);
        timeoutSeconds = config.getLong("timeoutSeconds", timeoutSeconds);
        responseTimeThresholdSeconds = config.getLong("responseTimeThresholdSeconds",
                responseTimeThresholdSeconds);
        reporter = config.getString("reporter", reporter);
        smtpServer = config.getString("smtpServer", smtpServer);
        smtpUsername = config.getString("smtpUsername", smtpUsername);
        smtpPassword = config.getString("smtpPassword", smtpPassword);
        smtpDebug = config.getBoolean("smtpDebug", smtpDebug);
        mailTo = config.getString("mailTo", mailTo);
    } catch (ConfigurationException e) {
        e.printStackTrace();
    }

    marker = logFile + ".mailed";

    try {
        BasicConfigurator.configure(new RollingFileAppender(pattern, logFile, true));
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    // Add email appender
    SMTPAppender mailme = new SMTPAppender();
    LevelRangeFilter warnFilter = new LevelRangeFilter();
    warnFilter.setLevelMin(Level.WARN);
    mailme.addFilter(warnFilter);
    mailme.setSMTPDebug(smtpDebug);
    mailme.setSMTPHost(smtpServer);
    mailme.setTo(mailTo);
    mailme.setFrom(reporter + " <" + smtpUsername + ">");
    mailme.setBufferSize(1);
    mailme.setSubject(servlet + " Not Responding!");
    mailme.setSMTPUsername(smtpUsername);
    mailme.setSMTPPassword(smtpPassword);
    mailme.setLayout(new SimpleLayout());
    mailme.activateOptions();
    mailme.setLayout(pattern);
    BasicConfigurator.configure(mailme);

    long before;
    ConnectionThread connectionThread = new ConnectionThread();
    connectionThread.start();
    synchronized (connectionThread) {
        connectionThread.setOkToGo(true);
        connectionThread.notifyAll();
        before = System.currentTimeMillis();
        long delay = timeoutSeconds * 1000;
        while (!done && delay > 0) {
            try {
                connectionThread.wait(delay);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            delay -= (System.currentTimeMillis() - before);
        }
    }
    long after = System.currentTimeMillis();
    responseMillis = after - before;
    String reportStatus = "Could not report";
    try {
        StringBuilder sb = new StringBuilder();
        sb.append(servlet + "/responsetest/report.action");
        sb.append("?reporter=" + URLEncoder.encode(reporter));
        sb.append("&status=" + URLEncoder.encode(status));
        sb.append("&bytesRead=" + bytesRead);
        sb.append("&timedOut=" + (!done));
        if (throwable == null) {
            sb.append("&exception=none");
        } else {
            sb.append("&exception="
                    + URLEncoder.encode(throwable.getClass().getName() + "-" + throwable.getMessage()));
        }
        sb.append("&responseMillis=" + responseMillis);
        URL reportURL = new URL(sb.toString());
        connection = (HttpURLConnection) reportURL.openConnection();
        connection.connect();
        reportStatus = connection.getResponseCode() + " - " + connection.getResponseMessage();
    } catch (Throwable t) {
        reportStatus = t.getClass().getName() + "-" + t.getMessage();
    }
    StringBuilder sb = new StringBuilder();
    sb.append(servlet + ": ");
    sb.append(status + ", " + bytesRead + " bytes, ");
    if (done) {
        sb.append("DONE, ");
    } else {
        sb.append("TIMED OUT, ");
    }
    sb.append(responseMillis + " millisecond response, ");
    sb.append(" report status=" + reportStatus);
    File markerFile = new File(marker);
    if (done && status.startsWith("200") && (throwable == null)) {
        if ((responseMillis / 1000) < responseTimeThresholdSeconds) {
            if (markerFile.exists()) {
                markerFile.delete();
            }
            log.debug(sb.toString());
        } else {
            if (markerFile.exists()) {
                log.info(sb.toString());
            } else {
                try {
                    new FileOutputStream(marker).close();
                    log.warn(sb.toString());
                } catch (IOException e) {
                    log.info(sb.toString());
                    log.info("Can't send email alert because could not write marker file: " + marker + ". "
                            + e.getMessage());
                }
            }
        }
    } else {
        if (throwable != null) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            throwable.printStackTrace(pw);
            sb.append(sw.toString());
        }
        if (markerFile.exists()) {
            log.info(sb.toString());
        } else {
            try {
                new FileOutputStream(marker).close();
                log.fatal(sb.toString()); // chosen appender layout ignoresThrowable()
            } catch (IOException e) {
                log.info(sb.toString());
                log.info("Can't send email alert because could not write marker file: " + marker + ". "
                        + e.getMessage());
            }
        }
    }
}

From source file:com.rackspacecloud.client.cloudfiles.sample.FilesCopy.java

public static void main(String args[]) throws NoSuchAlgorithmException, FilesException {
    //Build the command line options
    Options options = addCommandLineOptions();

    if (args.length <= 0)
        printHelp(options);/*w w  w.j ava2 s.c o m*/

    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help"))
            printHelp(options);

        if (line.hasOption("file") && line.hasOption("folder")) {
            System.err.println("Can not use both -file and -folder on the command line at the same time.");
            System.exit(-1);
        } //if (line.hasOption("file") && line.hasOption("folder"))

        if (line.hasOption("download")) {
            if (line.hasOption("folder")) {
                String localFolder = FilenameUtils.normalize(line.getOptionValue("folder"));
                String containerName = null;
                if (StringUtils.isNotBlank(localFolder)) {
                    File localFolderObj = new File(localFolder);
                    if (localFolderObj.exists() && localFolderObj.isDirectory()) {
                        if (line.hasOption("container")) {
                            containerName = line.getOptionValue("container");
                            if (!StringUtils.isNotBlank(containerName)) {
                                System.err.println(
                                        "You must provide a valid value for the  Container to upload to !");
                                System.exit(-1);
                            } //if (!StringUtils.isNotBlank(ontainerName))                            
                        } else {
                            System.err.println(
                                    "You must provide the -container for a copy operation to work as expected.");
                            System.exit(-1);
                        }

                        System.out.println("Downloading all objects from: " + containerName
                                + " to local folder: " + localFolder);

                        getContainerObjects(localFolderObj, containerName);

                    } else {
                        if (!localFolderObj.exists()) {
                            System.err.println("The local folder: " + localFolder
                                    + " does not exist.  Create it first and then run this command.");
                        }

                        if (!localFolderObj.isDirectory()) {
                            System.err.println(
                                    "The local folder name supplied : " + localFolder + " is not a folder !");
                        }

                        System.exit(-1);
                    }
                }
            }
            System.exit(0);
        } //if (line.hasOption("download"))

        if (line.hasOption("folder")) {
            String containerName = null;
            String folderPath = null;

            if (line.hasOption("container")) {
                containerName = line.getOptionValue("container");
                if (!StringUtils.isNotBlank(containerName)) {
                    System.err.println("You must provide a valid value for the  Container to upload to !");
                    System.exit(-1);
                } //if (!StringUtils.isNotBlank(containerName))

            } else {
                System.err.println("You must provide the -container for a copy operation to work as expected.");
                System.exit(-1);
            }

            folderPath = line.getOptionValue("folder");
            if (StringUtils.isNotBlank(folderPath)) {
                File folder = new File(FilenameUtils.normalize(folderPath));
                if (folder.isDirectory()) {
                    if (line.hasOption("z")) {
                        System.out.println("Zipping: " + folderPath);
                        System.out.println("Nested folders are ignored !");

                        File zipedFolder = zipFolder(folder);
                        String mimeType = FilesConstants.getMimetype(ZIPEXTENSION);
                        copyToCreateContainerIfNeeded(zipedFolder, mimeType, containerName);
                    } else {
                        File[] files = folder.listFiles();
                        for (File f : files) {
                            String mimeType = FilesConstants
                                    .getMimetype(FilenameUtils.getExtension(f.getName()));
                            System.out.println("Uploading :" + f.getName() + " to " + folder.getName());
                            copyToCreateContainerIfNeeded(f, mimeType, containerName);
                            System.out.println(
                                    "Upload :" + f.getName() + " to " + folder.getName() + " completed.");
                        }
                    }
                } else {
                    System.err.println("You must provide a valid folder value for the -folder option !");
                    System.err.println("The value provided is: " + FilenameUtils.normalize(folderPath));
                    System.exit(-1);
                }

            }
        } //if (line.hasOption("folder"))

        if (line.hasOption("file")) {
            String containerName = null;
            String fileNamePath = null;

            if (line.hasOption("container")) {
                containerName = line.getOptionValue("container");
                if (!StringUtils.isNotBlank(containerName) || containerName.indexOf('/') != -1) {
                    System.err.println("You must provide a valid value for the  Container to upload to !");
                    System.exit(-1);
                } //if (!StringUtils.isNotBlank(containerName))
            } else {
                System.err.println("You must provide the -container for a copy operation to work as expected.");
                System.exit(-1);
            }

            fileNamePath = line.getOptionValue("file");
            if (StringUtils.isNotBlank(fileNamePath)) {
                String fileName = FilenameUtils.normalize(fileNamePath);
                String fileExt = FilenameUtils.getExtension(fileNamePath);
                String mimeType = FilesConstants.getMimetype(fileExt);
                File file = new File(fileName);

                if (line.hasOption("z")) {
                    logger.info("Zipping " + fileName);
                    if (!file.isDirectory()) {
                        File zippedFile = zipFile(file);
                        mimeType = FilesConstants.getMimetype(ZIPEXTENSION);
                        copyTo(zippedFile, mimeType, containerName);
                        zippedFile.delete();
                    }

                } //if (line.hasOption("z"))
                else {

                    logger.info("Uploading " + fileName + ".");
                    if (!file.isDirectory())
                        copyTo(file, mimeType, containerName);
                    else {
                        System.err.println(
                                "The path you provided is a folder.  For uploading folders use the -folder option.");
                        System.exit(-1);
                    }
                }
            } //if (StringUtils.isNotBlank(file))
            else {
                System.err.println("You must provide a valid value for the file to upload !");
                System.exit(-1);
            }
        } //if (line.hasOption("file"))
    } //end try        
    catch (ParseException err) {
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
        err.printStackTrace(System.err);
    } //catch( ParseException err )
    catch (FilesAuthorizationException err) {
        logger.fatal("FilesAuthorizationException : Failed to login to your  account !" + err);
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
    } //catch (FilesAuthorizationException err)

    catch (Exception err) {
        logger.fatal("IOException : " + err);
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
    } //catch ( IOException err)
}

From source file:com.mosso.client.cloudfiles.sample.FilesCopy.java

public static void main(String args[]) throws NoSuchAlgorithmException, FilesException {
    //Build the command line options
    Options options = addCommandLineOptions();

    if (args.length <= 0)
        printHelp(options);//ww w.jav a  2s.  c  o  m

    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help"))
            printHelp(options);

        if (line.hasOption("file") && line.hasOption("folder")) {
            System.err.println("Can not use both -file and -folder on the command line at the same time.");
            System.exit(-1);
        } //if (line.hasOption("file") && line.hasOption("folder"))

        if (line.hasOption("download")) {
            if (line.hasOption("folder")) {
                String localFolder = FilenameUtils.normalize(line.getOptionValue("folder"));
                String containerName = null;
                if (StringUtils.isNotBlank(localFolder)) {
                    File localFolderObj = new File(localFolder);
                    if (localFolderObj.exists() && localFolderObj.isDirectory()) {
                        if (line.hasOption("container")) {
                            containerName = line.getOptionValue("container");
                            if (!StringUtils.isNotBlank(containerName)) {
                                System.err.println(
                                        "You must provide a valid value for the  Container to upload to !");
                                System.exit(-1);
                            } //if (!StringUtils.isNotBlank(ontainerName))                            
                        } else {
                            System.err.println(
                                    "You must provide the -container for a copy operation to work as expected.");
                            System.exit(-1);
                        }

                        System.out.println("Downloading all objects from: " + containerName
                                + " to local folder: " + localFolder);

                        getContainerObjects(localFolderObj, containerName);

                    } else {
                        if (!localFolderObj.exists()) {
                            System.err.println("The local folder: " + localFolder
                                    + " does not exist.  Create it first and then run this command.");
                        }

                        if (!localFolderObj.isDirectory()) {
                            System.err.println(
                                    "The local folder name supplied : " + localFolder + " is not a folder !");
                        }

                        System.exit(-1);
                    }
                }
            }
            System.exit(0);
        } //if (line.hasOption("download"))

        if (line.hasOption("folder")) {
            String containerName = null;
            String folderPath = null;

            if (line.hasOption("container")) {
                containerName = line.getOptionValue("container");
                if (!StringUtils.isNotBlank(containerName)) {
                    System.err.println("You must provide a valid value for the  Container to upload to !");
                    System.exit(-1);
                } //if (!StringUtils.isNotBlank(containerName))

            } else {
                System.err.println("You must provide the -container for a copy operation to work as expected.");
                System.exit(-1);
            }

            folderPath = line.getOptionValue("folder");
            if (StringUtils.isNotBlank(folderPath)) {
                File folder = new File(FilenameUtils.normalize(folderPath));
                if (folder.isDirectory()) {
                    if (line.hasOption("z")) {
                        System.out.println("Zipping: " + folderPath);
                        System.out.println("Nested folders are ignored !");

                        File zipedFolder = zipFolder(folder);
                        String mimeType = FilesConstants.getMimetype(ZIPEXTENSION);
                        copyToCreateContainerIfNeeded(zipedFolder, mimeType, containerName);
                    } else {
                        File[] files = folder.listFiles();
                        for (File f : files) {
                            String mimeType = FilesConstants
                                    .getMimetype(FilenameUtils.getExtension(f.getName()));
                            System.out.println("Uploading :" + f.getName() + " to " + folder.getName());
                            copyToCreateContainerIfNeeded(f, mimeType, containerName);
                            System.out.println(
                                    "Upload :" + f.getName() + " to " + folder.getName() + " completed.");
                        }
                    }
                } else {
                    System.err.println("You must provide a valid folder value for the -folder option !");
                    System.err.println("The value provided is: " + FilenameUtils.normalize(folderPath));
                    System.exit(-1);
                }

            }
        } //if (line.hasOption("folder"))

        if (line.hasOption("file")) {
            String containerName = null;
            String fileNamePath = null;

            if (line.hasOption("container")) {
                containerName = line.getOptionValue("container");
                if (!StringUtils.isNotBlank(containerName) || containerName.indexOf('/') != -1) {
                    System.err.println("You must provide a valid value for the  Container to upload to !");
                    System.exit(-1);
                } //if (!StringUtils.isNotBlank(containerName))
            } else {
                System.err.println("You must provide the -container for a copy operation to work as expected.");
                System.exit(-1);
            }

            fileNamePath = line.getOptionValue("file");
            if (StringUtils.isNotBlank(fileNamePath)) {
                String fileName = FilenameUtils.normalize(fileNamePath);
                String fileExt = FilenameUtils.getExtension(fileNamePath);
                String mimeType = FilesConstants.getMimetype(fileExt);
                File file = new File(fileName);

                if (line.hasOption("z")) {
                    logger.info("Zipping " + fileName);
                    if (!file.isDirectory()) {
                        File zippedFile = zipFile(file);
                        mimeType = FilesConstants.getMimetype(ZIPEXTENSION);
                        copyTo(zippedFile, mimeType, containerName);
                        zippedFile.delete();
                    }

                } //if (line.hasOption("z"))
                else {

                    logger.info("Uploading " + fileName + ".");
                    if (!file.isDirectory())
                        copyTo(file, mimeType, containerName);
                    else {
                        System.err.println(
                                "The path you provided is a folder.  For uploading folders use the -folder option.");
                        System.exit(-1);
                    }
                }
            } //if (StringUtils.isNotBlank(file))
            else {
                System.err.println("You must provide a valid value for the file to upload !");
                System.exit(-1);
            }
        } //if (line.hasOption("file"))
    } //end try        
    catch (ParseException err) {
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
        err.printStackTrace(System.err);
    } //catch( ParseException err )
    catch (FilesAuthorizationException err) {
        logger.fatal("FilesAuthorizationException : Failed to login to your  account !" + err);
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
    } //catch (FilesAuthorizationException err)

    catch (IOException err) {
        logger.fatal("IOException : " + err);
        System.err.println("Please see the logs for more details. Error Message: " + err.getMessage());
    } //catch ( IOException err)
}

From source file:com.jcwhatever.resourcepackermc.Main.java

public static void main(String[] args) {

    if (args.length == 0) {
        launch(args);//from w  w  w.j  a va2 s  .co  m
        return;
    }

    CommandLineParser parser = new BasicParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(_options, args);
    } catch (ParseException e) {
        System.err.println(e.getLocalizedMessage());
        showHelp();
        System.exit(-1);
        return;
    }

    // show help if requested
    if (cmd.hasOption("help")) {
        showHelp();
        return;
    }

    File folder;

    if (cmd.hasOption("folder")) {
        // use specified folder
        String foldername = cmd.getOptionValue("folder");
        folder = new File(foldername);
    } else {
        // use folder jar file is in.
        folder = Utils.getJarFolder();
    }

    // make sure folder exists
    if (!folder.exists()) {
        System.err.println("Folder not found: " + folder);
        System.exit(-1);
        return;
    }

    ResourcePackFiles files = new ResourcePackFiles(folder);
    Collection<OggSound> sounds = files.getSounds();
    Collection<OggSound> extraSounds = MinecraftSounds.removeMinecraft(sounds);

    // generate/update sounds.json file
    if (cmd.hasOption("sounds")) {

        SoundsJSONGenerator generator = new SoundsJSONGenerator();

        generator.generate(files, SoundsJSONGenerator.getFile(folder));

        // add newly generated sounds.json files to files collection
        if (files.getSoundsJson() == null) {
            File file = SoundsJSONGenerator.getFile(folder);
            files.getFiles().add(file);
        }
    }

    // Generate resource-sounds.yml
    if (cmd.hasOption("nucleus")) {
        NucleusGenerator generator = new NucleusGenerator();
        generator.generate(files, new File(Utils.getJarFolder(), "resource-sounds.yml"));
    }

    // Generate SOUNDS.TXT and SOUNDS_EXTRA.TXT
    if (cmd.hasOption("soundtxt")) {
        SoundsTxtGenerator generator = new SoundsTxtGenerator();

        File tracksFile = new File(Utils.getJarFolder(), "SOUNDS.TXT");

        generator.generate(files, tracksFile);
        System.out.println("Generated SOUNDS.TXT");

        if (!files.getFiles().contains(tracksFile)) {
            files.getFiles().add(tracksFile);
            System.out.println("Packed SOUNDS.TXT");
        }

        if (!extraSounds.isEmpty()) {

            SoundsExtraTxtGenerator extraGen = new SoundsExtraTxtGenerator();
            File extraTracksFile = new File(Utils.getJarFolder(), "SOUNDS_EXTRA.TXT");

            extraGen.generate(files, extraTracksFile);
            System.out.println("Generated SOUNDS_EXTRA.TXT");

            if (!files.getFiles().contains(extraTracksFile)) {
                files.getFiles().add(extraTracksFile);
                System.out.println("Packed SOUNDS_EXTRA.TXT");
            }
        }
    }

    // Generate Zip file
    if (cmd.hasOption("zip")) {
        String filename = cmd.getOptionValue("zip");
        File file = new File(Utils.getJarFolder(), filename);

        PackGenerator generator = new PackGenerator();
        generator.generate(files, file);
    }
}

From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java

public static void main(String[] args) {
    // check &   validate cmdline options
    OptionGroup opt_g = getCMDLineOptionsGroups();
    Options opt = getCMDLineOptions();//w  w  w.  j  a  v  a  2 s.  c o m
    opt.addOptionGroup(opt_g);

    CommandLineParser cli = new DefaultParser();
    try {
        CommandLine cl = cli.parse(opt, args);

        if (cl.hasOption("v")) {
            VerboseOutputFilter.SHOW_VERBOSE = true;
        }

        switch (opt_g.getSelected()) {
        case "V":
            try {
                URL jarUrl = Main.class.getProtectionDomain().getCodeSource().getLocation();
                String jarPath = URLDecoder.decode(jarUrl.getFile(), "UTF-8");
                JarFile jarFile = new JarFile(jarPath);
                Manifest m = jarFile.getManifest();
                StringBuilder versionInfo = new StringBuilder();
                for (Object key : m.getMainAttributes().keySet()) {
                    versionInfo.append(key).append(":").append(m.getMainAttributes().getValue(key.toString()))
                            .append("\n");
                }
                System.out.println(versionInfo.toString());
            } catch (Exception e) {
                log.error("Version info could not be read.");
            }
            break;
        case "h":
            HelpFormatter help = new HelpFormatter();
            String header = ""; //TODO: missing infotext 
            StringBuilder footer = new StringBuilder("Supported configuration properties :");
            help.printHelp("CodeGen -h | -V | -g  [...]", header, opt, footer.toString());
            break;
        case "g":
            // target dir
            if (cl.hasOption("t")) {
                File target = new File(cl.getOptionValue("t"));
                if (target.isDirectory() && target.canExecute() && target.canWrite()) {
                    config.setProperty("target.dir", cl.getOptionValue("t"));
                } else {
                    log.error("Target dir '{}' is inaccessible!", cl.getOptionValue("t"));
                    break;
                }
            } else {
                config.setProperty("target.dir", System.getProperty("java.io.tmpdir"));
            }

            // project dir
            if (cl.hasOption("p")) {
                File project = new File(cl.getOptionValue("p"));
                if (!project.exists()) {
                    if (!project.mkdirs()) {
                        log.error("Project dir '{}' can't be created!", cl.getOptionValue("p"));
                        break;
                    }
                }

                if (project.isDirectory() && project.canExecute() && project.canWrite()) {
                    config.setProperty("project.dir", cl.getOptionValue("p"));
                } else {
                    log.error("Project dir '{}' is inaccessible!", cl.getOptionValue("p"));
                    break;
                }
            }

            generateAppfromXML(cl.getOptionValue("g"));
            break;
        }
    } catch (ParseException e) {
        log.error("ParseException occurred while parsing cmdline arguments!\n{}", e.getLocalizedMessage());
    }

}

From source file:act.installer.GenbankInstaller.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());//from  w  ww .j a  v  a2s .  c  o m
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        LOGGER.error("Argument parsing failed: %s", e.getMessage());
        HELP_FORMATTER.printHelp(GenbankInstaller.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(GenbankInstaller.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    File genbankFile = new File(cl.getOptionValue(OPTION_GENBANK_PATH));
    String dbName = cl.getOptionValue(OPTION_DB_NAME);
    String seqType = cl.getOptionValue(OPTION_SEQ_TYPE);

    if (!genbankFile.exists()) {
        String msg = String.format("Genbank file path is null");
        LOGGER.error(msg);
        throw new RuntimeException(msg);
    } else {
        MongoDB db = new MongoDB("localhost", 27017, dbName);

        DBIterator iter = db.getDbIteratorOverOrgs();

        Iterator<Organism> orgIterator = new Iterator<Organism>() {
            @Override
            public boolean hasNext() {
                boolean hasNext = iter.hasNext();
                if (!hasNext)
                    iter.close();
                return hasNext;
            }

            @Override
            public Organism next() {
                DBObject o = iter.next();
                return db.convertDBObjectToOrg(o);
            }

        };

        OrgMinimalPrefixGenerator prefixGenerator = new OrgMinimalPrefixGenerator(orgIterator);
        Map<String, String> minimalPrefixMapping = prefixGenerator.getMinimalPrefixMapping();

        GenbankInstaller installer = new GenbankInstaller(genbankFile, seqType, db, minimalPrefixMapping);
        installer.init();
    }

}

From source file:com.frostvoid.trekwar.server.TrekwarServer.java

public static void main(String[] args) {
    // load language
    try {/*w w w . j ava2 s . co  m*/
        lang = new Language(Language.ENGLISH);
    } catch (IOException ioe) {
        System.err.println("FATAL ERROR: Unable to load language file!");
        System.exit(1);
    }

    System.out.println(lang.get("trekwar_server") + " " + VERSION);
    System.out.println("==============================================".substring(0,
            lang.get("trekwar_server").length() + 1 + VERSION.length()));

    // Handle parameters
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("file").withLongOpt("galaxy").hasArg()
            .withDescription("the galaxy file to load").create("g")); //"g", "galaxy", true, "the galaxy file to load");
    options.addOption(OptionBuilder.withArgName("port number").withLongOpt("port").hasArg()
            .withDescription("the port number to bind to (default 8472)").create("p"));
    options.addOption(OptionBuilder.withArgName("number").withLongOpt("save-interval").hasArg()
            .withDescription("how often (in turns) to save the galaxy to disk (default: 5)").create("s"));
    options.addOption(OptionBuilder.withArgName("log level").withLongOpt("log").hasArg()
            .withDescription("sets the log level: ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF")
            .create("l"));
    options.addOption("h", "help", false, "prints this help message");

    CommandLineParser cliParser = new BasicParser();

    try {
        CommandLine cmd = cliParser.parse(options, args);
        String portStr = cmd.getOptionValue("p");
        String galaxyFileStr = cmd.getOptionValue("g");
        String saveIntervalStr = cmd.getOptionValue("s");
        String logLevelStr = cmd.getOptionValue("l");

        if (cmd.hasOption("h")) {
            HelpFormatter help = new HelpFormatter();
            help.printHelp("TrekwarServer", options);
            System.exit(0);
        }

        if (cmd.hasOption("g") && galaxyFileStr != null) {
            galaxyFileName = galaxyFileStr;
        } else {
            throw new ParseException("galaxy file not specified");
        }

        if (cmd.hasOption("p") && portStr != null) {
            port = Integer.parseInt(portStr);
            if (port < 1 || port > 65535) {
                throw new NumberFormatException(lang.get("port_number_out_of_range"));
            }
        } else {
            port = 8472;
        }

        if (cmd.hasOption("s") && saveIntervalStr != null) {
            saveInterval = Integer.parseInt(saveIntervalStr);
            if (saveInterval < 1 || saveInterval > 100) {
                throw new NumberFormatException("Save Interval out of range (1-100)");
            }
        } else {
            saveInterval = 5;
        }

        if (cmd.hasOption("l") && logLevelStr != null) {
            if (logLevelStr.equalsIgnoreCase("finest")) {
                LOG.setLevel(Level.FINEST);
            } else if (logLevelStr.equalsIgnoreCase("finer")) {
                LOG.setLevel(Level.FINER);
            } else if (logLevelStr.equalsIgnoreCase("fine")) {
                LOG.setLevel(Level.FINE);
            } else if (logLevelStr.equalsIgnoreCase("config")) {
                LOG.setLevel(Level.CONFIG);
            } else if (logLevelStr.equalsIgnoreCase("info")) {
                LOG.setLevel(Level.INFO);
            } else if (logLevelStr.equalsIgnoreCase("warning")) {
                LOG.setLevel(Level.WARNING);
            } else if (logLevelStr.equalsIgnoreCase("severe")) {
                LOG.setLevel(Level.SEVERE);
            } else if (logLevelStr.equalsIgnoreCase("off")) {
                LOG.setLevel(Level.OFF);
            } else if (logLevelStr.equalsIgnoreCase("all")) {
                LOG.setLevel(Level.ALL);
            } else {
                System.err.println("ERROR: invalid log level: " + logLevelStr);
                System.err.println("Run again with -h flag to see valid log level values");
                System.exit(1);
            }
        } else {
            LOG.setLevel(Level.INFO);
        }
        // INIT LOGGING
        try {
            LOG.setUseParentHandlers(false);
            initLogging();
        } catch (IOException ex) {
            System.err.println("Unable to initialize logging to file");
            System.err.println(ex);
            System.exit(1);
        }

    } catch (Exception ex) {
        System.err.println("ERROR: " + ex.getMessage());
        System.err.println("use -h for help");
        System.exit(1);
    }

    LOG.log(Level.INFO, "Trekwar2 server " + VERSION + " starting up");

    // LOAD GALAXY
    File galaxyFile = new File(galaxyFileName);
    if (galaxyFile.exists()) {
        try {
            long timer = System.currentTimeMillis();
            LOG.log(Level.INFO, "Loading galaxy file {0}", galaxyFileName);
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(galaxyFile));
            galaxy = (Galaxy) ois.readObject();
            timer = System.currentTimeMillis() - timer;
            LOG.log(Level.INFO, "Galaxy file loaded in {0} ms", timer);
            ois.close();
        } catch (IOException ioe) {
            LOG.log(Level.SEVERE, "IO error while trying to load galaxy file", ioe);
        } catch (ClassNotFoundException cnfe) {
            LOG.log(Level.SEVERE, "Unable to find class while loading galaxy", cnfe);
        }
    } else {
        System.err.println("Error: file " + galaxyFileName + " not found");
        System.exit(1);
    }

    // if turn == 0 (start of game), execute first turn to update fog of war.
    if (galaxy.getCurrentTurn() == 0) {
        TurnExecutor.executeTurn(galaxy);
    }

    LOG.log(Level.INFO, "Current turn  : {0}", galaxy.getCurrentTurn());
    LOG.log(Level.INFO, "Turn speed    : {0} seconds", galaxy.getTurnSpeed() / 1000);
    LOG.log(Level.INFO, "Save Interval : {0}", saveInterval);
    LOG.log(Level.INFO, "Users / max   : {0} / {1}",
            new Object[] { galaxy.getUserCount(), galaxy.getMaxUsers() });

    // START SERVER
    try {
        server = new ServerSocket(port);
        LOG.log(Level.INFO, "Server listening on port {0}", port);
    } catch (BindException be) {
        LOG.log(Level.SEVERE, "Error: Unable to bind to port {0}", port);
        System.err.println(be);
        System.exit(1);
    } catch (IOException ioe) {
        LOG.log(Level.SEVERE, "Error: IO error while binding to port {0}", port);
        System.err.println(ioe);
        System.exit(1);
    }

    galaxy.startup();

    Thread timerThread = new Thread(new Runnable() {

        @Override
        @SuppressWarnings("SleepWhileInLoop")
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                    // && galaxy.getLoggedInUsers().size() > 0 will make server pause when nobody is logged in (TESTING)
                    if (System.currentTimeMillis() > galaxy.nextTurnDate) {
                        StringBuffer loggedInUsers = new StringBuffer();
                        for (User u : galaxy.getLoggedInUsers()) {
                            loggedInUsers.append(u.getUsername()).append(", ");
                        }

                        long time = TurnExecutor.executeTurn(galaxy);
                        LOG.log(Level.INFO, "Turn {0} executed in {1} ms",
                                new Object[] { galaxy.getCurrentTurn(), time });
                        LOG.log(Level.INFO, "Logged in users: " + loggedInUsers.toString());
                        LOG.log(Level.INFO,
                                "====================================================================================");

                        if (galaxy.getCurrentTurn() % saveInterval == 0) {
                            saveGalaxy();
                        }

                        galaxy.lastTurnDate = System.currentTimeMillis();
                        galaxy.nextTurnDate = galaxy.lastTurnDate + galaxy.turnSpeed;
                    }

                } catch (InterruptedException e) {
                    LOG.log(Level.SEVERE, "Error in main server loop, interrupted", e);
                }
            }
        }
    });
    timerThread.start();

    // ACCEPT CONNECTIONS AND DELEGATE TO CLIENT SESSIONS
    while (true) {
        Socket clientConnection;
        try {
            clientConnection = server.accept();
            ClientSession c = new ClientSession(clientConnection, galaxy);
            Thread t = new Thread(c);
            t.start();
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, "IO Exception while trying to handle incoming client connection", ex);
        }
    }
}

From source file:co.cask.cdap.etl.tool.UpgradeTool.java

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

    Options options = new Options().addOption(new Option("h", "help", false, "Print this usage message."))
            .addOption(new Option("u", "uri", true,
                    "CDAP instance URI to interact with in the format "
                            + "[http[s]://]<hostname>:<port>. Defaults to localhost:10000."))
            .addOption(new Option("a", "accesstoken", true,
                    "File containing the access token to use when interacting "
                            + "with a secure CDAP instance."))
            .addOption(new Option("t", "timeout", true,
                    "Timeout in milliseconds to use when interacting with the "
                            + "CDAP RESTful APIs. Defaults to " + DEFAULT_READ_TIMEOUT_MILLIS + "."))
            .addOption(new Option("n", "namespace", true,
                    "Namespace to perform the upgrade in. If none is given, "
                            + "pipelines in all namespaces will be upgraded."))
            .addOption(new Option("p", "pipeline", true,
                    "Name of the pipeline to upgrade. If specified, a namespace " + "must also be given."))
            .addOption(new Option("f", "configfile", true, "File containing old application details to update. "
                    + "The file contents are expected to be in the same format as the request body for creating an "
                    + "ETL application from one of the etl artifacts. "
                    + "It is expected to be a JSON Object containing 'artifact' and 'config' fields."
                    + "The value for 'artifact' must be a JSON Object that specifies the artifact scope, name, and version. "
                    + "The value for 'config' must be a JSON Object specifies the source, transforms, and sinks of the pipeline, "
                    + "as expected by older versions of the etl artifacts."))
            .addOption(new Option("o", "outputfile", true,
                    "File to write the converted application details provided in "
                            + "the configfile option. If none is given, results will be written to the input file + '.converted'. "
                            + "The contents of this file can be sent directly to CDAP to update or create an application."))
            .addOption(new Option("e", "errorDir", true,
                    "Optional directory to write any upgraded pipeline configs that "
                            + "failed to upgrade. The problematic configs can then be manually edited and upgraded separately. "
                            + "Upgrade errors may happen for pipelines that use plugins that are not backwards compatible. "
                            + "This directory must be writable by the user that is running this tool."));

    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(options, args);
    String[] commandArgs = commandLine.getArgs();

    // if help is an option, or if there isn't a single 'upgrade' command, print usage and exit.
    if (commandLine.hasOption("h") || commandArgs.length != 1 || !"upgrade".equalsIgnoreCase(commandArgs[0])) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp(UpgradeTool.class.getName() + " upgrade",
                "Upgrades Hydrator pipelines created for 3.2.x versions"
                        + "of the cdap-etl-batch and cdap-etl-realtime artifacts into pipelines compatible with 3.3.x versions of "
                        + "cdap-etl-batch and cdap-etl-realtime. Connects to an instance of CDAP to find any 3.2.x pipelines, then "
                        + "upgrades those pipelines.",
                options, "");
        System.exit(0);// www  . ja  va 2s . c o m
    }

    ClientConfig clientConfig = getClientConfig(commandLine);

    if (commandLine.hasOption("f")) {
        String inputFilePath = commandLine.getOptionValue("f");
        String outputFilePath = commandLine.hasOption("o") ? commandLine.getOptionValue("o")
                : inputFilePath + ".new";
        convertFile(inputFilePath, outputFilePath, new ArtifactClient(clientConfig));
        System.exit(0);
    }

    File errorDir = commandLine.hasOption("e") ? new File(commandLine.getOptionValue("e")) : null;
    if (errorDir != null) {
        if (!errorDir.exists()) {
            if (!errorDir.mkdirs()) {
                LOG.error("Unable to create error directory {}.", errorDir.getAbsolutePath());
                System.exit(1);
            }
        } else if (!errorDir.isDirectory()) {
            LOG.error("{} is not a directory.", errorDir.getAbsolutePath());
            System.exit(1);
        } else if (!errorDir.canWrite()) {
            LOG.error("Unable to write to error directory {}.", errorDir.getAbsolutePath());
            System.exit(1);
        }
    }
    UpgradeTool upgradeTool = new UpgradeTool(clientConfig, errorDir);

    String namespace = commandLine.getOptionValue("n");
    String pipelineName = commandLine.getOptionValue("p");

    if (pipelineName != null) {
        if (namespace == null) {
            throw new IllegalArgumentException("Must specify a namespace when specifying a pipeline.");
        }
        Id.Application appId = Id.Application.from(namespace, pipelineName);
        if (upgradeTool.upgrade(appId)) {
            LOG.info("Successfully upgraded {}.", appId);
        } else {
            LOG.info("{} did not need to be upgraded.", appId);
        }
        System.exit(0);
    }

    if (namespace != null) {
        printUpgraded(upgradeTool.upgrade(Id.Namespace.from(namespace)));
        System.exit(0);
    }

    printUpgraded(upgradeTool.upgrade());
}

From source file:de.prozesskraft.pkraft.Waitinstance.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    /*----------------------------
      get options from ini-file//w  w w .  ja  v a2 s  . com
    ----------------------------*/
    java.io.File inifile = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Waitinstance.class) + "/"
            + "../etc/pkraft-waitinstance.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option oinstance = OptionBuilder.withArgName("FILE").hasArg().withDescription(
            "[mandatory if no -scandir] instance file (process.pmb) that this program will wait till its status is 'error' or 'finished'")
            //            .isRequired()
            .create("instance");

    Option oscandir = OptionBuilder.withArgName("DIR").hasArg().withDescription(
            "[mandatory if no -instance] directory tree with instances (process.pmb). the first instance found will be tracked.")
            //            .isRequired()
            .create("scandir");

    Option omaxrun = OptionBuilder.withArgName("INTEGER").hasArg().withDescription(
            "[optional, default: 4320] time period (in minutes, default: 3 days) this program waits till it aborts further waiting.")
            //            .isRequired()
            .create("maxrun");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(oinstance);
    options.addOption(oscandir);
    options.addOption(omaxrun);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    // parse the command line arguments
    commandline = parser.parse(options, args);

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("waitinstance", options);
        System.exit(0);
    }

    if (commandline.hasOption("v")) {
        System.out.println("author:  alexander.vogel@caegroup.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }
    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    Integer maxrun = new Integer(4320);
    String pathInstance = null;
    String pathScandir = null;

    // instance & scandir
    if (!(commandline.hasOption("instance")) && !(commandline.hasOption("scandir"))) {
        System.err.println("one of the options -instance/-scandir is mandatory");
        exiter();
    } else if ((commandline.hasOption("instance")) && (commandline.hasOption("scandir"))) {
        System.err.println("both options -instance/-scandir are not allowed");
        exiter();
    } else if (commandline.hasOption("instance")) {
        pathInstance = commandline.getOptionValue("instance");
    } else if (commandline.hasOption("scandir")) {
        pathScandir = commandline.getOptionValue("scandir");
    }

    // maxrun
    if (commandline.hasOption("maxrun")) {
        maxrun = new Integer(commandline.getOptionValue("maxrun"));
    }
    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/

    // scannen nach dem ersten process.pmb 
    if ((pathScandir != null) && (pathInstance == null)) {
        String[] allBinariesOfScanDir = getProcessBinaries(pathScandir);

        if (allBinariesOfScanDir.length == 0) {
            System.err.println("no instance (process.pmb) found in directory tree " + pathScandir);
            exiter();
        } else {
            pathInstance = allBinariesOfScanDir[0];
            System.err.println("found instance: " + pathInstance);
        }
    }

    // ueberpruefen ob instance file existiert
    java.io.File fileInstance = new java.io.File(pathInstance);

    if (!fileInstance.exists()) {
        System.err.println("instance file does not exist: " + fileInstance.getAbsolutePath());
        exiter();
    }

    if (!fileInstance.isFile()) {
        System.err.println("instance file is not a file: " + fileInstance.getAbsolutePath());
        exiter();
    }

    // zeitpunkt wenn spaetestens beendet werden soll
    long runTill = System.currentTimeMillis() + (maxrun * 60 * 1000);

    // logging
    System.err.println("waiting for instance: " + fileInstance.getAbsolutePath());
    System.err.println("checking its status every 5 minutes");
    System.err.println("now is: " + new Timestamp(startInMillis).toString());
    System.err.println("maxrun till: " + new Timestamp(runTill).toString());

    // instanz einlesen
    Process p1 = new Process();
    p1.setInfilebinary(fileInstance.getAbsolutePath());
    Process p2 = p1.readBinary();

    // schleife, die prozess einliest und ueberprueft ob er noch laeuft
    while (!(p2.getStatus().equals("error") || p2.getStatus().equals("finished"))) {
        // logging
        System.err.println(new Timestamp(System.currentTimeMillis()) + " instance status: " + p2.getStatus());

        // 5 minuten schlafen: 300000 millis
        try {
            Thread.sleep(300000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // ist die maximale laufzeit von this erreicht, dann soll beendet werden (3 tage)
        if (System.currentTimeMillis() > runTill) {
            System.err
                    .println("exiting because of maxrun. now is: " + new Timestamp(System.currentTimeMillis()));
            System.exit(2);
        }

        // den prozess frisch einlesen
        p2 = p1.readBinary();
    }

    System.err.println("exiting because instance status is: " + p2.getStatus());
    System.err.println("now is: " + new Timestamp(System.currentTimeMillis()).toString());
    System.exit(0);

}