List of usage examples for java.util.logging FileHandler FileHandler
public FileHandler(String pattern) throws IOException, SecurityException
From source file:MyHtmlFormatter.java
public static void main(String[] argv) throws Exception { Logger logger = Logger.getLogger("com.mycompany"); FileHandler fh = new FileHandler("mylog.html"); fh.setFormatter(new MyHtmlFormatter()); logger.addHandler(fh);/*from w w w .java 2 s . co m*/ logger.setLevel(Level.ALL); logger.severe("my severe message"); logger.info("my info message"); logger.entering("Main class", "myMethod", new Object[] { "para1", "para2" }); }
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 ww . j av a2s . co 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: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 ww w . jav a 2 s . c om 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:com.googlecode.promnetpp.main.Main.java
/** * Main function (entry point for the tool). * * @param args Command-line arguments.//from w ww . jav a2s . c o m */ public static void main(String[] args) { //Prepare logging try { Handler fileHandler = new FileHandler("promnetpp-log.xml"); Logger logger = Logger.getLogger(""); logger.removeHandler(logger.getHandlers()[0]); logger.addHandler(fileHandler); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } catch (SecurityException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } String PROMNeTppHome = System.getenv("PROMNETPP_HOME"); if (PROMNeTppHome == null) { String userDir = System.getProperty("user.dir"); System.err.println("WARNING: PROMNETPP_HOME environment variable" + " not set."); System.err.println("PROMNeT++ will assume " + userDir + " as" + " home."); PROMNeTppHome = userDir; } System.setProperty("promnetpp.home", PROMNeTppHome); Logger.getLogger(Main.class.getName()).log(Level.INFO, "PROMNeT++ home" + " set to {0}", System.getProperty("promnetpp.home")); if (args.length == 1) { fileNameOrPath = args[0]; configurationFilePath = PROMNeTppHome + "/default-configuration.xml"; } else if (args.length == 2) { fileNameOrPath = args[0]; configurationFilePath = args[1]; } else { System.err.println("Invalid number of command-line arguments."); System.err.println("Usage #1: promnetpp.jar <PROMELA model>.pml"); System.err.println("Usage #2: promnetpp.jar <PROMELA model>.pml" + " <configuration file>.xml"); System.exit(1); } //We must have a file name or path at this point assert fileNameOrPath != null : "Unspecified file name or" + " path to file!"; //Log basic info Logger.getLogger(Main.class.getName()).log(Level.INFO, "Running" + " PROMNeT++ from {0}", System.getProperty("user.dir")); //Final steps loadXMLFile(); Verifier verifier = new StandardVerifier(fileNameOrPath); verifier.doVerification(); assert verifier.isErrorFree() : "Errors reported during model" + " verification!"; verifier.finish(); buildAbstractSyntaxTree(); Translator translator = new StandardTranslator(); translator.init(); translator.translate(abstractSyntaxTree); translator.finish(); }
From source file:core.PlanC.java
/** * inicio de aplicacion/*from w ww . java 2 s. c om*/ * * @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:malware_classification.Malware_Classification.java
/** * @param args the command line arguments. Order is malicious_filename, * benign filename, (optional) bin_size/*from w ww .j a v a 2s. co m*/ */ public static void main(String[] args) { String malicious_file_path = args[0]; String benign_file_path = args[1]; int curr_bin_size; if (args.length > 2) { curr_bin_size = Integer.parseInt(args[2]); } else { curr_bin_size = -1; } String pid_str = ManagementFactory.getRuntimeMXBean().getName(); logger.setLevel(Level.CONFIG); logger.log(Level.INFO, pid_str); boolean found_file = false; String output_base = "std_output"; File output_file = null; for (int i = 0; !found_file; i++) { output_file = new File(output_base + i + ".txt"); found_file = !output_file.exists(); } FileHandler fh = null; try { fh = new FileHandler(output_file.getAbsolutePath()); } catch (IOException ex) { Logger.getLogger(Malware_Classification.class.getName()).log(Level.SEVERE, null, ex); } catch (SecurityException ex) { Logger.getLogger(Malware_Classification.class.getName()).log(Level.SEVERE, null, ex); } logger.addHandler(fh); logger.info("Writing output in " + output_file.getAbsolutePath()); Malware_Classification classifier = new Malware_Classification(malicious_file_path, benign_file_path, curr_bin_size); // classifier.run_tests(); }
From source file:GIST.IzbirkomExtractor.IzbirkomExtractor.java
/** * @param args// w w w.j av a 2s . c o m */ public static void main(String[] args) { // process command-line options Options options = new Options(); options.addOption("n", "noaddr", false, "do not do any address matching (for testing)"); options.addOption("i", "info", false, "create and populate address information table"); options.addOption("h", "help", false, "this message"); // database connection options.addOption("s", "server", true, "database server to connect to"); options.addOption("d", "database", true, "OSM database name"); options.addOption("u", "user", true, "OSM database user name"); options.addOption("p", "pass", true, "OSM database password"); // logging options options.addOption("l", "logdir", true, "log file directory (default './logs')"); options.addOption("e", "loglevel", true, "log level (default 'FINEST')"); // automatically generate the help statement HelpFormatter help_formatter = new HelpFormatter(); // database URI for connection String dburi = null; // Information message for help screen String info_msg = "IzbirkomExtractor [options] <html_directory>"; try { CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('h') || cmd.getArgs().length != 1) { help_formatter.printHelp(info_msg, options); System.exit(1); } /* prohibit n and i together */ if (cmd.hasOption('n') && cmd.hasOption('i')) { System.err.println("Options 'n' and 'i' cannot be used together."); System.exit(1); } /* require database arguments without -n */ if (cmd.hasOption('n') && (cmd.hasOption('s') || cmd.hasOption('d') || cmd.hasOption('u') || cmd.hasOption('p'))) { System.err.println("Options 'n' and does not need any databse parameters."); System.exit(1); } /* require all 4 database options to be used together */ if (!cmd.hasOption('n') && !(cmd.hasOption('s') && cmd.hasOption('d') && cmd.hasOption('u') && cmd.hasOption('p'))) { System.err.println( "For database access all of the following arguments have to be specified: server, database, user, pass"); System.exit(1); } /* useful variables */ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm"); String dateString = formatter.format(new Date()); /* setup logging */ File logdir = new File(cmd.hasOption('l') ? cmd.getOptionValue('l') : "logs"); FileUtils.forceMkdir(logdir); File log_file_name = new File( logdir + "/" + IzbirkomExtractor.class.getName() + "-" + formatter.format(new Date()) + ".log"); FileHandler log_file = new FileHandler(log_file_name.getPath()); /* create "latest" link to currently created log file */ Path latest_log_link = Paths.get(logdir + "/latest"); Files.deleteIfExists(latest_log_link); Files.createSymbolicLink(latest_log_link, Paths.get(log_file_name.getName())); log_file.setFormatter(new SimpleFormatter()); LogManager.getLogManager().reset(); // prevents logging to console logger.addHandler(log_file); logger.setLevel(cmd.hasOption('e') ? Level.parse(cmd.getOptionValue('e')) : Level.FINEST); // open directory with HTML files and create file list File dir = new File(cmd.getArgs()[0]); if (!dir.isDirectory()) { System.err.println("Unable to find directory '" + cmd.getArgs()[0] + "', exiting"); System.exit(1); } PathMatcher pmatcher = FileSystems.getDefault() .getPathMatcher("glob:? * ?*.html"); ArrayList<File> html_files = new ArrayList<>(); for (Path file : Files.newDirectoryStream(dir.toPath())) if (pmatcher.matches(file.getFileName())) html_files.add(file.toFile()); if (html_files.size() == 0) { System.err.println("No matching HTML files found in '" + dir.getAbsolutePath() + "', exiting"); System.exit(1); } // create csvResultSink FileOutputStream csvout_file = new FileOutputStream("parsed_addresses-" + dateString + ".csv"); OutputStreamWriter csvout = new OutputStreamWriter(csvout_file, "UTF-8"); ResultSink csvResultSink = new CSVResultSink(csvout, new CSVStrategy('|', '"', '#')); // Connect to DB and osmAddressMatcher AddressMatcher osmAddressMatcher; DBSink dbSink = null; DBInfoSink dbInfoSink = null; if (cmd.hasOption('n')) { osmAddressMatcher = new DummyAddressMatcher(); } else { dburi = "jdbc:postgresql://" + cmd.getOptionValue('s') + "/" + cmd.getOptionValue('d'); Connection con = DriverManager.getConnection(dburi, cmd.getOptionValue('u'), cmd.getOptionValue('p')); osmAddressMatcher = new OsmAddressMatcher(con); dbSink = new DBSink(con); if (cmd.hasOption('i')) dbInfoSink = new DBInfoSink(con); } /* create resultsinks */ SinkMultiplexor sm = SinkMultiplexor.newSinkMultiplexor(); sm.addResultSink(csvResultSink); if (dbSink != null) { sm.addResultSink(dbSink); if (dbInfoSink != null) sm.addResultSink(dbInfoSink); } // create tableExtractor TableExtractor te = new TableExtractor(osmAddressMatcher, sm); // TODO: printout summary of options: processing date/time, host, directory of HTML files, jdbc uri, command line with parameters // iterate through files logger.info("Start processing " + html_files.size() + " files in " + dir); for (int i = 0; i < html_files.size(); i++) { System.err.println("Parsing #" + i + ": " + html_files.get(i)); te.processHTMLfile(html_files.get(i)); } System.err.println("Processed " + html_files.size() + " HTML files"); logger.info("Finished processing " + html_files.size() + " files in " + dir); } catch (ParseException e1) { System.err.println("Failed to parse CLI: " + e1.getMessage()); help_formatter.printHelp(info_msg, options); System.exit(1); } catch (IOException e) { System.err.println("I/O Exception: " + e.getMessage()); e.printStackTrace(); System.exit(1); } catch (SQLException e) { System.err.println("Database '" + dburi + "': " + e.getMessage()); System.exit(1); } catch (ResultSinkException e) { System.err.println("Failed to initialize ResultSink: " + e.getMessage()); System.exit(1); } catch (TableExtractorException e) { System.err.println("Failed to initialize Table Extractor: " + e.getMessage()); System.exit(1); } catch (CloneNotSupportedException | IllegalAccessException | InstantiationException e) { System.err.println("Something really odd happened: " + e.getMessage()); e.printStackTrace(); System.exit(1); } }
From source file:net.sf.mpaxs.spi.computeHost.StartUp.java
/** * * @param args/*w ww. jav a 2 s. c o m*/ */ public static void main(String args[]) { FileHandler handler; try { handler = new FileHandler("computeHost.log"); Logger logger = Logger.getLogger(StartUp.class.getName()); logger.addHandler(handler); } catch (IOException ex) { Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex); } catch (SecurityException ex) { Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex); } Options options = new Options(); Option[] optionArray = new Option[] { OptionBuilder.withArgName("configuration").hasArg().isRequired() .withDescription("URL to configuration file for compute host").create("c") }; for (Option opt : optionArray) { options.addOption(opt); } if (args.length == 0) { HelpFormatter hf = new HelpFormatter(); hf.printHelp(StartUp.class.getCanonicalName(), options, true); System.exit(1); } GnuParser gp = new GnuParser(); try { CommandLine cl = gp.parse(options, args); try { URL configURL = new URL(cl.getOptionValue("c")); PropertiesConfiguration cfg = new PropertiesConfiguration(configURL); StartUp su = new StartUp(cfg); } catch (ConfigurationException ex) { Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex); } catch (MalformedURLException ex) { Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex); } } catch (ParseException ex) { Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.scify.NewSumServer.Server.Utils.Main.java
public static void main(String[] args) throws FeedParserException, NetworkException, IOException { //initialize logger Handler h;//w ww .j av a 2s. c om try { 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:velo.patterns.FactoryLogger.java
/** * Factory a logger by a log file name/* w w w . ja v a 2s. co m*/ * @param logName The log file name to factory a logger object for * @return A logger object for the specified log file name */ public static Logger loggerFactory(String logName) { Logger logger = Logger.getLogger(logName); //Create a new handler that uses the simple formatter try { FileHandler fh = new FileHandler(getLogDir() + logName + ".txt"); fh.setFormatter(new SimpleFormatter()); logger.addHandler(fh); } catch (IOException e) { } return logger; }