Example usage for java.util.logging FileHandler setLevel

List of usage examples for java.util.logging FileHandler setLevel

Introduction

In this page you can find the example usage for java.util.logging FileHandler setLevel.

Prototype

public synchronized void setLevel(Level newLevel) throws SecurityException 

Source Link

Document

Set the log level specifying which message levels will be logged by this Handler .

Usage

From source file:com.flagleader.builder.FlagLeader.java

public static void main(String[] paramArrayOfString) {
    Shell localShell = new Shell(16777216);
    localShell.setLocation(new Point(300, 200));
    localShell.setLayout(new FillLayout());
    Composite localComposite = new Composite(localShell, 0);
    localComposite.setLayout(new FillLayout());
    Label localLabel = new Label(localComposite, 0);
    Image localImage = ImageDescriptor
            .createFromURL(localShell.getClass().getClassLoader().getResource("icons/start.jpg")).createImage();
    localLabel.setImage(localImage);/*from   w  w w. j  a v  a2s .  c  o  m*/
    localShell.setSize(400, 300);
    localShell.setText("Visual Rules Solution");
    localShell.open();
    Init.a();
    String str = null;
    if (BuilderConfig.getInstance().isLoadDefault())
        str = RuleRepository.DEFAULTEXT;
    if (paramArrayOfString.length > 0)
        str = "";
    for (int i = 0; i < paramArrayOfString.length; i++)
        str = str + paramArrayOfString[i] + " ";
    Logger localLogger = Logger.getLogger("ruleengine");
    Object localObject;
    try {
        new File(SystemUtils.USER_HOME + File.separator + ".visualrules" + File.separator + "logs").mkdirs();
        FileHandler localFileHandler = new FileHandler(SystemUtils.USER_HOME + File.separator + ".visualrules"
                + File.separator + "logs" + File.separator + "logfile%u.%g.txt", 0, 10);
        localFileHandler.setFormatter(new com.flagleader.server.c());
        localFileHandler.setLevel(Level.ALL);
        Logger.getLogger("flagleader").addHandler(localFileHandler);
        localLogger.addHandler(localFileHandler);
    } catch (Exception localException1) {
        if (!b) {
            localObject = new ConsoleHandler();
            ((ConsoleHandler) localObject).setFormatter(new com.flagleader.server.c());
            ((ConsoleHandler) localObject).setLevel(Level.ALL);
            Logger.getLogger("flagleader").addHandler((Handler) localObject);
            localLogger.addHandler((Handler) localObject);
        }
    }
    if (!BuilderManager.checkLicense()) {
        localImage.dispose();
        localShell.dispose();
        return;
    }
    Property.getInstance().setEngineImplement("com.flagleader.engine.impl.SingleRuleEngineFactory");
    FlagLeader localFlagLeader = new FlagLeader();
    Property.getInstance().setUpdateInternateTime(0L);
    localFlagLeader.setBlockOnOpen(true);
    localFlagLeader.builderManager = new BuilderManager(localFlagLeader);
    if ((com.flagleader.manager.d.c.a("needLogin", false)) || (BuilderConfig.getInstance().isFirstLogin()))
        try {
            localObject = localFlagLeader.builderManager.getUserServer();
            if ((localObject == null) || (((String) localObject).length() == 0)
                    || (localFlagLeader.builderManager.getUserType() == 0)
                    || (localFlagLeader.builderManager.getUserid() == 0)) {
                localImage.dispose();
                localShell.dispose();
                return;
            }
        } catch (Exception localException2) {
            MessageDialog.openError(null, "",
                    ResourceTools.getMessage("loginserver.error") + localException2.getLocalizedMessage());
            localImage.dispose();
            localShell.dispose();
            return;
        }
    if ((str != null) && (new File(str).exists()))
        localFlagLeader.builderManager.getRulesManager().a(new File(str));
    localFlagLeader.initWindow();
    if (new File(SystemUtils.JAVA_IO_TMPDIR, "engine.jar").exists())
        new File(SystemUtils.JAVA_IO_TMPDIR, "engine.jar").delete();
    if (new File(SystemUtils.JAVA_IO_TMPDIR, "export.jar").exists())
        new File(SystemUtils.JAVA_IO_TMPDIR, "export.jar").delete();
    if (BuilderConfig.getInstance().isAutosave())
        new com.flagleader.builder.d.c(localFlagLeader.builderManager).b();
    if (BuilderConfig.getInstance().isAutoCheckVersion())
        new a(localFlagLeader.builderManager).b();
    new e().b();
    localImage.dispose();
    localShell.dispose();
    localFlagLeader.open();
    BuilderManager localBuilderManager = localFlagLeader.builderManager;
    localFlagLeader.getShell().addShellListener(new d(localBuilderManager));
}

From source file:core.PlanC.java

/**
 * inicio de aplicacion/*  ww w  .  j av a 2s.co  m*/
 * 
 * @param arg - argumentos de entrada
 */
public static void main(String[] args) {

    // user.name

    /*
     * Properties prp = System.getProperties(); System.out.println(getWmicValue("bios", "SerialNumber"));
     * System.out.println(getWmicValue("cpu", "SystemName"));
     */

    try {
        // log
        // -Djava.util.logging.SimpleFormatter.format='%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n'
        // System.setProperty("java.util.logging.SimpleFormatter.format",
        // "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n");
        System.setProperty("java.util.logging.SimpleFormatter.format",
                "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %5$s%6$s%n");

        FileHandler fh = new FileHandler(LOG_FILE);
        fh.setFormatter(new SimpleFormatter());
        fh.setLevel(Level.INFO);
        ConsoleHandler ch = new ConsoleHandler();
        ch.setFormatter(new SimpleFormatter());
        ch.setLevel(Level.INFO);
        logger = Logger.getLogger("");
        Handler[] hs = logger.getHandlers();
        for (int x = 0; x < hs.length; x++) {
            logger.removeHandler(hs[x]);
        }
        logger.addHandler(fh);
        logger.addHandler(ch);
        // point apache log to this log
        System.setProperty("org.apache.commons.logging.Log", Jdk14Logger.class.getName());

        TPreferences.init();
        TStringUtils.init();

        Font fo = Font.createFont(Font.TRUETYPE_FONT, TResourceUtils.getFile("Dosis-Light.ttf"));
        GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(fo);
        fo = Font.createFont(Font.TRUETYPE_FONT, TResourceUtils.getFile("Dosis-Medium.ttf"));
        GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(fo);
        fo = Font.createFont(Font.TRUETYPE_FONT, TResourceUtils.getFile("AERO_ITALIC.ttf"));
        GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(fo);

        SwingTimerTimingSource ts = new SwingTimerTimingSource();
        AnimatorBuilder.setDefaultTimingSource(ts);
        ts.init();

        // parse app argument parameters and append to tpreferences to futher uses
        for (String arg : args) {
            String[] kv = arg.split("=");
            TPreferences.setProperty(kv[0], kv[1]);
        }
        RUNNING_MODE = TPreferences.getProperty("runningMode", RM_NORMAL);

        newMsg = Applet.newAudioClip(TResourceUtils.getURL("newMsg.wav"));

    } catch (Exception e) {
        SystemLog.logException1(e, true);
    }

    // pass icon from metal to web look and feel
    Icon i1 = UIManager.getIcon("OptionPane.errorIcon");
    Icon i2 = UIManager.getIcon("OptionPane.informationIcon");
    Icon i3 = UIManager.getIcon("OptionPane.questionIcon");
    Icon i4 = UIManager.getIcon("OptionPane.warningIcon");
    // Object fcui = UIManager.get("FileChooserUI");
    // JFileChooser fc = new JFileChooser();

    WebLookAndFeel.install();
    // WebLookAndFeel.setDecorateFrames(true);
    // WebLookAndFeel.setDecorateDialogs(true);

    UIManager.put("OptionPane.errorIcon", i1);
    UIManager.put("OptionPane.informationIcon", i2);
    UIManager.put("OptionPane.questionIcon", i3);
    UIManager.put("OptionPane.warningIcon", i4);
    // UIManager.put("TFileChooserUI", fcui);

    // warm up the IDW.
    // in my computer, some weird error ocurr if i don't execute this preload.
    new RootWindow(null);

    frame = new TWebFrame();
    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            Exit.shutdown();
        }
    });

    if (RUNNING_MODE.equals(RM_NORMAL)) {
        initEnviorement();
    }
    if (RUNNING_MODE.equals(RM_CONSOLE)) {
        initConsoleEnviorement();
    }

    if (RUNNING_MODE.equals(ONE_TASK)) {
        String cln = TPreferences.getProperty("taskName", "*TaskNotFound");
        PlanC.logger.log(Level.INFO, "OneTask parameter found in .properties. file Task name = " + cln);
        try {
            Class cls = Class.forName(cln);
            Object dobj = cls.newInstance();
            // new class must be extends form AbstractExternalTask
            TTaskManager.executeTask((Runnable) dobj);
            return;
        } catch (Exception e) {
            PlanC.logger.log(Level.SEVERE, e.getMessage(), e);
            Exit.shutdown();
        }
    }
}

From source file:Logi.GSeries.Service.LogiGSKService.java

/**
 * @param args the command line arguments
 *//*from  www  . j  a va2s  . c  om*/
public static void main(String[] args) {
    SystemTray.DEBUG = false;

    Settings settings;
    if (IOOperations.currentSettingsExist()) {
        settings = IOOperations.loadCurrentSettingsObjectFromFile();
    } else {
        settings = new Settings();
    }

    LogiGSKService l = new LogiGSKService();
    if (settings.getShowSystemTray()) {
        l.showSystemTray();
    } else {
        l.hideSystemTray();
    }
    l.begin();
    try {
        String dataFolderPath = IOOperations.getLocalDataDirectoryPath();
        File dataFolder = new File(dataFolderPath);
        if (!dataFolder.exists()) {
            dataFolder.mkdir();
        }
        String logFolderPath = IOOperations.getLogDirectoryPath();
        File logFolder = new File(logFolderPath);
        if (!logFolder.exists()) {
            logFolder.mkdir();
        }
        FileHandler fileHandler = new FileHandler(logFolderPath + "LogiGSK.log", FILE_SIZE, 3);
        fileHandler.setLevel(Level.ALL);
        logger.setLevel(Level.ALL);
        logger.addHandler(fileHandler);
    } catch (IOException | SecurityException ex) {
        Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex);
    }
    int clientNumber = 0;
    ServerSocket listener = null;
    PropertyConfigurator.configure(LogiGSKService.class.getResource("/Logi/GSeries/Service/log4j.properties"));
    reloading = true;
    boolean firstTime = true;
    while (reloading) {
        listener = null;
        if (reloading && !firstTime) {
            if (IOOperations.currentSettingsExist()) {
                settings = IOOperations.loadCurrentSettingsObjectFromFile();
            } else {
                settings = new Settings();
            }
        }
        firstTime = false;
        reloading = false;
        running = true;
        try {
            listener = new ServerSocket(settings.getPort(), 0, InetAddress.getByName(null));
            while (running) {
                new Manager(listener.accept(), clientNumber++, logger).start();
            }
        } catch (IOException ex) {
            Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (listener != null) {
                try {
                    listener.close();
                } catch (IOException ex) {
                    Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}

From source file:havocx42.Program.java

private static void initRootLogger() throws SecurityException, IOException {

    FileHandler fileHandler;
    fileHandler = new FileHandler("PRWeaponStats.%u.%g.txt", 1024 * 1024 * 8, 3, false);
    fileHandler.setLevel(Level.FINEST);
    fileHandler.setFormatter(new SimpleFormatter());
    Logger rootLogger = Logger.getLogger("");
    Handler[] handlers = rootLogger.getHandlers();
    for (Handler handler : handlers) {
        handler.setLevel(Level.INFO);
    }//from w  ww .  j ava2  s.  c  o  m
    rootLogger.setLevel(Level.FINEST);
    rootLogger.addHandler(fileHandler);
}

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

/**
 * Initiates logging/*from  www. j a  va 2s  .  c  o m*/
 *
 * @throws IOException
 */
private static void initLogging() throws IOException {
    FileHandler fh = new FileHandler(galaxyFileName + ".log");
    fh.setLevel(LOG.getLevel());
    Formatter logFormat = new Formatter() {

        @Override
        public String format(LogRecord rec) {
            StringBuilder buf = new StringBuilder(200);
            buf.append("#");
            buf.append(new java.util.Date());
            buf.append(' ');
            buf.append(rec.getLevel());
            buf.append(' ');
            buf.append(rec.getSourceClassName()).append(".").append(rec.getSourceMethodName());
            buf.append(":\n");
            buf.append(formatMessage(rec));
            buf.append('\n');
            return buf.toString();
        }
    };
    fh.setFormatter(logFormat);

    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(LOG.getLevel());
    Formatter conlogFormat = new Formatter() {
        @Override
        public String format(LogRecord rec) {
            StringBuilder buf = new StringBuilder(200);
            buf.append(rec.getLevel());
            buf.append(": ");
            buf.append(formatMessage(rec));
            buf.append('\n');
            return buf.toString();
        }
    };
    ch.setFormatter(conlogFormat);

    LOG.addHandler(fh);
    LOG.addHandler(ch);
}

From source file:net.nharyes.drivecopy.Main.java

public Main(String[] args) {

    // compose options
    composeOptions();/*from   www.j a v a  2s.  co m*/

    // create the command line parser
    CommandLineParser parser = new PosixParser();

    try {

        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        // check log option
        if (line.hasOption('L')) {

            // add file handler
            FileHandler handler = new FileHandler(line.getOptionValue('L'));
            handler.setLevel(Level.FINE);
            Logger.getLogger(getClass().getPackage().getName()).addHandler(handler);
            logger.info(String.format("Added log output file '%s'", line.getOptionValue('L')));
        }

        // check arguments number
        if (line.getArgs().length == 0)
            throw new ParseException("Missing argument MODE");

        // check mode
        int action = -1;
        if (line.getArgs()[0].equals("upload"))
            action = FileStorageWorkflowManager.ACTION_UPLOAD;
        else if (line.getArgs()[0].equals("download"))
            action = FileStorageWorkflowManager.ACTION_DOWNLOAD;
        else if (line.getArgs()[0].equals("replace"))
            action = FileStorageWorkflowManager.ACTION_REPLACE;
        if (action == -1)
            throw new ParseException("MODE must be 'download', 'replace' or 'upload'.");

        // compose BO
        FileBO fileBO = new FileBO();

        // check directory
        char c = 'f';
        fileBO.setDirectory(false);
        if (line.hasOption('d')) {

            c = 'd';
            fileBO.setDirectory(true);
        }
        fileBO.setFile(new File(line.getOptionValue(c)));

        // entry name
        if (line.getArgs().length == 2) {

            // check slashes
            String name = line.getArgs()[1];
            if (name.startsWith("/"))
                name = name.substring(1);
            if (name.endsWith("/"))
                name += "Untitled";
            fileBO.setName(name);

        } else
            fileBO.setName(fileBO.getFile().getName());

        // compression level
        fileBO.setCompressionLevel(Integer.parseInt(line.getOptionValue('l', "0")));

        // check delete after operation
        fileBO.setDeleteAfter(false);
        if (line.hasOption('D'))
            fileBO.setDeleteAfter(true);

        // check skip revision
        fileBO.setSkipRevision(false);
        if (line.hasOption('s'))
            fileBO.setSkipRevision(true);

        // MIME type
        if (line.hasOption('m'))
            fileBO.setMimeType(line.getOptionValue('m'));

        // check MD5 comparison
        fileBO.setCheckMd5(false);
        if (line.hasOption('c'))
            fileBO.setCheckMd5(true);

        // check force
        fileBO.setForce(false);
        if (line.hasOption('F'))
            fileBO.setForce(true);

        // check tree
        fileBO.setCreateFolders(false);
        if (line.hasOption('t'))
            fileBO.setCreateFolders(true);

        // get Workflow Manager
        Injector injector;
        if (line.hasOption('C'))
            injector = Guice.createInjector(new MainModule(line.getOptionValue('C')));
        else
            injector = Guice.createInjector(new MainModule(CONFIGURATION_FILE));
        FileStorageWorkflowManager wfm = injector.getInstance(FileStorageWorkflowManager.class);

        // execute workflow
        wfm.handleWorkflow(fileBO, action);

    } catch (ParseException ex) {

        // print help
        HelpFormatter formatter = new HelpFormatter();
        System.out.println("Drive Copy version " + VERSION);
        System.out.println("Copyright 2012-2013 Luca Zanconato (luca.zanconato@nharyes.net)");
        System.out.println();
        formatter.printHelp("java -jar " + JAR_FILE + " [OPTIONS] <MODE> [ENTRY]", DESCRIPTION + "\n", options,
                "\nMODE can be download/replace/upload.\nENTRY is the path of the entry in Google Drive (i.e. \"Test Folder/Another Folder/file.txt\"); if not set, the name of the local file/directory will be used.");
        System.out.println();

        // log exception
        logger.log(Level.SEVERE, ex.getMessage(), ex);

        // exit with error
        System.exit(1);

    } catch (WorkflowManagerException ex) {

        // log exception
        logger.log(Level.SEVERE, ex.getMessage(), ex);

        // exit with error
        System.exit(1);

    } catch (IOException ex) {

        // log exception
        logger.log(Level.SEVERE, ex.getMessage(), ex);

        // exit with error
        System.exit(1);

    } catch (Exception ex) {

        // log exception
        logger.log(Level.SEVERE, ex.getMessage(), ex);

        // exit with error
        System.exit(1);
    }
}

From source file:com.yahoo.dba.perf.myperf.common.MyPerfContext.java

private void configureLogging() {
    Logger logger = Logger.getLogger("");
    try {/*from ww  w  . j ava 2s.  co  m*/
        logger.setLevel(Level.parse(getLogLevel()));
    } catch (Exception ex) {
        logger.setLevel(Level.INFO);
    }
    try {
        for (Handler h : logger.getHandlers()) {
            if (h instanceof java.util.logging.ConsoleHandler)
                h.setLevel(Level.SEVERE);
        }
        String logRoot = System.getProperty("logPath", ".");

        java.util.logging.FileHandler fileHandler = new java.util.logging.FileHandler(
                logRoot + File.separatorChar + getLogPath(), this.logFileSize, this.logFileCount);
        fileHandler.setLevel(logger.getLevel());
        fileHandler.setFormatter(new SimpleFormatter());
        logger.addHandler(fileHandler);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:eu.asterics.mw.services.AstericsErrorHandling.java

/**
 * This method creates the logger. Actually there are 4 types of loggers: 
 * "severe": logs fatal errors i.e. errors that prevent the ARE from functioning
 * "warning": logs errors other than fatal e.g. component errors
 * "info": logs informative messages/*from w  w w .  java 2  s .c  om*/
 * "fine": logs debugging messages
 * 
 * Each logger by default also logs all messages with severity level higher than its own. 
 * E.g. the warning logger logs warning and severe messages, the info logger logs info, 
 * warning and severe messages etc. The same applies to the consoleHandler, i.e. by 
 * setting its level to info, the console will also print severe and warning messages 
 * along with info messages
 */
public Logger getLogger() {
    if (logger == null) {
        logger = Logger.getLogger("AstericsLogger");

        FileHandler warningFileHandler, severeFileHandler, infoFileHandler, fineFileHandler;
        ConsoleHandler consoleHandler;
        try {
            //cleanup before starting:
            logger.setUseParentHandlers(false);

            // remove and handlers that will be replaced
            Handler[] handlers = logger.getHandlers();
            for (Handler handler : handlers) {
                if (handler.getClass() == ConsoleHandler.class)
                    logger.removeHandler(handler);
            }

            File logFolder = new File(System.getProperty(LOG_PATH_PROPERTY, ResourceRegistry.TMP_FOLDER));
            if (!logFolder.exists()) {
                FileUtils.forceMkdir(logFolder);
            }
            //Create handlers
            severeFileHandler = new FileHandler(new File(logFolder, "asterics_logger_severe.log").getPath(),
                    true);
            warningFileHandler = new FileHandler(new File(logFolder, "asterics_logger_warning.log").getPath(),
                    true);
            infoFileHandler = new FileHandler(new File(logFolder, "asterics_logger.log").getPath(), true);
            fineFileHandler = new FileHandler(new File(logFolder, "asterics_logger_fine.log").getPath(), true);
            consoleHandler = new ConsoleHandler();

            //Set report level of handlers
            severeFileHandler.setLevel(Level.SEVERE);
            warningFileHandler.setLevel(Level.WARNING);
            infoFileHandler.setLevel(Level.INFO);
            fineFileHandler.setLevel(Level.FINE);

            //The consoleHandler prints log messaged to the console. Its 
            //severety level can be adjusted accordingly. 
            String level = getLoggerLevel();
            switch (level) {
            case "INFO":
                consoleHandler.setLevel(Level.INFO);
                break;
            case "WARNING":
                consoleHandler.setLevel(Level.WARNING);
                break;
            case "FINE":
                consoleHandler.setLevel(Level.FINE);
                break;
            case "SEVERE":
                consoleHandler.setLevel(Level.SEVERE);
                break;

            default:
                consoleHandler.setLevel(Level.INFO);
                break;
            }

            //Add handlers to the logger
            logger.addHandler(warningFileHandler);
            logger.addHandler(severeFileHandler);
            logger.addHandler(infoFileHandler);
            logger.addHandler(fineFileHandler);
            logger.addHandler(consoleHandler);

            //Create formatters for the handlers (optional)
            severeFileHandler.setFormatter(new SimpleFormatter());
            warningFileHandler.setFormatter(new SimpleFormatter());
            infoFileHandler.setFormatter(new SimpleFormatter());
            fineFileHandler.setFormatter(new SimpleFormatter());
            consoleHandler.setFormatter(new SimpleFormatter());

            logger.setLevel(Level.ALL);
            logger.setUseParentHandlers(false);

        } catch (SecurityException e) {
            System.out.println(AstericsErrorHandling.class.getName() + ": Error creating AstericsLogger: "
                    + e.getMessage());
        } catch (IOException e) {
            //logger.warning(this.getClass().getName()+
            //   ": Error creating AstericsLogger: "+e.getMessage());
            System.out.println(AstericsErrorHandling.class.getName() + ": Error creating AstericsLogger: "
                    + e.getMessage());
        }
    }

    return logger;
}

From source file:net.tradelib.apps.StrategyBacktest.java

public static void run(Strategy strategy) throws Exception {
    // Setup the logging
    System.setProperty("java.util.logging.SimpleFormatter.format",
            "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS: %4$s: %5$s%n%6$s%n");
    LogManager.getLogManager().reset();
    Logger rootLogger = Logger.getLogger("");
    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("file.log", "true"))) {
        FileHandler logHandler = new FileHandler("diag.out", 8 * 1024 * 1024, 2, true);
        logHandler.setFormatter(new SimpleFormatter());
        logHandler.setLevel(Level.FINEST);
        rootLogger.addHandler(logHandler);
    }/*from  www  .j  a va 2 s . c  o  m*/

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("console.log", "true"))) {
        ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setFormatter(new SimpleFormatter());
        consoleHandler.setLevel(Level.INFO);
        rootLogger.addHandler(consoleHandler);
    }

    rootLogger.setLevel(Level.INFO);

    // Setup Hibernate
    // Configuration configuration = new Configuration();
    // StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    // SessionFactory factory = configuration.buildSessionFactory(builder.build());

    Context context = new Context();
    context.dbUrl = BacktestCfg.instance().getProperty("db.url");

    HistoricalDataFeed hdf = new SQLDataFeed(context);
    hdf.configure(BacktestCfg.instance().getProperty("datafeed.config", "config/datafeed.properties"));
    context.historicalDataFeed = hdf;

    HistoricalReplay hr = new HistoricalReplay(context);
    context.broker = hr;

    strategy.initialize(context);
    strategy.cleanupDb();

    long start = System.nanoTime();
    strategy.start();
    long elapsedTime = System.nanoTime() - start;
    System.out.println("backtest took " + String.format("%.2f secs", (double) elapsedTime / 1e9));

    start = System.nanoTime();
    strategy.updateEndEquity();
    strategy.writeExecutionsAndTrades();
    strategy.writeEquity();
    elapsedTime = System.nanoTime() - start;
    System.out
            .println("writing to the database took " + String.format("%.2f secs", (double) elapsedTime / 1e9));

    System.out.println();

    // Write the strategy totals to the database
    strategy.totalTradeStats();

    // Write the strategy report to the database and obtain the JSON
    // for writing it to the console.
    JsonObject report = strategy.writeStrategyReport();

    JsonArray asa = report.getAsJsonArray("annual_stats");

    String csvPath = BacktestCfg.instance().getProperty("positions.csv.prefix");
    if (!Strings.isNullOrEmpty(csvPath)) {
        csvPath += "-" + strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE)
                + ".csv";
    }

    String ordersCsvPath = BacktestCfg.instance().getProperty("orders.csv.suffix");
    if (!Strings.isNullOrEmpty(ordersCsvPath)) {
        ordersCsvPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-"
                + strategy.getName() + ordersCsvPath;
    }

    String actionsPath = BacktestCfg.instance().getProperty("actions.file.suffix");
    if (!Strings.isNullOrEmpty(actionsPath)) {
        actionsPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-"
                + strategy.getName() + actionsPath;
    }

    // If emails are being send out
    String signalText = StrategyText.build(context.dbUrl, strategy.getName(),
            strategy.getLastTimestamp().toLocalDate(), "   ", csvPath, '|');

    System.out.println(signalText);
    System.out.println();

    if (!Strings.isNullOrEmpty(ordersCsvPath)) {
        StrategyText.buildOrdersCsv(context.dbUrl, strategy.getName(),
                strategy.getLastTimestamp().toLocalDate(), ordersCsvPath);
    }

    File actionsFile = Strings.isNullOrEmpty(actionsPath) ? null : new File(actionsPath);

    if (actionsFile != null) {
        FileUtils.writeStringToFile(actionsFile,
                signalText + System.getProperty("line.separator") + System.getProperty("line.separator"));
    }

    String message = "";

    if (asa.size() > 0) {
        // Sort the array
        TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
        for (int ii = 0; ii < asa.size(); ++ii) {
            int year = asa.get(ii).getAsJsonObject().get("year").getAsInt();
            map.put(year, ii);
        }

        for (int id : map.values()) {
            JsonObject jo = asa.get(id).getAsJsonObject();
            String yearStr = String.valueOf(jo.get("year").getAsInt());
            String pnlStr = String.format("$%,d", jo.get("pnl").getAsInt());
            String pnlPctStr = String.format("%.2f%%", jo.get("pnl_pct").getAsDouble());
            String endEqStr = String.format("$%,d", jo.get("end_equity").getAsInt());
            String ddStr = String.format("$%,d", jo.get("maxdd").getAsInt());
            String ddPctStr = String.format("%.2f%%", jo.get("maxdd_pct").getAsDouble());
            String str = yearStr + " PnL: " + pnlStr + ", PnL Pct: " + pnlPctStr + ", End Equity: " + endEqStr
                    + ", MaxDD: " + ddStr + ", Pct MaxDD: " + ddPctStr;
            message += str + "\n";
        }

        String pnlStr = String.format("$%,d", report.get("pnl").getAsInt());
        String pnlPctStr = String.format("%.2f%%", report.get("pnl_pct").getAsDouble());
        String ddStr = String.format("$%,d", report.get("avgdd").getAsInt());
        String ddPctStr = String.format("%.2f%%", report.get("avgdd_pct").getAsDouble());
        String gainToPainStr = String.format("%.4f", report.get("gain_to_pain").getAsDouble());
        String str = "\nAvg PnL: " + pnlStr + ", Pct Avg PnL: " + pnlPctStr + ", Avg DD: " + ddStr
                + ", Pct Avg DD: " + ddPctStr + ", Gain to Pain: " + gainToPainStr;
        message += str + "\n";
    } else {
        message += "\n";
    }

    // Global statistics
    JsonObject jo = report.getAsJsonObject("total_peak");
    String dateStr = jo.get("date").getAsString();
    int maxEndEq = jo.get("equity").getAsInt();
    jo = report.getAsJsonObject("total_maxdd");
    double cash = jo.get("cash").getAsDouble();
    double pct = jo.get("pct").getAsDouble();
    message += "\n" + "Total equity peak [" + dateStr + "]: " + String.format("$%,d", maxEndEq) + "\n"
            + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n";

    if (report.has("latest_peak") && report.has("latest_maxdd")) {
        jo = report.getAsJsonObject("latest_peak");
        LocalDate ld = LocalDate.parse(jo.get("date").getAsString(), DateTimeFormatter.ISO_DATE);
        maxEndEq = jo.get("equity").getAsInt();
        jo = report.getAsJsonObject("latest_maxdd");
        cash = jo.get("cash").getAsDouble();
        pct = jo.get("pct").getAsDouble();
        message += "\n" + Integer.toString(ld.getYear()) + " equity peak ["
                + ld.format(DateTimeFormatter.ISO_DATE) + "]: " + String.format("$%,d", maxEndEq) + "\n"
                + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n";
    }

    message += "\n" + "Avg Trade PnL: "
            + String.format("$%,d", Math.round(report.get("avg_trade_pnl").getAsDouble())) + ", Max DD: "
            + String.format("$%,d", Math.round(report.get("maxdd").getAsDouble())) + ", Max DD Pct: "
            + String.format("%.2f%%", report.get("maxdd_pct").getAsDouble()) + ", Num Trades: "
            + Integer.toString(report.get("num_trades").getAsInt());

    System.out.println(message);

    if (actionsFile != null) {
        FileUtils.writeStringToFile(actionsFile, message + System.getProperty("line.separator"), true);
    }

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("email.enabled", "false"))) {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.sendgrid.net");
        props.put("mail.smtp.port", "587");

        String user = BacktestCfg.instance().getProperty("email.user");
        String pass = BacktestCfg.instance().getProperty("email.pass");

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, pass);
            }
        });

        MimeMessage msg = new MimeMessage(session);
        try {
            msg.setFrom(new InternetAddress(BacktestCfg.instance().getProperty("email.from")));
            msg.addRecipients(RecipientType.TO, BacktestCfg.instance().getProperty("email.recipients"));
            msg.setSubject(strategy.getName() + " Report ["
                    + strategy.getLastTimestamp().format(DateTimeFormatter.ISO_LOCAL_DATE) + "]");
            msg.setText("Positions & Signals\n" + signalText + "\n\nStatistics\n" + message);
            Transport.send(msg);
        } catch (Exception ee) {
            Logger.getLogger("").warning(ee.getMessage());
        }
    }

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("sftp.enabled", "false"))) {
        HashMap<String, String> fileMap = new HashMap<String, String>();
        if (!Strings.isNullOrEmpty(actionsPath))
            fileMap.put(actionsPath, actionsPath);
        if (!Strings.isNullOrEmpty(ordersCsvPath))
            fileMap.put(ordersCsvPath, ordersCsvPath);
        String user = BacktestCfg.instance().getProperty("sftp.user");
        String pass = BacktestCfg.instance().getProperty("sftp.pass");
        String host = BacktestCfg.instance().getProperty("sftp.host");
        SftpUploader sftp = new SftpUploader(host, user, pass);
        sftp.upload(fileMap);
    }
}

From source file:org.azrul.langmera.DecisionService.java

public static void main(String[] args) throws IOException {
    ConfigurationProvider config = null;
    ConfigFilesProvider configFilesProvider = () -> Arrays.asList(Paths.get("config.properties"));
    if (args.length <= 0) {
        ConfigurationSource source = new ClasspathConfigurationSource(configFilesProvider);
        config = new ConfigurationProviderBuilder().withConfigurationSource(source).build();
    } else {/* w w w  .j  a v a2s . c  o m*/
        ConfigurationSource source = new FilesConfigurationSource(configFilesProvider);
        Environment environment = new ImmutableEnvironment(args[0]);
        config = new ConfigurationProviderBuilder().withConfigurationSource(source).withEnvironment(environment)
                .build();

    }
    Logger logger = null;
    if (config.getProperty("log.file", String.class).isEmpty() == false) {
        FileHandler logHandler = new FileHandler(config.getProperty("log.file", String.class),
                config.getProperty("log.sizePerFile", Integer.class) * 1024 * 1024,
                config.getProperty("log.maxFileCount", Integer.class), true);
        logHandler.setFormatter(new SimpleFormatter());
        logHandler.setLevel(Level.INFO);

        Logger rootLogger = Logger.getLogger("");
        rootLogger.removeHandler(rootLogger.getHandlers()[0]);
        logHandler.setLevel(Level.parse(config.getProperty("log.level", String.class)));
        rootLogger.setLevel(Level.parse(config.getProperty("log.level", String.class)));
        rootLogger.addHandler(logHandler);

        logger = rootLogger;
    } else {
        logger = Logger.getGlobal();
    }

    VertxOptions options = new VertxOptions();
    options.setMaxEventLoopExecuteTime(Long.MAX_VALUE);
    options.setWorkerPoolSize(config.getProperty("workerPoolSize", Integer.class));
    options.setEventLoopPoolSize(40);

    Vertx vertx = Vertx.vertx(options);
    vertx.deployVerticle(new DecisionService(logger, config));
    vertx.deployVerticle(new SaveToDB(logger, config));

}