Example usage for java.io File isFile

List of usage examples for java.io File isFile

Introduction

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

Prototype

public boolean isFile() 

Source Link

Document

Tests whether the file denoted by this abstract pathname is a normal file.

Usage

From source file:net.sf.xmm.moviemanager.MovieManager.java

public static void main(String args[]) {

    boolean sandbox = SysUtil.isRestrictedSandbox();

    // Uses this to check if the app is running in a sandbox with limited privileges
    try {/*w  ww .j a  va2s .  c  om*/
        /* Disable HTTPClient logging output */
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); //$NON-NLS-1$ //$NON-NLS-2$

    } catch (java.security.AccessControlException s) {
        s.printStackTrace();
        sandbox = true;
    }

    if (!sandbox) {
        // Disables logging for cobra html renderer
        java.util.logging.Logger.getLogger("").setLevel(java.util.logging.Level.OFF);

        File log4jConfigFile = FileUtil.getFile("config/log4j.properties"); //$NON-NLS-1$

        if (log4jConfigFile.isFile()) {
            PropertyConfigurator.configure(log4jConfigFile.getAbsolutePath());
        } else {
            BasicConfigurator.configure();
        }
    } else
        BasicConfigurator.configure();

    log = Logger.getRootLogger();

    // Places the Log file in the user directory (the program location)
    RollingFileAppender appndr = (RollingFileAppender) log.getAppender("FileAppender");

    String logFile = null;

    try {
        if (SysUtil.isMac() || SysUtil.isWindowsVista() || SysUtil.isWindows7())
            logFile = new File(SysUtil.getConfigDir(), "Log.txt").getAbsolutePath();
    } catch (Exception e1) {
        e1.printStackTrace();
    } finally {

        if (logFile == null)
            logFile = new File(SysUtil.getUserDir(), "Log.txt").getAbsolutePath();
    }

    if (appndr != null && appndr.getFile() == null) {
        appndr.setFile(logFile);
        appndr.activateOptions();
    }

    /* Writes the date. */
    log.debug("================================================================================"); //$NON-NLS-1$
    log.debug("Log Start: " + new Date(System.currentTimeMillis())); //$NON-NLS-1$
    log.debug("MeD's Movie Manager v" + config.sysSettings.getVersion()); //$NON-NLS-1$
    log.debug("MovieManager release:" + MovieManager.getConfig().sysSettings.getRelease() + " - "
            + "IMDb Lib release:" + IMDbLib.getRelease() + " (" + IMDbLib.getVersion() + ")");
    log.debug(SysUtil.getSystemInfo(SysUtil.getLineSeparator())); //$NON-NLS-1$

    /* Loads the config */
    if (!sandbox)
        config.loadConfig();

    // Calls the plugin startup method 
    MovieManagerStartupHandler startupHandler = MovieManager.getConfig().getStartupHandler();

    if (startupHandler != null) {
        startupHandler.startUp();
    }

    if (!sandbox) {

        if (SysUtil.isAtLeastJRE6()) {
            SysUtil.includeJarFilesInClasspath("lib/LookAndFeels/1.6");
        }

        SysUtil.includeJarFilesInClasspath("lib/LookAndFeels");
        SysUtil.includeJarFilesInClasspath("lib/drivers");

        /* Must be called before the GUI is created */
        if (SysUtil.isMac()) {
            SysUtil.includeJarFilesInClasspath("lib/mac");
            lookAndFeelManager.setupOSXLaF();
        }
    }

    movieManager = new MovieManager();
    movieManager.sandbox = sandbox;

    //       Loads the HTML templates
    templateHandler.loadHTMLTemplates();

    EventQueue.invokeLater(new Runnable() {
        public final void run() {

            try {

                /* Installs the Look&Feels */
                lookAndFeelManager.instalLAFs();

                if (!MovieManager.isApplet())
                    lookAndFeelManager.setLookAndFeel();

                log.debug("Look & Feels installed.");

                log.debug("Creating MovieManager Dialog");
                movieManager.createDialog();

                /* Starts the MovieManager. */
                MovieManager.getDialog().setUp();
                log.debug("MovieManager Dialog - setup.");

                MovieManager.getDialog().showDialog();

                /* SetUp the Application Menu for OSX */
                if (SysUtil.isMac()) {
                    LookAndFeelManager.macOSXRegistration(MovieManager.getDialog());
                }

                // Calls the plugin startup method 
                MovieManagerLoginHandler loginHandler = MovieManager.getConfig().getLoginHandler();

                if (loginHandler != null) {
                    loginHandler.loginStartUp();
                }

                log.debug("Loading Database....");

                /* Loads the database. */
                databaseHandler.loadDatabase(true);

                log.debug("Database loaded.");

                AppUpdater.handleVersionUpdate();

            } catch (Exception e) {
                log.error("Exception occured while intializing MeD's Movie Manager", e);
            }
        }
    });
}

From source file:DIA_Umpire_Quant.DIA_Umpire_IntLibSearch.java

/**
 * @param args the command line arguments
 *//*from w  w w. java2s . c  o m*/
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println("DIA-Umpire targeted re-extraction analysis using internal library (version: "
            + UmpireInfo.GetInstance().Version + ")");
    if (args.length != 1) {
        System.out.println(
                "command format error, the correct format should be : java -jar -Xmx10G DIA_Umpire_IntLibSearch.jar diaumpire_module.params");
        return;
    }
    try {
        ConsoleLogger.SetConsoleLogger(Level.INFO);
        ConsoleLogger.SetFileLogger(Level.DEBUG,
                FilenameUtils.getFullPath(args[0]) + "diaumpire_intlibsearch.log");
    } catch (Exception e) {
    }

    Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version);
    Logger.getRootLogger().info("Parameter file:" + args[0]);

    BufferedReader reader = new BufferedReader(new FileReader(args[0]));
    String line = "";
    String WorkFolder = "";
    int NoCPUs = 2;

    String InternalLibID = "";

    float ProbThreshold = 0.99f;
    float RTWindow_Int = -1f;
    float Freq = 0f;
    int TopNFrag = 6;

    TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600);
    HashMap<String, File> AssignFiles = new HashMap<>();

    //<editor-fold defaultstate="collapsed" desc="Reading parameter file">
    while ((line = reader.readLine()) != null) {
        line = line.trim();
        Logger.getRootLogger().info(line);
        if (!"".equals(line) && !line.startsWith("#")) {
            //System.out.println(line);
            if (line.equals("==File list begin")) {
                do {
                    line = reader.readLine();
                    line = line.trim();
                    if (line.equals("==File list end")) {
                        continue;
                    } else if (!"".equals(line)) {
                        File newfile = new File(line);
                        if (newfile.exists()) {
                            AssignFiles.put(newfile.getAbsolutePath(), newfile);
                        } else {
                            Logger.getRootLogger().info("File: " + newfile + " does not exist.");
                        }
                    }
                } while (!line.equals("==File list end"));
            }
            if (line.split("=").length < 2) {
                continue;
            }
            String type = line.split("=")[0].trim();
            String value = line.split("=")[1].trim();
            switch (type) {
            case "Path": {
                WorkFolder = value;
                break;
            }
            case "path": {
                WorkFolder = value;
                break;
            }
            case "Thread": {
                NoCPUs = Integer.parseInt(value);
                break;
            }

            case "InternalLibID": {
                InternalLibID = value;
                break;
            }

            case "RTWindow_Int": {
                RTWindow_Int = Float.parseFloat(value);
                break;
            }

            case "ProbThreshold": {
                ProbThreshold = Float.parseFloat(value);
                break;
            }
            case "TopNFrag": {
                TopNFrag = Integer.parseInt(value);
                break;
            }
            case "Freq": {
                Freq = Float.parseFloat(value);
                break;
            }
            case "Fasta": {
                tandemPara.FastaPath = value;
                break;
            }
            }
        }
    }
    //</editor-fold>

    //Initialize PTM manager using compomics library
    PTMManager.GetInstance();

    //Check if the fasta file can be found
    if (!new File(tandemPara.FastaPath).exists()) {
        Logger.getRootLogger().info("Fasta file :" + tandemPara.FastaPath
                + " cannot be found, the process will be terminated, please check.");
        System.exit(1);
    }

    //Generate DIA file list
    ArrayList<DIAPack> FileList = new ArrayList<>();
    try {
        File folder = new File(WorkFolder);
        if (!folder.exists()) {
            Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found.");
            System.exit(1);
        }
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isFile()
                    && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                            | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry);
            }
            if (fileEntry.isDirectory()) {
                for (final File fileEntry2 : fileEntry.listFiles()) {
                    if (fileEntry2.isFile()
                            && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                                    | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                        AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2);
                    }
                }
            }
        }

        Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size());
        for (File fileEntry : AssignFiles.values()) {
            Logger.getRootLogger().info(fileEntry.getAbsolutePath());
        }
        for (File fileEntry : AssignFiles.values()) {
            String mzXMLFile = fileEntry.getAbsolutePath();
            if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) {
                DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs);
                Logger.getRootLogger().info(
                        "=================================================================================================");
                Logger.getRootLogger().info("Processing " + mzXMLFile);
                if (!DiaFile.LoadDIASetting()) {
                    Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete");
                    System.exit(1);
                }
                if (!DiaFile.LoadParams()) {
                    Logger.getRootLogger().info("Loading parameters failed, job is incomplete");
                    System.exit(1);
                }
                Logger.getRootLogger().info("Loading identification results " + mzXMLFile + "....");

                //If the serialization file for ID file existed
                if (DiaFile.ReadSerializedLCMSID()) {
                    DiaFile.IDsummary.ReduceMemoryUsage();
                    DiaFile.IDsummary.FastaPath = tandemPara.FastaPath;
                    FileList.add(DiaFile);
                }
            }
        }

        //<editor-fold defaultstate="collapsed" desc="Targete re-extraction using internal library">            
        Logger.getRootLogger().info(
                "=================================================================================================");
        if (FileList.size() > 1) {
            Logger.getRootLogger().info("Targeted re-extraction using internal library");

            FragmentLibManager libManager = FragmentLibManager.ReadFragmentLibSerialization(WorkFolder,
                    InternalLibID);
            if (libManager == null) {
                Logger.getRootLogger().info("Building internal spectral library");
                libManager = new FragmentLibManager(InternalLibID);
                ArrayList<LCMSID> LCMSIDList = new ArrayList<>();
                for (DIAPack dia : FileList) {
                    LCMSIDList.add(dia.IDsummary);
                }
                libManager.ImportFragLibTopFrag(LCMSIDList, Freq, TopNFrag);
                libManager.WriteFragmentLibSerialization(WorkFolder);
            }
            libManager.ReduceMemoryUsage();

            Logger.getRootLogger()
                    .info("Building retention time prediction model and generate candidate peptide list");
            for (int i = 0; i < FileList.size(); i++) {
                FileList.get(i).IDsummary.ClearMappedPep();
            }
            for (int i = 0; i < FileList.size(); i++) {
                for (int j = i + 1; j < FileList.size(); j++) {
                    RTAlignedPepIonMapping alignment = new RTAlignedPepIonMapping(WorkFolder,
                            FileList.get(i).GetParameter(), FileList.get(i).IDsummary,
                            FileList.get(j).IDsummary);
                    alignment.GenerateModel();
                    alignment.GenerateMappedPepIon();
                }
                FileList.get(i).ExportID();
                FileList.get(i).IDsummary = null;
            }

            Logger.getRootLogger().info("Targeted matching........");
            for (DIAPack diafile : FileList) {
                if (diafile.IDsummary == null) {
                    diafile.ReadSerializedLCMSID();
                }
                if (!diafile.IDsummary.GetMappedPepIonList().isEmpty()) {
                    diafile.UseMappedIon = true;
                    diafile.FilterMappedIonByProb = false;
                    diafile.BuildStructure();
                    diafile.MS1FeatureMap.ReadPeakCluster();
                    diafile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster();
                    diafile.GenerateMassCalibrationRTMap();
                    diafile.TargetedExtractionQuant(false, libManager, ProbThreshold, RTWindow_Int);
                    diafile.MS1FeatureMap.ClearAllPeaks();
                    diafile.IDsummary.ReduceMemoryUsage();
                    diafile.IDsummary.RemoveLowProbMappedIon(ProbThreshold);
                    diafile.ExportID();
                    Logger.getRootLogger().info("Peptide ions: " + diafile.IDsummary.GetPepIonList().size()
                            + " Mapped ions: " + diafile.IDsummary.GetMappedPepIonList().size());
                    diafile.ClearStructure();
                }
                diafile.IDsummary = null;
                System.gc();
            }
            Logger.getRootLogger().info(
                    "=================================================================================================");
        }
        //</editor-fold>

        Logger.getRootLogger().info("Job done");
        Logger.getRootLogger().info(
                "=================================================================================================");

    } catch (Exception e) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e));
        throw e;
    }
}

From source file:MainClass.java

public static void main(String args[]) {
    File f1 = new File("MainClass.java");
    System.out.println("File Name:" + f1.getName());
    System.out.println("Path:" + f1.getPath());
    System.out.println("Abs Path:" + f1.getAbsolutePath());
    System.out.println("Parent:" + f1.getParent());
    System.out.println(f1.exists() ? "exists" : "does not exist");
    System.out.println(f1.canWrite() ? "is writeable" : "is not writeable");
    System.out.println(f1.canRead() ? "is readable" : "is not readable");
    System.out.println("is a directory" + f1.isDirectory());
    System.out.println(f1.isFile() ? "is normal file" : "might be a named pipe");
    System.out.println(f1.isAbsolute() ? "is absolute" : "is not absolute");
    System.out.println("File last modified:" + f1.lastModified());
    System.out.println("File size:" + f1.length() + " Bytes");
}

From source file:FileDemo.java

public static void main(String args[]) {
    File f1 = new File("/java/COPYRIGHT");
    System.out.println("File Name: " + f1.getName());
    System.out.println("Path: " + f1.getPath());
    System.out.println("Abs Path: " + f1.getAbsolutePath());
    System.out.println("Parent: " + f1.getParent());
    System.out.println(f1.exists() ? "exists" : "does not exist");
    System.out.println(f1.canWrite() ? "is writeable" : "is not writeable");
    System.out.println(f1.canRead() ? "is readable" : "is not readable");
    System.out.println("is " + (f1.isDirectory() ? "" : "not" + " a directory"));
    System.out.println(f1.isFile() ? "is normal file" : "might be a named pipe");
    System.out.println(f1.isAbsolute() ? "is absolute" : "is not absolute");
    System.out.println("File last modified: " + f1.lastModified());
    System.out.println("File size: " + f1.length() + " Bytes");
}

From source file:fr.iphc.grid.jobmanager.JobManager.java

/**
 * @param args/*from  w  ww  . j a v  a  2 s.  co  m*/
 */
public static void main(String[] args) throws Exception {
    JobManager command = new JobManager();
    CommandLine line = command.parse(args);
    ArrayList<File> JdlList = new ArrayList<File>();
    Global.getOutputexecutor = Executors.newFixedThreadPool(10);
    Initialize init = new Initialize();
    String SetupFile = "setup_vigrid.xml";

    if (line.hasOption(OPT_SETUP)) {
        SetupFile = line.getOptionValue(OPT_SETUP);
    }
    if ((new File(SetupFile).isFile())) {
        init.GlobalSetup(SetupFile);
    }
    // Init Job
    if (line.hasOption(OPT_JOB)) {
        File file = new File(line.getOptionValue(OPT_JOB));
        if ((file.isFile())) {
            JdlList.add(file);
        } else {
            System.err.println("The file " + file + " doesn't exist");
            System.exit(-1);
        }
    } else {
        File file = new File(line.getOptionValue(OPT_FILEJOB));
        if ((file.isFile())) {
            JdlList = init.InitJdl(file);
        } else {
            System.err.println("The file " + file + " doesn't exist");
            System.exit(-1);
        }
    }
    if (line.hasOption(OPT_WAIT)) {
        Global.TIMEOUTWAIT = Integer.parseInt(line.getOptionValue(OPT_WAIT));
    }
    if (line.hasOption(OPT_RUN)) {
        Global.TIMEOUTRUN = Integer.parseInt(line.getOptionValue(OPT_RUN));
    }
    if (line.hasOption(OPT_END)) {
        Global.TIMEOUTEND = Integer.parseInt(line.getOptionValue(OPT_END));
    }
    if (line.hasOption(OPT_LOGDISPLAY)) {
        Global.SEUILDISPLAYLOG = Float.parseFloat(line.getOptionValue(OPT_LOGDISPLAY));
    }
    init.InitJob(JdlList);
    // Init Url Ce
    if (line.hasOption(OPT_QUEUE)) {
        Global.file = new File(line.getOptionValue(OPT_QUEUE));
    }
    if (line.hasOption(OPT_BAD)) {
        Global.BadCe = new File(line.getOptionValue(OPT_BAD));
    }
    if (line.hasOption(OPT_OPTIMIZETIMEOUTRUN)) {
        Global.OPTTIMEOUTRUN = false;
    }
    if (line.hasOption(OPT_CWD)) {
        File theDir = new File(line.getOptionValue(OPT_CWD));
        if (!theDir.exists()) {
            if (!theDir.mkdirs()) {
                System.err.println("Working directory create failed: " + line.getOptionValue(OPT_CWD));
                System.exit(-1);
            }
        }
        Global.Cwd = line.getOptionValue(OPT_CWD);
    } else {
        Global.Cwd = System.getProperty("user.dir");
    }
    if (!(new File(Global.Cwd)).canWrite()) {
        System.err.println(" Write permission denied : " + Global.Cwd);
        System.exit(-1);
    }
    System.out.println("Current working directory : " + Global.Cwd);
    Date start = new Date();
    init.PrintGlobalSetup();
    init.InitUrl(Global.file);
    init.InitSosCe();
    init.rmLoadFailed(Global.Cwd + "/loadFailed.txt");
    System.out.println("CE: " + Global.ListUrl.size() + " Nb JOB: " + Global.ListJob.size() + " " + new Date());
    if (Global.ListJob.size() < 6) { // pour obtenir rapport de 0.8
        Global.OPTTIMEOUTRUN = false;
    }
    // check if we can connect to the grid
    try {
        SessionFactory.createSession(true);
    } catch (NoSuccessException e) {
        System.err.println("Could not connect to the grid at all (" + e.getMessage() + ")");
        System.err.println("Aborting");
        System.exit(0);

    }
    // Launch Tread Job
    JobThread st = new JobThread(Global.ListJob, Global.ListUrl);
    st.start();
    LoggingThread logst = new LoggingThread(Global.ListJob, Global.ListUrl, Global.SEUILDISPLAYLOG);
    logst.start();
    // create Thread Hook intercept kill +CNTL+C
    Thread hook = new Thread() {
        public void run() {
            try {
                for (Jdl job : Global.ListJob) {
                    if (job.getJobId() != null) {
                        JobThread.jobCancel(job.getJobId());
                    }
                }
            } catch (Exception e) {
                System.err.println("Thread Hook:\n" + e.getMessage());
            }
            // give it a change to display final job state
            try {
                sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    Runtime.getRuntime().addShutdownHook(hook);

    //      Integer timer = 180 * 60 * 1000;
    Date now = new Date();

    //      Boolean Fin = false;
    while ((!Global.END) && ((now.getTime() - start.getTime()) < Global.TIMEOUTEND * 60 * 1000)) { // TOEND
        // en
        // minutes
        now = new Date();
        // int mb = 1024*1024;
        // Getting the runtime reference from system
        // Runtime runtime = Runtime.getRuntime();
        // System.out.println("##### Heap utilization statistics [MB]
        // #####");
        // Print used memory
        // System.out.println("Used Memory:"
        // + (runtime.totalMemory() - runtime.freeMemory()) / mb);

        // Print free memory
        // System.out.println("Free Memory:"
        // + runtime.freeMemory() / mb);

        // Print total available memory
        // System.out.println("Total Memory:" + runtime.totalMemory() / mb);

        // Print Maximum available memory
        // System.out.println("Max Memory:" + runtime.maxMemory() / mb);
        // // System.out.println("NB: "+nb_end);
        // if ((float)(runtime.totalMemory() -
        // runtime.freeMemory())/(float)runtime.maxMemory() > (float)0.3){
        // System.out.println ("GC: "+(float)(runtime.totalMemory() -
        // runtime.freeMemory())/runtime.maxMemory());
        // System.gc();
        // };
        sleep(15 * 1000); // in ms

        // System.gc();
        // Fin=true;
        // for (Jdl job : Global.ListJob) {
        // if (job.getJob() != null) {
        // System.out.println("JOB: "+job.getId()+"\t"+job.getStatus());
        // if (job.getStatus().compareTo("END")==0){
        // ((JobImpl) job.getJob()).postStagingAndCleanup();
        // System.out.println("END JOB: "+job.getId());
        // job.setStatus("END");
        // }
        // if (job.getStatus().compareTo("END")!=0){
        // Fin=false;
        // }
        // System.out.println("JOB: "+job.getId()+"\t"+job.getStatus() +
        // "\t"+job.getFail()+"\t"+job.getNodeCe());
        // }
        // }
        // while ((Global.END==0) && ((new
        // Date().getTime()-start.getTime())<timer)){
    }
    // Boolean end_load=false;
    // while (!end_load){
    // end_load=true;
    // for(Jdl job:Global.ListJob){
    // if (job.getStatus().equals("LOAD")){
    // end_load=false;
    // }
    // }
    // }
    System.out.println("END JOB: " + now);
    st.halt();
    logst.halt();
    Iterator<Url> k = Global.ListUrl.iterator();
    while (k.hasNext()) {
        Url url = k.next();
        System.out.println("URL: " + url.getUrl());
    }
    Iterator<Jdl> m = Global.ListJob.iterator();
    while (m.hasNext()) {
        Jdl job = m.next();
        System.out.println(
                "JOB: " + job.getId() + "\t" + job.getFail() + "\t" + job.getStatus() + "\t" + job.getNodeCe());
    }
    System.out.println(start + " " + new Date());
    System.exit(0);
}

From source file:edu.cuhk.hccl.IDConverter.java

public static void main(String[] args) {
    if (args.length < 2) {
        printUsage();//www  .  ja v a  2 s  .co m
    }

    try {
        File inFile = new File(args[0]);
        File outFile = new File(args[1]);

        if (inFile.isDirectory()) {
            System.out.println("ID Converting begins...");
            FileUtils.forceMkdir(outFile);
            for (File file : inFile.listFiles()) {
                if (!file.isHidden())
                    processFile(file, new File(outFile.getAbsolutePath() + "/"
                            + FilenameUtils.removeExtension(file.getName()) + "-long.txt"));
            }
        } else if (inFile.isFile()) {
            System.out.println("ID Converting begins...");
            processFile(inFile, outFile);
        } else {
            printUsage();
        }

        System.out.println("ID Converting finished.");

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.objectrepository.MessageConsumerDaemon.java

/**
 * main/*from   w ww.  ja va  2s  . c o  m*/
 * <p/>
 * Accepts one folder as argument:  -messageQueues
 * That folder ought to contain one or more folders ( or symbolic links ) to the files
 * The folder has the format: [foldername] or [foldername].[maxTasks]
 * MaxTasks is to indicate the total number of jobs being able to run.
 *
 * long
 *
 * @param argv
 */
public static void main(String[] argv) {

    if (instance == null) {
        final Properties properties = new Properties();

        if (argv.length > 0) {
            for (int i = 0; i < argv.length; i += 2) {
                try {
                    properties.put(argv[i], argv[i + 1]);
                } catch (ArrayIndexOutOfBoundsException arr) {
                    System.out.println("Missing value after parameter " + argv[i]);
                    System.exit(-1);
                }
            }
        } else {
            log.fatal("Usage: pmq-agent.jar -messageQueues [queues] -heartbeatInterval [interval in ms]\n"
                    + "The queues is a folder that contains symbolic links to the startup scripts.");
            System.exit(-1);
        }

        if (log.isInfoEnabled()) {
            log.info("Arguments set: ");
            for (String key : properties.stringPropertyNames()) {
                log.info("'" + key + "'='" + properties.getProperty(key) + "'");
            }
        }

        if (!properties.containsKey("-messageQueues")) {
            log.fatal("Expected case sensitive parameter: -messageQueues");
            System.exit(-1);
        }

        final File messageQueues = new File((String) properties.get("-messageQueues"));
        if (!messageQueues.exists()) {
            log.fatal("Cannot find folder for messageQueues: " + messageQueues.getAbsolutePath());
            System.exit(-1);
        }

        if (messageQueues.isFile()) {
            log.fatal(
                    "-messageQueues should point to a folder, not a file: " + messageQueues.getAbsolutePath());
            System.exit(-1);
        }

        long heartbeatInterval = 600000;
        if (properties.containsKey("-heartbeatInterval")) {
            heartbeatInterval = Long.parseLong((String) properties.get("heartbeatInterval"));
        }

        String identifier = null;
        if (properties.containsKey("-id")) {
            identifier = (String) properties.get("-id");
        } else if (properties.containsKey("-identifier")) {
            identifier = (String) properties.get("-identifier");
        }

        final File[] files = messageQueues.listFiles();
        final String[] scriptNames = (properties.containsKey("-startup"))
                ? new String[] { properties.getProperty("-startup") }
                : new String[] { "/startup.sh", "\\startup.bat" };
        final List<Queue> queues = new ArrayList<Queue>();
        for (File file : files) {
            final String name = file.getName();
            final String[] split = name.split("\\.", 2);
            final String queueName = split[0];
            for (String scriptName : scriptNames) {
                final String shellScript = file.getAbsolutePath() + scriptName;
                final int maxTask = (split.length == 1) ? 1 : Integer.parseInt(split[1]);
                log.info("Candidate mq client for " + queueName + " maxTasks " + maxTask);
                if (new File(shellScript).exists()) {
                    final Queue queue = new Queue(queueName, shellScript, false);
                    queue.setCorePoolSize(1);
                    queue.setMaxPoolSize(maxTask);
                    queue.setQueueCapacity(1);
                    queues.add(queue);
                    break;
                } else {
                    log.warn("... skipping, because no startup script found at " + shellScript);
                }
            }
        }

        if (queues.size() == 0) {
            log.fatal("No queue folders seen in " + messageQueues.getAbsolutePath());
            System.exit(-1);
        }

        // Add the system queue
        queues.add(new Queue("Connection", null, true));

        getInstance(queues, identifier, heartbeatInterval).run();
    }
    System.exit(0);
}

From source file:de.mycrobase.jcloudapp.Main.java

public static void main(String[] args) throws Exception {
    try {//w  ww .j a  v  a 2s.c o m
        // borrowed from https://github.com/cmur2/gloudapp
        ImageNormal = ImageIO.read(Main.class.getResourceAsStream("gloudapp.png"));
        ImageWorking = ImageIO.read(Main.class.getResourceAsStream("gloudapp_working.png"));
        IconNormal = new ImageIcon(ImageNormal.getScaledInstance(64, 64, Image.SCALE_SMOOTH));
        IconLarge = new ImageIcon(ImageNormal);
    } catch (IOException ex) {
        showErrorDialog("Could not load images!\n" + ex);
        System.exit(1);
    }

    URI serviceUrl = URI.create("http://my.cl.ly:80/");
    File storage = getStorageFile();

    if (storage.exists() && storage.isFile()) {
        Yaml yaml = new Yaml();
        try {
            Map<String, String> m = (Map<String, String>) yaml.load(new FileInputStream(storage));
            // avoid NPE by implicitly assuming the presence of a service URL
            if (m.containsKey("service_url")) {
                serviceUrl = URI.create(m.get("service_url"));
            }
        } catch (IOException ex) {
            showErrorDialog("Loading settings from .cloudapp-cli failed: " + ex);
            System.exit(1);
        }
    }

    Main app = new Main(serviceUrl);
    app.login(args);
    app.run();
}

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/*ww  w .ja va  2s  . c o m*/
    ----------------------------*/
    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);

}

From source file:appmain.AppMain.java

public static void main(String[] args) {

    try {/*w  ww.j  a  v a  2s  .  co m*/
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        UIManager.put("OptionPane.yesButtonText", "Igen");
        UIManager.put("OptionPane.noButtonText", "Nem");
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    try {

        AppMain app = new AppMain();
        app.init();

        File importFolder = new File(DEFAULT_IMPORT_FOLDER);
        if (!importFolder.isDirectory() || !importFolder.exists()) {
            JOptionPane.showMessageDialog(null,
                    "Az IMPORT mappa nem elrhet!\n"
                            + "Ellenrizze az elrsi utat s a jogosultsgokat!\n" + "Mappa: "
                            + importFolder.getAbsolutePath(),
                    "Informci", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        File exportFolder = new File(DEFAULT_EXPORT_FOLDER);
        if (!exportFolder.isDirectory() || !exportFolder.exists()) {
            JOptionPane.showMessageDialog(null,
                    "Az EXPORT mappa nem elrhet!\n"
                            + "Ellenrizze az elrsi utat s a jogosultsgokat!\n" + "Mappa: "
                            + exportFolder.getAbsolutePath(),
                    "Informci", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        List<File> xmlFiles = app.getXMLFiles(importFolder);
        if (xmlFiles == null || xmlFiles.isEmpty()) {
            JOptionPane.showMessageDialog(null,
                    "Nincs beolvasand XML fjl!\n" + "Mappa: " + importFolder.getAbsolutePath(),
                    "Informci", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        StringBuilder fileList = new StringBuilder();
        xmlFiles.stream().forEach(xml -> fileList.append("\n").append(xml.getName()));
        int ret = JOptionPane.showConfirmDialog(null,
                "Beolvassra elksztett fjlok:\n" + fileList + "\n\nIndulhat a feldolgozs?",
                "Megtallt XML fjlok", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

        if (ret == JOptionPane.OK_OPTION) {
            String csvName = "tranzakcio_lista_" + df.format(new Date()) + "_" + System.currentTimeMillis()
                    + ".csv";
            File csv = new File(DEFAULT_EXPORT_FOLDER + "/" + csvName);
            app.writeCSV(csv, Arrays.asList(app.getHeaderLine()));
            xmlFiles.stream().forEach(xml -> {
                List<String> lines = app.readXMLData(xml);
                if (lines != null)
                    app.writeCSV(csv, lines);
            });
            if (csv.isFile() && csv.exists()) {
                JOptionPane.showMessageDialog(null,
                        "A CSV fjl sikeresen elllt!\n" + "Fjl: " + csv.getAbsolutePath(),
                        "Informci", JOptionPane.INFORMATION_MESSAGE);
                app.openFile(csv);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Feldolgozs megszaktva!", "Informci",
                    JOptionPane.INFORMATION_MESSAGE);
        }

    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Nem kezelt kivtel!\n" + ExceptionUtils.getStackTrace(ex), "Hiba",
                JOptionPane.ERROR_MESSAGE);
    }

}