Example usage for java.util.logging Handler setFormatter

List of usage examples for java.util.logging Handler setFormatter

Introduction

In this page you can find the example usage for java.util.logging Handler setFormatter.

Prototype

public synchronized void setFormatter(Formatter newFormatter) throws SecurityException 

Source Link

Document

Set a Formatter .

Usage

From source file:MainClass.java

public static void main(String[] args) {
    logger.setUseParentHandlers(false);//from  w w w .j a va 2s  . co  m
    Handler conHdlr = new ConsoleHandler();
    conHdlr.setFormatter(new Formatter() {
        public String format(LogRecord record) {
            return record.getLevel() + "  :  " + record.getSourceClassName() + " -:- "
                    + record.getSourceMethodName() + " -:- " + record.getMessage() + "\n";
        }
    });
    logger.addHandler(conHdlr);
    logMessages();
}

From source file:com.versusoft.packages.jodl.gui.CommandLineGUI.java

public static void main(String args[]) throws SAXException, IOException {

    Handler fh = new FileHandler(LOG_FILENAME_PATTERN);
    fh.setFormatter(new SimpleFormatter());

    //removeAllLoggersHandlers(Logger.getLogger(""));
    Logger.getLogger("").addHandler(fh);
    Logger.getLogger("").setLevel(Level.FINEST);

    Options options = new Options();

    Option option1 = new Option("in", "ODT file (required)");
    option1.setRequired(true);/*from   www.  ja va2s  .  c o  m*/
    option1.setArgs(1);

    Option option2 = new Option("out", "Output file (required)");
    option2.setRequired(false);
    option2.setArgs(1);

    Option option3 = new Option("pic", "extract pics");
    option3.setRequired(false);
    option3.setArgs(1);

    Option option4 = new Option("page", "enable pagination processing");
    option4.setRequired(false);
    option4.setArgs(0);

    options.addOption(option1);
    options.addOption(option2);
    options.addOption(option3);
    options.addOption(option4);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        printHelp();
        return;
    }

    if (cmd.hasOption("help")) {
        printHelp();
        return;
    }

    File outFile = new File(cmd.getOptionValue("out"));

    OdtUtils utils = new OdtUtils();

    utils.open(cmd.getOptionValue("in"));
    //utils.correctionStep();
    utils.saveXML(outFile.getAbsolutePath());

    try {

        if (cmd.hasOption("page")) {
            OdtUtils.paginationProcessing(outFile.getAbsolutePath());
        }

        OdtUtils.correctionProcessing(outFile.getAbsolutePath());

    } catch (ParserConfigurationException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (TransformerConfigurationException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (TransformerException ex) {
        logger.log(Level.SEVERE, null, ex);
    }

    if (cmd.hasOption("pic")) {

        String imageDir = cmd.getOptionValue("pic");
        if (!imageDir.endsWith("/")) {
            imageDir += "/";
        }

        try {

            String basedir = new File(cmd.getOptionValue("out")).getParent().toString()
                    + System.getProperty("file.separator");
            OdtUtils.extractAndNormalizeEmbedPictures(cmd.getOptionValue("out"), cmd.getOptionValue("in"),
                    basedir, imageDir);
        } catch (SAXException ex) {
            logger.log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            logger.log(Level.SEVERE, null, ex);
        } catch (TransformerConfigurationException ex) {
            logger.log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }

}

From source file:MainClass.java

public static void main(String args[]) {

    Logger logger = Logger.getLogger("my.log");

    Handler handler = null;

    try {//from www.  ja  v a2 s  .c  om
        handler = new FileHandler("messages.log");
    } catch (IOException e) {
        System.out.println("Could not create file. Using the console handler");
        handler = new ConsoleHandler();
    }

    logger.addHandler(handler);

    handler.setFormatter(new XMLFormatter());

    logger.info("Our first logging message");
    logger.severe("Something terrible happened");
}

From source file:org.archive.crawler.processor.recrawl.PersistProcessor.java

/**
 * Utility main for importing a log into a BDB-JE environment or moving a
 * database between environments (2 arguments), or simply dumping a log
 * to stderr in a more readable format (1 argument). 
 * //from w  w  w . ja v  a 2 s .  co m
 * @param args command-line arguments
 * @throws DatabaseException
 * @throws IOException
 */
public static void main(String[] args) throws DatabaseException, IOException {
    Handler handler = new ConsoleHandler();
    handler.setLevel(Level.ALL);
    handler.setFormatter(new OneLineSimpleLogger());
    logger.addHandler(handler);
    logger.setUseParentHandlers(false);

    if (args.length == 2) {
        logger.setLevel(Level.INFO);
        populatePersistEnv(args[0], new File(args[1]));
    } else if (args.length == 1) {
        logger.setLevel(Level.FINE);
        populatePersistEnv(args[0], null);
    } else {
        System.out.println("Arguments: ");
        System.out.println("    source [target]");
        System.out.println("...where source is either a txtser log file or BDB env dir");
        System.out.println("and target, if present, is a BDB env dir. ");
        return;
    }
}

From source file:com.versusoft.packages.ooo.odt2daisy.gui.CommandLineGUI.java

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

    Handler fh = new FileHandler(LOG_FILENAME_PATTERN);
    fh.setFormatter(new SimpleFormatter());

    //removeAllLoggersHandlers(Logger.getLogger(""));

    Logger.getLogger("").addHandler(fh);
    Logger.getLogger("").setLevel(Level.FINEST);

    Options options = new Options();

    Option option1 = new Option("in", "name of ODT file (required)");
    option1.setRequired(true);//from  w w w  . j a  v  a2  s  . c  o m
    option1.setArgs(1);

    Option option2 = new Option("out", "name of DAISY DTB file (required)");
    option2.setRequired(true);
    option2.setArgs(1);

    Option option3 = new Option("h", "show this help");
    option3.setArgs(Option.UNLIMITED_VALUES);

    Option option4 = new Option("alt", "use alternate Level Markup");

    Option option5 = new Option("u", "UID of DAISY DTB (optional)");
    option5.setArgs(1);

    Option option6 = new Option("t", "Title of DAISY DTB");
    option6.setArgs(1);

    Option option7 = new Option("c", "Creator of DAISY DTB");
    option7.setArgs(1);

    Option option8 = new Option("p", "Publisher of DAISY DTB");
    option8.setArgs(1);

    Option option9 = new Option("pr", "Producer of DAISY DTB");
    option9.setArgs(1);

    Option option10 = new Option("pic", "set Picture directory");
    option10.setArgs(1);

    Option option11 = new Option("page", "enable pagination");
    option11.setArgs(0);

    Option option12 = new Option("css", "write CSS file");
    option12.setArgs(0);

    options.addOption(option1);
    options.addOption(option2);
    options.addOption(option3);
    options.addOption(option4);
    options.addOption(option5);
    options.addOption(option6);
    options.addOption(option7);
    options.addOption(option8);
    options.addOption(option9);
    options.addOption(option10);
    options.addOption(option11);
    options.addOption(option12);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        //System.out.println("***ERROR: " + e.getClass() + ": " + e.getMessage());

        printHelp();
        return;
    }

    if (cmd.hasOption("help")) {
        printHelp();
        return;
    }

    try {

        Odt2Daisy odt2daisy = new Odt2Daisy(cmd.getOptionValue("in")); //@todo add initial output directory URL?
        odt2daisy.init();

        if (odt2daisy.isEmptyDocument()) {
            logger.info("Cannot convert empty documents. Export Aborted...");
            System.exit(1);
        }

        //System.out.println("Metadatas");
        //System.out.println("- title: " + odt2daisy.getTitleMeta());
        //System.out.println("- creator: " + odt2daisy.getCreatorMeta());

        if (!odt2daisy.isUsingHeadings()) {
            logger.info("You SHOULD use Heading styles in your document. Export in a single level.");
        }
        //@todo Warning for incompatible image formats should go here. See UnoGui.java.

        if (cmd.hasOption("u")) {
            //System.out.println("arg uid:"+cmd.getOptionValue("u"));
            odt2daisy.setUidParam(cmd.getOptionValue("u"));
        }

        if (cmd.hasOption("t")) {
            //System.out.println("arg title:"+cmd.getOptionValue("t"));
            odt2daisy.setTitleParam(cmd.getOptionValue("t"));
        }

        if (cmd.hasOption("c")) {
            //System.out.println("arg creator:"+cmd.getOptionValue("c"));
            odt2daisy.setCreatorParam(cmd.getOptionValue("c"));
        }

        if (cmd.hasOption("p")) {
            //System.out.println("arg publisher:"+cmd.getOptionValue("p"));
            odt2daisy.setPublisherParam(cmd.getOptionValue("p"));
        }

        if (cmd.hasOption("pr")) {
            //System.out.println("arg producer:"+cmd.getOptionValue("pr"));
            odt2daisy.setProducerParam(cmd.getOptionValue("pr"));
        }

        if (cmd.hasOption("alt")) {
            //System.out.println("arg alt:"+cmd.getOptionValue("alt"));
            odt2daisy.setUseAlternateLevelParam(true);
        }

        if (cmd.hasOption("css")) {
            odt2daisy.setWriteCSSParam(true);
        }

        if (cmd.hasOption("page")) {
            odt2daisy.paginationProcessing();
        }

        odt2daisy.correctionProcessing();

        if (cmd.hasOption("pic")) {

            odt2daisy.convertAsDTBook(cmd.getOptionValue("out"), cmd.getOptionValue("pic"));

        } else {

            logger.info("Language detected: " + odt2daisy.getLangParam());
            odt2daisy.convertAsDTBook(cmd.getOptionValue("out"), Configuration.DEFAULT_IMAGE_DIR);
        }

        boolean valid = odt2daisy.validateDTD(cmd.getOptionValue("out"));

        if (valid) {

            logger.info("DAISY DTBook produced is valid against DTD - Congratulations !");

        } else {

            logger.info("DAISY Book produced isn't valid against DTD - You SHOULD NOT use this DAISY Book !");
            logger.info("Error at line: " + odt2daisy.getErrorHandler().getLineNumber());
            logger.info("Error Message: " + odt2daisy.getErrorHandler().getMessage());
        }

    } catch (Exception e) {

        e.printStackTrace();

    } finally {

        if (fh != null) {
            fh.flush();
            fh.close();
        }
    }

}

From source file:de.burlov.amazon.s3.dirsync.CLI.java

/**
 * @param args/*www . java2s. c om*/
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    Logger.getLogger("").setLevel(Level.OFF);
    Logger deLogger = Logger.getLogger("de");
    deLogger.setLevel(Level.INFO);
    Handler handler = new ConsoleHandler();
    handler.setFormatter(new VerySimpleFormatter());
    deLogger.addHandler(handler);
    deLogger.setUseParentHandlers(false);
    //      if (true)
    //      {
    //         LogFactory.getLog(CLI.class).error("test msg", new Exception("test extception"));
    //         return;
    //      }
    Options opts = new Options();
    OptionGroup gr = new OptionGroup();

    /*
     * Befehlsgruppe initialisieren
     */
    gr = new OptionGroup();
    gr.setRequired(true);
    gr.addOption(OptionBuilder.withArgName("up|down").hasArg()
            .withDescription("Upload/Download changed or new files").create(CMD_UPDATE));
    gr.addOption(OptionBuilder.withArgName("up|down").hasArg()
            .withDescription("Upload/Download directory snapshot").create(CMD_SNAPSHOT));
    gr.addOption(OptionBuilder.withDescription("Delete remote folder").create(CMD_DELETE_DIR));
    gr.addOption(OptionBuilder.withDescription("Delete a bucket").create(CMD_DELETE_BUCKET));
    gr.addOption(OptionBuilder.create(CMD_HELP));
    gr.addOption(OptionBuilder.create(CMD_VERSION));
    gr.addOption(OptionBuilder.withDescription("Prints summary for stored data").create(CMD_SUMMARY));
    gr.addOption(OptionBuilder.withDescription("Clean up orphaned objekts").create(CMD_CLEANUP));
    gr.addOption(OptionBuilder.withDescription("Changes encryption password").withArgName("new password")
            .hasArg().create(CMD_CHANGE_PASSWORD));
    gr.addOption(OptionBuilder.withDescription("Lists all buckets").create(CMD_LIST_BUCKETS));
    gr.addOption(OptionBuilder.withDescription("Lists raw objects in a bucket").create(CMD_LIST_BUCKET));
    gr.addOption(OptionBuilder.withDescription("Lists files in remote folder").create(CMD_LIST_DIR));
    opts.addOptionGroup(gr);
    /*
     * Parametergruppe initialisieren
     */
    opts.addOption(OptionBuilder.withArgName("key").isRequired(false).hasArg().withDescription("S3 access key")
            .create(OPT_S3S_KEY));
    opts.addOption(OptionBuilder.withArgName("secret").isRequired(false).hasArg()
            .withDescription("Secret key for S3 account").create(OPT_S3S_SECRET));
    opts.addOption(OptionBuilder.withArgName("bucket").isRequired(false).hasArg().withDescription(
            "Optional bucket name for storage. If not specified then an unique bucket name will be generated")
            .create(OPT_BUCKET));
    // opts.addOption(OptionBuilder.withArgName("US|EU").hasArg().
    // withDescription(
    // "Where the new bucket should be created. Default US").create(
    // OPT_LOCATION));
    opts.addOption(OptionBuilder.withArgName("path").isRequired(false).hasArg()
            .withDescription("Local directory path").create(OPT_LOCAL_DIR));
    opts.addOption(OptionBuilder.withArgName("name").isRequired(false).hasArg()
            .withDescription("Remote directory name").create(OPT_REMOTE_DIR));
    opts.addOption(OptionBuilder.withArgName("password").isRequired(false).hasArg()
            .withDescription("Encryption password").create(OPT_ENC_PASSWORD));
    opts.addOption(OptionBuilder.withArgName("patterns").hasArgs()
            .withDescription("Comma separated exclude file patterns like '*.tmp,*/dir/*.tmp'")
            .create(OPT_EXCLUDE_PATTERNS));
    opts.addOption(OptionBuilder.withArgName("patterns").hasArgs().withDescription(
            "Comma separated include patterns like '*.java'. If not specified, then all files in specified local directory will be included")
            .create(OPT_INCLUDE_PATTERNS));

    if (args.length == 0) {
        printUsage(opts);
        return;
    }

    CommandLine cmd = null;
    try {
        cmd = new GnuParser().parse(opts, args);
        if (cmd.hasOption(CMD_HELP)) {
            printUsage(opts);
            return;
        }
        if (cmd.hasOption(CMD_VERSION)) {
            System.out.println("s3dirsync version " + Version.CURRENT_VERSION);
            return;
        }
        String awsKey = cmd.getOptionValue(OPT_S3S_KEY);
        String awsSecret = cmd.getOptionValue(OPT_S3S_SECRET);
        String bucket = cmd.getOptionValue(OPT_BUCKET);
        String bucketLocation = cmd.getOptionValue(OPT_LOCATION);
        String localDir = cmd.getOptionValue(OPT_LOCAL_DIR);
        String remoteDir = cmd.getOptionValue(OPT_REMOTE_DIR);
        String password = cmd.getOptionValue(OPT_ENC_PASSWORD);
        String exclude = cmd.getOptionValue(OPT_EXCLUDE_PATTERNS);
        String include = cmd.getOptionValue(OPT_INCLUDE_PATTERNS);

        if (StringUtils.isBlank(awsKey) || StringUtils.isBlank(awsSecret)) {
            System.out.println("S3 account data required");
            return;
        }

        if (StringUtils.isBlank(bucket)) {
            bucket = awsKey + ".dirsync";
        }

        if (cmd.hasOption(CMD_DELETE_BUCKET)) {
            if (StringUtils.isBlank(bucket)) {
                System.out.println("Bucket name required");
                return;
            }
            int deleted = S3Utils.deleteBucket(awsKey, awsSecret, bucket);
            System.out.println("Deleted objects: " + deleted);
            return;
        }
        if (cmd.hasOption(CMD_LIST_BUCKETS)) {
            for (String str : S3Utils.listBuckets(awsKey, awsSecret)) {
                System.out.println(str);
            }
            return;
        }
        if (cmd.hasOption(CMD_LIST_BUCKET)) {
            if (StringUtils.isBlank(bucket)) {
                System.out.println("Bucket name required");
                return;
            }
            for (String str : S3Utils.listObjects(awsKey, awsSecret, bucket)) {
                System.out.println(str);
            }
            return;
        }
        if (StringUtils.isBlank(password)) {
            System.out.println("Encryption password required");
            return;
        }
        char[] psw = password.toCharArray();
        DirSync ds = new DirSync(awsKey, awsSecret, bucket, bucketLocation, psw);
        ds.setExcludePatterns(parseSubargumenths(exclude));
        ds.setIncludePatterns(parseSubargumenths(include));
        if (cmd.hasOption(CMD_SUMMARY)) {
            ds.printStorageSummary();
            return;
        }
        if (StringUtils.isBlank(remoteDir)) {
            System.out.println("Remote directory name required");
            return;
        }
        if (cmd.hasOption(CMD_DELETE_DIR)) {
            ds.deleteFolder(remoteDir);
            return;
        }
        if (cmd.hasOption(CMD_LIST_DIR)) {
            Folder folder = ds.getFolder(remoteDir);
            if (folder == null) {
                System.out.println("No such folder found: " + remoteDir);
                return;
            }
            for (Map.Entry<String, FileInfo> entry : folder.getIndexData().entrySet()) {
                System.out.println(entry.getKey() + " ("
                        + FileUtils.byteCountToDisplaySize(entry.getValue().getLength()) + ")");
            }
            return;
        }
        if (cmd.hasOption(CMD_CLEANUP)) {
            ds.cleanUp();
            return;
        }
        if (cmd.hasOption(CMD_CHANGE_PASSWORD)) {
            String newPassword = cmd.getOptionValue(CMD_CHANGE_PASSWORD);
            if (StringUtils.isBlank(newPassword)) {
                System.out.println("new password required");
                return;
            }
            char[] chars = newPassword.toCharArray();
            ds.changePassword(chars);
            newPassword = null;
            Arrays.fill(chars, ' ');
            return;
        }
        if (StringUtils.isBlank(localDir)) {
            System.out.println(OPT_LOCAL_DIR + " argument required");
            return;
        }
        String direction = "";
        boolean up = false;
        boolean snapshot = false;
        if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_UPDATE))) {
            direction = cmd.getOptionValue(CMD_UPDATE);
        } else if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_SNAPSHOT))) {
            direction = cmd.getOptionValue(CMD_SNAPSHOT);
            snapshot = true;
        }
        if (StringUtils.isBlank(direction)) {
            System.out.println("Operation direction required");
            return;
        }
        up = StringUtils.equalsIgnoreCase(OPT_UP, direction);
        File baseDir = new File(localDir);
        if (!baseDir.exists() && !baseDir.mkdirs()) {
            System.out.println("Invalid local directory: " + baseDir.getAbsolutePath());
            return;
        }
        ds.syncFolder(baseDir, remoteDir, up, snapshot);

    } catch (DirSyncException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printUsage(opts);

    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

From source file:org.owasp.proxy.Main.java

public static void main(String[] args) throws Exception {
    java.lang.System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
    logger.setUseParentHandlers(false);//w  w w  .  ja  v a2s . com
    Handler ch = new ConsoleHandler();
    ch.setFormatter(new TextFormatter());
    logger.addHandler(ch);

    final Configuration config = Configuration.init(args);

    final InetSocketAddress listen = new InetSocketAddress(config.iface, config.port);
    TargetedConnectionHandler tch;
    if (config.httpConnect == null) {
        DefaultHttpRequestHandler drh = configureRequestHandler(config);
        ServerGroup sg = new ServerGroup();
        sg.addServer(listen);
        drh.setServerGroup(sg);

        HttpRequestHandler rh = drh;
        rh = configureAuthentication(rh, config);
        rh = configureAJP(rh, config);
        rh = new LoggingHttpRequestHandler(rh);
        rh = configureJDBCLogging(rh, config);
        rh = configureInterception(rh, config);

        HttpProxyConnectionHandler hpch = new HttpProxyConnectionHandler(rh);
        SSLContextSelector cp = getServerSSLContextSelector();
        tch = new SSLConnectionHandler(cp, true, hpch);
        tch = new LoopAvoidingTargetedConnectionHandler(sg, tch);
        hpch.setConnectHandler(tch);
    } else {
        tch = new ConnectConnectionHandler(config.httpConnect);
    }
    TargetedConnectionHandler socks = new SocksConnectionHandler(tch, true);
    Proxy p = new Proxy(listen, socks, null);
    p.setSocketTimeout(90000);
    p.start();

    System.out.println("Listener started on " + listen);
    System.out.println("Press Enter to terminate");
    new BufferedReader(new InputStreamReader(System.in)).readLine();
    p.stop();
    System.out.println("Terminated");
    System.exit(0);
}

From source file:primarydatamanager.PrimaryDataManager.java

public static void main(String[] args) {
    // setup logging
    try {/* w ww .  j a v  a 2  s.com*/
        // Get the default Logger
        Logger mainLogger = Logger.getLogger("");
        mainLogger.setLevel(Level.FINEST);

        Handler consoleHandler = mainLogger.getHandlers()[0];
        consoleHandler.setLevel(Level.FINEST);
        consoleHandler.setFormatter(new VerySimpleFormatter());

        // Add a file handler
        new File("log").mkdir();
        Handler fileHandler = new FileHandler("log/datamanager.log", 50000, 2, true);
        fileHandler.setLevel(Level.INFO);
        mainLogger.addHandler(fileHandler);
    } catch (IOException exc) {
        System.out.println("Can't create log file");
        exc.printStackTrace();
    }

    // Start the update
    if (args.length == 0) {
        System.out.println("USAGE: PrimaryDataManager [-forceCompleteUpdate [channel{;channel}]] groups...");
        System.exit(1);
    } else {
        try {
            PrimaryDataManager manager = new PrimaryDataManager(new File("."));
            ArrayList<String> groupNames = new ArrayList<String>();
            for (int i = 0; i < args.length; i++) {
                if (args[i].equalsIgnoreCase("-forceCompleteUpdate")) {
                    if ((i + 1) >= args.length) {
                        System.out.println("You have to specify a colon separated "
                                + "list of channels after -forceCompleteUpdate");
                        System.exit(1);
                    } else {
                        i++;
                        StringTokenizer tokenizer = new StringTokenizer(args[i], ":");
                        while (tokenizer.hasMoreTokens()) {
                            manager.forceCompleteUpdateFor(tokenizer.nextToken());
                        }
                    }
                } else {
                    final String[] groups = args[i].split(",");
                    groupNames.addAll(Arrays.asList(groups));
                }
            }

            if (groupNames.size() == 0) {
                System.out.println("Please specify at least one channel group");
                System.exit(-1);
            }

            if (!manager.doesPreparedExist()) {
                System.out.println(
                        "The prepared directory is missing, this directory is very important and shouldn't "
                                + "be deleted, because this leeds to massiv problems.");
                System.exit(-1);
            }

            if (!manager.createLockFile()) {
                System.out.println("The PrimaryDataManager is already running.");
                System.exit(-1);
            }

            String[] groupNamesArr = new String[groupNames.size()];
            groupNames.toArray(groupNamesArr);
            manager.setGroupNames(groupNamesArr);

            manager.updateRawDataDir();

            manager.deleteLockFile();

            // Exit with error code 2 if some day programs were put into quarantine
            if (manager.mRawDataProcessor.getQuarantineCount() != 0) {
                System.exit(2);
            }
        } catch (PreparationException exc) {
            exc.printStackTrace();
            System.exit(1);
        }
    }
}

From source file:org.scify.NewSumServer.Server.Utils.Main.java

public static void main(String[] args) throws FeedParserException, NetworkException, IOException {
    //initialize logger
    Handler h;
    try {/*from   ww w. j a v a2s.  c  o  m*/
        h = new FileHandler(sLogFile);
        SimpleFormatter f = new SimpleFormatter();
        h.setFormatter(f);
        LOGGER.addHandler(h);
        LOGGER.setLevel(Level.FINE);
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
    } catch (SecurityException ex) {
        LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
    }
    //program info
    System.out.print("NewSumServer Switches:\n\n"
            + "-BaseDir: The full path to the folder where the storage module stores data\n"
            + "-PathToSources: The file named RSSSources.txt with it's full path\n"
            + "\t(e.g. /home/pathtosources/RSSSources.txt)\n"
            + "-indexPath: The full path to the folder where the Indexer Class stores data\n"
            + "-SummaryPath: The full path to the folder where the Summarisation package stores data\n"
            + "-ArticlePath: The full path to the folder where the "
            + "Summarisation package stores the Clustered Articles\n"
            + "-ToolPath: The full path to the folder for misc Tools\n"
            + "-iOutputSize: The max number of Sentences the Summariser prints\n"
            + "-ArticleMaxDays: The Number of Max Days to Accept an article (until now)\n"
            + "-useInputDirData: true or false, defaults to false\n"
            + "-DebugRun: true if you want to run with category switching (for quicker runs)\n\n"
            + "Example Usage: java -jar NewSumServer.jar -BaseDir=./data/Dir -iOutputSize=50\n\n");
    //Parse and check Command Line arguments
    parseCommandLine(args);
    //Write Configuration file so that NewSumFreeService reads statics
    writeConfigFile();
    // check if splitterTraining file was changed since the previous run
    if (SplitterTrainingFileChanged()) {
        // if so, delete the Model file, in order to get recreated with the new data
        File sDat = new File(sToolPath + "splitModel.dat");
        try {
            sDat.delete();
            LOGGER.log(Level.INFO, "deleted {0} cause splitterTrainer was updated", sDat.toString());
        } catch (Exception ex) {
            LOGGER.log(Level.WARNING,
                    "Could not delete {0}, although file Was Changed. " + "Please do it manually",
                    sDat.toString());
        }
    }
    //init data storage
    IDataStorage ids = new InsectFileIO(sBaseDir);
    //        justWaitABit(50000);

    //init rssSources 
    RSSSources r = new RSSSources(sPathToSources);
    // initialize sources: read the sources file
    r.initialize(ids);
    //get the sources
    HashMap<String, String> Sources = r.getRssLinks();//link,category
    //get categories
    Collection<String> sCategories = r.getCategories(); // TODO: Ignore UNCLASSIFIED CATEGORY
    ArrayList<String> lCategories = new ArrayList<String>(sCategories);
    //init rssparser
    ISourceParser isp = new RssParser(ids, iArticleDays);
    //DEBUG LINES //get user input
    List al = new ArrayList(sCategories);
    ArrayList<String> subSources = null;
    ArrayList<Article> Articles = new ArrayList<Article>();
    String sCurCateg = "0";
    if (bDebugRun) { // if only one category needed (quick run)
        System.out.println("Choose Category by number: \nIf -1, all categories are loaded");
        for (int i = 0; i < lCategories.size(); i++) {
            System.out.println(String.valueOf(i) + ": " + lCategories.get(i));
        }
        Scanner user_input = new Scanner(System.in);
        sCurCateg = user_input.next();
        /////////////

        if (Integer.valueOf(sCurCateg) != -1) {
            subSources = new ArrayList<String>((HashSet<String>) Utilities.getKeysByValue(Sources,
                    (String) al.get(Integer.valueOf(sCurCateg))));
            //accept all articles from each category
            Articles = (ArrayList<Article>) isp.getAllNewsByCategory(subSources,
                    (String) al.get(Integer.valueOf(sCurCateg)));

        } else if (Integer.valueOf(sCurCateg) == -1) {

            //get all articles
            Articles = (ArrayList<Article>) isp.getAllArticles(Sources);
        }
    } else { //if all categories by default (no user choosing - normal mode)
        Articles = (ArrayList<Article>) isp.getAllArticles(Sources);
    }
    // check for spam sentences
    Utilities.checkForPossibleSpam(Articles);
    //Save Article List to Drive, so that the clusterer loads it
    isp.saveAllArticles(); //Name: "AllArticles", Category: "feeds"
    //        ArticleClusterer ac = new ArticleClusterer(subArticles, ids, sArticlePath);
    //get least occurencies of articles
    //        threshold = Utilities.getLeastOccurencies(Articles);
    //        //Train Classification Module
    //        clm = new classificationModule();
    //
    //
    //        //initialize Distribution category set
    //        Distribution<String> dArticleCategory = new Distribution<String>();
    //
    //        for (int i = 0; i < Articles.size(); i++) {
    //            if (Articles.get(i).getToWrap()) {
    //                boolean mergeGraph = true;
    //                //increase Distribution set 1.0
    //                dArticleCategory.increaseValue(Articles.get(i).getCategory(), 1.0);
    //                //check threshold
    //                double dInstanceCount = dArticleCategory.getValue(Articles.get(i).getCategory());
    //                if (dInstanceCount < threshold) {
    //
    //                    //check mergeGraph threshold --> threshold/2  turn mergeGraph from true to false
    //                    if (dInstanceCount > (threshold / 2)) {
    //                        mergeGraph = false;
    //                    }
    //                    clm.feedClassifier(Articles.get(i).getCategory(), Articles.get(i).getText(), mergeGraph);
    //                }
    //
    //            }
    //        }
    // Initialize Clusterer
    ArticleClusterer ac;

    ac = new ArticleClusterer((ArrayList<Article>) ids.loadObject("AllArticles", "feeds"), ids, sArticlePath);

    // Perform clustering calculations

    ac.calculateClusters(NVSThreshold, SSThreshold);
    //specify the locale for the indexer
    Locale loc = sPathToSources.endsWith("GR.txt") ? new Locale("el") : new Locale("en");
    // Create a new indexer
    Indexer ind = new Indexer(sArticlePath, sindexPath, loc);
    // Create the Index
    try {
        ind.createIndex();
    } catch (CorruptIndexException ex) {
        LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
    } catch (LockObtainFailedException ex) {
        LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
    }
    // Init the summarizer and obtain summaries
    INSECTDB idb = new INSECTFileDB("", sSummaryPath);
    Summariser sum = new Summariser(new HashSet<Topic>(ac.getArticlesPerCluster().values()), idb);
    // Perform summarization for all clusters
    Map<String, List<Sentence>> AllSummaries;
    AllSummaries = sum.getSummaries();

    // DEBUG // store summaries
    //        for (Map.Entry mp : AllSummaries.entrySet()) {
    //            String sUID = (String) mp.getKey();
    //            List<Sentence> lsSen = (List<Sentence>) mp.getValue();
    //            if (getNumberOfSources(lsSen) > 1) {
    //                writeSummaryToFile(lsSen, sUID, ac.getArticlesPerCluster());
    //            }
    //        }        
    // DEBUG //
    if (bDebugRun) {

        // DEBUG LINES
        // Delete files in "data/txtSummaries" and write all the summaries extracted
        File f = new File(sTxtSumPath);
        if (f.exists()) {
            for (File k : f.listFiles()) {
                k.delete();
            }
        }
        for (Map.Entry mp : AllSummaries.entrySet()) {
            String sUID = (String) mp.getKey();
            List<Sentence> lsSen = (List<Sentence>) mp.getValue();
            if (getNumberOfSources(lsSen) > 1) {
                writeSummaryToFile(lsSen, sUID, ac.getArticlesPerCluster());
            }
        }

        // debug communicator
        Communicator cm = new Communicator(ids, ac, sum, ind);
        int bb = Integer.valueOf(sCurCateg);
        if (bb == -1) {
            bb = 0;
        }
        // print summary from communicator
        int iSummarizedClusterCnt = 0;
        for (Topic tTopic : ac.getArticlesPerCluster().values()) {
            if (tTopic.size() > 1) {
                System.out.println("Printing summary for topic: " + tTopic.getTitle());
                String[] eachSnippet = cm.getSummary(tTopic.getID(), "All").split(cm.getFirstLevelSeparator());
                int iAllTmpSourcesCount = eachSnippet[0].split(cm.getSecondLevelSeparator()).length;
                System.out.println("With Summary Sources: " + iAllTmpSourcesCount);
                for (int i = 1; i < eachSnippet.length; i++) {
                    String[] eachSent = eachSnippet[i].split(cm.getSecondLevelSeparator());
                    System.out.println(eachSent[0]);
                    System.out.println("-----------------------------------");
                    iSummarizedClusterCnt++;
                }
                System.out.println("===========================");
            }
        }

    }
    //DEBUG LINES //get user input
    //        System.out.println("Enter Search String\n");
    //        Scanner imp = new Scanner(System.in);
    //        String term = imp.next();
    //

    //        String sTop = cm.getTopicIDsByKeyword(ind, term, "All");
    //        System.out.println(sTop);
    //        System.out.println(cm.getTopicTitlesByIDs(sTop));

    // last debug
    //        String sUserSources = "http://rss.in.gr/feed/news/culture/" +
    //            "http://www.tovima.gr/feed/culture/" +
    //            "http://www.naftemporiki.gr/rssFeed?mode=section&id=6&atype=story";
    //        System.out.println(cm.getTopics(sUserSources, (String) al.get(bb)));
    //        System.out.println(cm.getTopics("All", (String) al.get(bb)));
    // last debug

    //        System.out.println("Found a total of " + iSummarizedClusterCnt + " summaries"
    //                + " from more than one texts.");
    //        System.out.println(cm.getTopicIDs("All", (String) al.get(bb)));
    //        System.out.println("===============printing topic titles");
    //        System.out.println(cm.getTopicTitles("All", (String) al.get(bb)));
    //        System.out.println("===============ending printing topic titles");
    //        String sUserSources = "http://rss.in.gr/feed/news/world/;;;"
    //                + "http://www.naftemporiki.gr/news/static/rss/news_pol_pol-world.xml;;;"
    //                + "http://ws.kathimerini.gr/xml_files/worldnews.xml;;;"
    //                + "http://feeds.feedburner.com/skai/aqOL?format=xml";
    //        System.out.println(cm.getTopicIDs(sUserSources, (String) al.get(bb)));
    //        System.out.println(cm.getTopicTitles(sUserSources, (String) al.get(bb)));

    //        int counter = 0;
    //        for (Topic tTopic : ac.getArticlesPerCluster().values()) {
    //            System.out.println("====================");
    //            System.out.println(cm.getSummary(tTopic.getID(), sUserSources));
    //            counter ++;
    //            if (counter == 3) {
    //                break;
    //            }
    //        }

}

From source file:prm4j.indexing.monitor.ParametricMonitorLogger.java

/**
 * A simple file logger which outputs only the message.
 * //from w ww  .  jav a  2 s. co  m
 * @param fileName
 *            path to the output file
 * @return the logger
 */
private static Logger getFileLogger(String fileName) {
    // make sure parent directories exist
    new File(fileName).getParentFile().mkdirs();
    final Logger logger = Logger.getLogger(fileName);
    try {
        logger.setUseParentHandlers(false);
        Handler handler = new FileHandler(fileName, true);
        handler.setFormatter(new Formatter() {
            @Override
            public String format(LogRecord record) {
                return record.getMessage() + "\n";
            }
        });
        logger.addHandler(handler);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return logger;
}