List of usage examples for java.util.logging Logger getLogger
@CallerSensitive public static Logger getLogger(String name)
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);/* w w w . j a v a2s.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:eu.edisonproject.utility.execute.Main.java
public static void main(String args[]) { Options options = new Options(); Option operation = new Option("op", "operation", true, "type of operation to perform. " + "To move cached terms from org.mapdb.DB 'm'"); operation.setRequired(true);// ww w.j a v a 2s .com options.addOption(operation); Option input = new Option("i", "input", true, "input file path"); input.setRequired(true); options.addOption(input); String helpmasg = "Usage: \n"; for (Object obj : options.getOptions()) { Option op = (Option) obj; helpmasg += op.getOpt() + ", " + op.getLongOpt() + "\t Required: " + op.isRequired() + "\t\t" + op.getDescription() + "\n"; } try { CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); switch (cmd.getOptionValue("operation")) { case "m": DBTools.portTermCache2Hbase(cmd.getOptionValue("input")); DBTools.portBabelNetCache2Hbase(cmd.getOptionValue("input")); break; default: System.out.println(helpmasg); } } catch (Exception ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, helpmasg, ex); } }
From source file:be.kdg.repaircafemodel.TestRepairCafe.java
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( "be/kdg/repaircafemodel/spring/root-context.xml"); // Get userService from Spring Context UserService userService = (UserService) context.getBean("userService"); // Get repairService from Spring Context RepairService repairService = (RepairService) context.getBean("repairService"); // Create a client Address address1 = new Address("Nationalestraat", "5", "2000", "Antwerpen"); Person person1 = new Person("Jan", "Peeters", address1); Client client = new Client(person1, "jan.peeters@student.kdg.be", "jan"); // Create a repairer Address address2 = new Address("Nationalestraat", "5", "2000", "Antwerpen"); Person person2 = new Person("Wouter", "Deketelaere", address2); Repairer repairGuy = new Repairer(person2, "wouter.deketelaere@kdg.be", "jef", "Master"); try {//from ww w . j a v a 2 s . co m userService.addUser(client); userService.addUser(repairGuy); } catch (UserServiceException ex) { Logger.getLogger(TestRepairCafe.class.getName()).log(Level.SEVERE, null, ex); } // update een gebruiker met een nieuw wachtwoord try { userService.updatePassword(repairGuy, "jef", "wouter"); userService.checkLogin(repairGuy.getUsername(), "wouter"); } catch (UserServiceException ex) { Logger.getLogger(TestRepairCafe.class.getName()).log(Level.SEVERE, null, ex); } try { userService.checkLogin("wouter.deketelaere@kdg.be", "wouter"); } catch (UserServiceException ex) { Logger.getLogger(TestRepairCafe.class.getName()).log(Level.SEVERE, null, ex); } Repair repair = new Repair(new Item("G 4210 i", "Miele", "Vaatwasser"), new RepairDetails("Elektrisch", "Toestel stopt niet meer", RepairDetails.PriceModel.FIXED, new DateTime().plusWeeks(2))); repairService.submitRepair(client, repair); System.out.println(repairService.getAllCategories()); repairService.placeBid(repairGuy, repair, 200.0); System.out.println(repairService.findAllRepairsByClient(client)); repairService.placeBid(repairGuy, repair, 150); try { System.out.println(repairService.findRepairsByCategory("Vaatwasser")); System.out.println(repairService.findRepairsByDefect("Elektrisch")); System.out.println(repairService.getBids(repairGuy)); } catch (RepairServiceException ex) { Logger.getLogger(TestRepairCafe.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:hk.mcc.utils.applog2es.Main.java
/** * @param args the command line arguments *//*w w w .j av a 2 s .c om*/ public static void main(String[] args) throws Exception { String pathString = "G:\\tmp\\Archive20160902"; Path path = Paths.get(pathString); try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, "app*.log")) { for (Path entry : stream) { List<AppLog> appLogs = new ArrayList<>(); try (AppLogParser appLogParser = new AppLogParser(Files.newInputStream(entry))) { AppLog nextLog = appLogParser.nextLog(); while (nextLog != null) { // System.out.println(nextLog); nextLog = appLogParser.nextLog(); appLogs.add(nextLog); } post2ES(appLogs); } catch (IOException ex) { Logger.getLogger(AppLogParser.class.getName()).log(Level.SEVERE, null, ex); } } } }
From source file:ie.peternagy.jcrypto.cli.JCryptoCli.java
public static void main(String[] args) { long startTime = System.currentTimeMillis(); try {/*from w ww .jav a 2s .com*/ CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(OPTIONS, args); isVerbose = line.hasOption('v'); routeParams(line); if (isVerbose) { System.out.printf("\n Process finished in %dms\n\n", System.currentTimeMillis() - startTime); } } catch (org.apache.commons.cli.ParseException ex) { printCliHelp(); //@todo: override the logger if not in debug mode Logger.getLogger(JCryptoCli.class.getName()).log(Level.SEVERE, null, ex); } }
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 . j av a 2s . 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:comparetopics.CompareTopics.java
/** * @param args the command line arguments *///from w w w.ja v a2 s . c o m public static void main(String[] args) { try { File file1 = new File( "/Users/apple/Desktop/graduation-project/topic-modeling/output/jhotdraw-extracted-code/keys.txt"); File file2 = new File( "/Users/apple/Desktop/graduation-project/topic-modeling/output/jhotdraw-extracted-code/keys.txt"); CompareTopics compareTopics = new CompareTopics(); String[] words1 = compareTopics.getWords(file1); String[] words2 = compareTopics.getWords(file2); StringBuffer words = new StringBuffer(); File outputFile = new File("/Users/apple/Desktop/test.txt"); if (outputFile.createNewFile()) { System.out.println("Create successful: " + outputFile.getName()); } boolean hasSame = false; for (String w1 : words1) { if (!NumberUtils.isNumber(w1)) { for (String w2 : words2) { if (w1.equals(w2)) { words.append(w1); // words.append("\r\n"); words.append(" "); hasSame = true; break; } } } } if (!hasSame) { System.out.println("No same word."); } else { compareTopics.printToFile(words.toString(), outputFile); } } catch (IOException ex) { Logger.getLogger(CompareTopics.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.mycompany.myelasticsearch.MainClass.java
/** * @param args the command line arguments */// ww w . ja v a 2 s . co m public static void main(String[] args) { // TODO code application logic here Tika tika = new Tika(); String fileEntry = "C:\\Contract\\Contract1.pdf"; String filetype = tika.detect(fileEntry); System.out.println("FileType " + filetype); BodyContentHandler handler = new BodyContentHandler(-1); String text = ""; Metadata metadata = new Metadata(); FileInputStream inputstream = null; try { inputstream = new FileInputStream(fileEntry); } catch (FileNotFoundException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } ParseContext pcontext = new ParseContext(); //parsing the document using PDF parser PDFParser pdfparser = new PDFParser(); try { pdfparser.parse(inputstream, handler, metadata, pcontext); } catch (IOException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } catch (TikaException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } String docText = ""; String outputArray[]; String out[]; //getting the content of the document docText = handler.toString().replaceAll("(/[^\\da-zA-Z.]/)", ""); // PhraseDetection.getPhrases(docText); try { Node node = nodeBuilder().node(); Client client = node.client(); DocumentReader.parseString(docText, client); //"Borrowing should be replaced by the user input key" Elastic.getDefinedTerm(client, "definedterms", "term", "1", "Borrowing"); node.close(); } catch (FileNotFoundException ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } Stanford.getSentence(docText); int definedTermsEnd = docText.indexOf("SCHEDULES"); String toc = docText.substring(0, definedTermsEnd); String c = docText.substring(definedTermsEnd); System.out.println("Table of content" + toc); System.out.println("--------------------------------"); System.out.println("content" + c); out = toc.split("Article|article|ARTICLE"); int count = 0; String outputArrayString = ""; int s = 0; StringBuffer tocOutput = new StringBuffer(); for (String o : out) { if (count != 0) { s = Integer.parseInt(String.valueOf(o.charAt(1))); if (s == count) { tocOutput.append(o); tocOutput.append("JigarAnkitNeeraj"); System.out.println(s); } } outputArrayString += "Count" + count + o; count++; System.out.println(); } System.out.println("---------------------------------------------------Content---------"); count = 1; StringBuffer contentOutput = new StringBuffer(); String splitContent[] = c.split("ARTICLE|Article"); Node node = nodeBuilder().node(); Client client = node.client(); for (String o : splitContent) { o = o.replaceAll("[^a-zA-Z0-9.,\\/#!$%\\^&\\*;:{}=\\-_`~()?\\s]+", ""); o = o.replaceAll("\n", " "); char input = o.charAt(1); if (input >= '0' && input <= '9') { s = Integer.parseInt(String.valueOf(o.charAt(1))); if (s == count) { //System.out.println(s); JSONObject articleJSONObject = new JSONObject(); contentOutput.append(" \n MyArticlesSeparated \n "); articleJSONObject.put("Article" + count, o.toString()); try { try { JSONObject articleJSONObject1 = new JSONObject(); articleJSONObject1.put("hi", "j"); client.prepareIndex("contract", "article", String.valueOf(count)) .setSource(articleJSONObject.toString()).execute().actionGet(); } catch (Exception e) { System.out.println(e.getMessage()); } //"Borrowing should be replaced by the user input key" } catch (Exception ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(s); count++; } //outputArrayString += "Count" + count + o; contentOutput.append(o); } } Elastic.getDocument(client, "contract", "article", "1"); Elastic.searchDocument(client, "contract", "article", "Lenders"); Elastic.searchDocument(client, "contract", "article", "Negative Covenants"); Elastic.searchDocument(client, "contract", "article", "Change in Law"); String tableOfContent[]; tableOfContent = tocOutput.toString().split("JigarAnkitNeeraj"); String splitContectsAccordingToArticles[]; splitContectsAccordingToArticles = contentOutput.toString().split("MyArticlesSeparated"); int numberOfArticle = splitContectsAccordingToArticles.length; int countArticle = 1; Double toBeTruncated = new Double("" + countArticle + ".00"); String section = "Section"; toBeTruncated += 0.01; System.out.println(toBeTruncated); String sectionEnd; StringBuffer sectionOutput = new StringBuffer(); int skipFirstArtcile = 0; JSONObject obj = new JSONObject(); for (String article : splitContectsAccordingToArticles) { if (skipFirstArtcile != 0) { DecimalFormat f = new DecimalFormat("##.00"); String sectionStart = section + " " + f.format(toBeTruncated); int start = article.indexOf(sectionStart); toBeTruncated += 0.01; System.out.println(); sectionEnd = section + " " + f.format(toBeTruncated); int end = article.indexOf(sectionEnd); while (end != -1) { sectionStart = section + " " + f.format(toBeTruncated - 0.01); sectionOutput.append(" \n Key:" + sectionStart); if (start < end) { sectionOutput.append("\n Value:" + article.substring(start, end)); obj.put(sectionStart, article.substring(start, end).replaceAll("\\r\\n|\\r|\\n", " ")); try { try { JSONObject articleJSONObject1 = new JSONObject(); articleJSONObject1.put("hi", "j"); client.prepareIndex("contract", "section", String.valueOf(count)) .setSource(obj.toString()).execute().actionGet(); } catch (Exception e) { System.out.println(e.getMessage()); } //"Borrowing should be replaced by the user input key" } catch (Exception ex) { Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex); } } start = end; toBeTruncated += 0.01; sectionEnd = section + " " + f.format(toBeTruncated); System.out.println("SectionEnd " + sectionEnd); try { end = article.indexOf(sectionEnd); } catch (Exception e) { System.out.print(e.getMessage()); } System.out.println("End section index " + end); } end = article.length() - 1; sectionOutput.append(" \n Key:" + sectionStart); try { sectionOutput.append(" \n Value:" + article.substring(start, end)); obj.put(sectionStart, article.substring(start, end).replaceAll("\\r\\n|\\r|\\n", " ")); } catch (Exception e) { //What if Article has No Sections String numberOnly = article.replaceAll("[^0-9]", "").substring(0, 1); String sectionArticle = "ARTICLE " + numberOnly; sectionOutput.append(" \n Value:" + article); obj.put(sectionArticle, article); System.out.println(e.getMessage()); } DecimalFormat ff = new DecimalFormat("##"); toBeTruncated = Double.valueOf(ff.format(toBeTruncated)) + 1.01; } skipFirstArtcile++; } for (String article : splitContectsAccordingToArticles) { if (skipFirstArtcile != 0) { DecimalFormat f = new DecimalFormat("##.00"); String sectionStart = section + " " + f.format(toBeTruncated); int start = article.indexOf(sectionStart); toBeTruncated += 0.01; System.out.println(); sectionEnd = section + " " + f.format(toBeTruncated); int end = article.indexOf(sectionEnd); while (end != -1) { sectionStart = section + " " + f.format(toBeTruncated - 0.01); sectionOutput.append(" \n Key:" + sectionStart); if (start < end) { sectionOutput.append("\n Value:" + article.substring(start, end)); System.out.println(sectionOutput); String patternStr = "\\n\\n+[(]"; String paragraphSubstringArray[] = article.substring(start, end).split(patternStr); JSONObject paragraphObject = new JSONObject(); int counter = 0; for (String paragraphSubstring : paragraphSubstringArray) { counter++; paragraphObject.put("Paragraph " + counter, paragraphSubstring); } obj.put(sectionStart, paragraphObject); } start = end; toBeTruncated += 0.01; sectionEnd = section + " " + f.format(toBeTruncated); System.out.println("SectionEnd " + sectionEnd); try { end = article.indexOf(sectionEnd); } catch (Exception e) { System.out.print(e.getMessage()); } System.out.println("End section index " + end); } end = article.length() - 1; sectionOutput.append(" \n Key:" + sectionStart); try { sectionOutput.append(" \n Value:" + article.substring(start, end)); obj.put(sectionStart, article.substring(start, end)); PhraseDetection.getPhrases(docText); } catch (Exception e) { //What if Article has No Sections String sectionArticle = "ARTICLE"; System.out.println(e.getMessage()); } DecimalFormat ff = new DecimalFormat("##"); toBeTruncated = Double.valueOf(ff.format(toBeTruncated)) + 1.01; } skipFirstArtcile++; } Elastic.getDocument(client, "contract", "section", "1"); Elastic.searchDocument(client, "contract", "section", "Lenders"); Elastic.searchDocument(client, "contract", "section", "Negative Covenants"); try { FileWriter file = new FileWriter("TableOfIndex.txt"); file.write(tocOutput.toString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } try { FileWriter file = new FileWriter("Contract3_JSONFile.txt"); file.write(obj.toString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } try { FileWriter file = new FileWriter("Contract1_KeyValueSections.txt"); file.write(sectionOutput.toString()); file.flush(); file.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:at.tuwien.aic.Main.java
/** * Main entry point//w w w.j a va 2 s . c o m * * @param args */ @SuppressWarnings("empty-statement") public static void main(String[] args) throws IOException, InterruptedException { try { System.out.println(new java.io.File(".").getCanonicalPath()); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } TweetCrawler tc = null; try { tc = TweetCrawler.getInstance(); } catch (UnknownHostException ex) { logger.severe("Could not connect to mongoDb"); exitWithError(2); return; } int action; while (true) { action = getDecision("The following actions can be executed", new String[] { "Subscribe to topic", "Query topic", "Test preprocessing", "Recreate the evaluation model", "Quit the application" }, "What action do you want to execute?"); switch (action) { case 1: tc.collectTweets(new DefaultTweetHandler() { @Override public boolean isMatch(String topic) { return true; } }, getNonEmptyString( "Which topic do you want to subscribe to (use spaces to specify more than one keyword)?") .split(" ")); System.out.println("Starting to collection tweets"); System.out.println("Press enter to quit collecting"); while (System.in.read() != 10) ; tc.stopCollecting(); break; case 2: System.out.println("Enter tweet"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String tweet = br.readLine(); //double prediction = ClassifyTweet.classifyTweets(c, tweet, 2); System.exit(0); //classifyTopic(); break; case 3: int subAction = getDecision("The following preprocessing steps are available", new String[] { "Stop word removal", "Stemming", "Both" }, "What do you want to test?"); switch (subAction) { case 1: stopWords(); break; case 2: stem(); break; case 3: stem(stopWords()); default: break; } break; case 4: //ClassifyTweet.classifyTweetArff(c, "resources/unlabeled.arff", "resources/train.arff"); ArrayList<String> tweets = new ArrayList<>(); ArrayList<String> processedTweets = new ArrayList<>(); //Positive Tweets tweets.add( "#Office365 is the fastest growing business in Microsofts history, one out of four enterprise clients owns #Office365 in the past 12 months"); tweets.add("oh yeah back to microsoft word it's great haha"); tweets.add( "Microsoft Visual Studio 2013 Ultimate: excellent tool, but a bit pricey at $13K - http://t.co/qbc4MHeOrF"); tweets.add( "Apple 'absolutely' plans to release new product types this year - Design Week: Design WeekApple 'absolutely' p... http://t.co/EK4rIbaHa0"); tweets.add( "RT @ReformedBroker: \"Apple can't innovate.\" Motherf***er you're watching a movie on a 4 ounce plate of glass."); tweets.add( "What's the best brand of shoes?! Lol. There's too damn many, what do you prefer. Me is some Adidas."); tweets.add( "I want ?? @AdorableWords: Tribal/Aztec pattern Nike free runs ?? http://t.co/WBxT8CNsPN?"); tweets.add( "I achieved the Streak Week trophy with my Nike+ FuelBand. #nikeplus http://t.co/OgtpRcoSvp"); tweets.add("RT @DriveOfAthletes: Retweet for Nike! Favorite for UA! http://t.co/sKZ8hb27xH"); //Neutral Tweets tweets.add("This site is giving away Free Microsoft Points #XBOX LIVE http://t.co/ZR1ythfqJ4"); tweets.add( "How To Save The World: 1. Open Microsoft Word. 2. In a size 12-36 font, type \"The World\". 3. Click save."); tweets.add( "Microsoft Special Deals for Education: Microsoft special deals for Students, faculty and staff: http://t.co/Hf0b2ixPZa"); tweets.add( "Microsoft is about to take Windows XP off life support On April 8, Windows XP's life is coming to an end. On that d http://t.co/kcSf4uIqW4"); tweets.add("Microsoft open sources its internet servers http://t.co/oLNTlVjE6Y"); tweets.add( "The Apple Macintosh computer turns 30 - ... http://t.co/CAfq09Jgn7 #CarlIcahn #IsaacsonIt #SteveJobs #WalterIsaacson"); tweets.add( "News Update| Samsung opens 60 dedicated stores in Europe with Carphone Warehouse http://t.co/1voh4yPMpN"); tweets.add("I posted a new photo to Facebook http://t.co/fI40hwklUj"); tweets.add( "Brand New Men's ADIDAS VIGOR TR 3 Athletic Running shoes. Size: 11.5 http://t.co/oPuFoXLpeI"); tweets.add("I just ran 2.58 mi with Nike+. http://t.co/pYLkhBxH4Y #nikeplus"); tweets.add("Why is facebook still a thing"); //Negative Tweets tweets.add("Thank God for microsoft programs....."); tweets.add( "RT @verge: UK government once again threatens to ditch Microsoft Office http://t.co/vhvybI1GwI"); tweets.add("Apple charge far too much for very poor phone cases"); tweets.add("Here's Why Everyone Is Worried About Apple's iPhone Sales http://t.co/Eq3oPt76AG"); tweets.add("Is Apple Ready to Disrupt Another Industry? http://t.co/07gedlN0cs via @zite"); tweets.add( "Tim Cook Officially Admits iPhone 5c Didnt Meet Expectations http://t.co/OdzGZOmdv7 #iPhone #Apple"); tweets.add("@MushIsAJedi @HeyItsAmine i dont rlly like samsung that much"); tweets.add("twitter facebook die shit"); tweets.add( "I am thinking of leaving Facebook for a while... To much spying going on.. I am sick and tired of thinking about... http:/)/t.co/ULydkDEube"); tweets.add("RT @OfficialSheIdon: RIP Facebook, too many of our parents joined."); StopWordRemoval swr = new StopWordRemoval("resources/stopwords.txt"); for (String t : tweets) { t = swr.processText(t); processedTweets.add(t); } for (int i = 0; i < 28; i++) { if (i != 4) { ArrayList<Integer> results = ClassifyTweet.classifyTweets(processedTweets, i); int correctCount = 0; int positiveCorrect = 0; int neutralCorrect = 0; int negativeCorrect = 0; int falsePosNeu = 0; int falsePosNeg = 0; int falseNeuPos = 0; int falseNeuNeg = 0; int falseNegNeu = 0; int falseNegPos = 0; for (int j = 0; j < 30; j++) { int pred = results.get(j); if (j >= 0 && j < 10) { if (pred == 1) { correctCount++; positiveCorrect++; } else if (pred == 0) { falsePosNeu++; } else if (pred == -1) { falsePosNeg++; } } else if (j >= 10 && j < 20) { if (pred == 0) { correctCount++; neutralCorrect++; } else if (pred == 1) { falseNeuPos++; } else if (pred == -1) { falseNeuNeg++; } } else if (j >= 20 && j < 30) { if (pred == -1) { correctCount++; negativeCorrect++; } else if (pred == 0) { falseNegNeu++; } else if (pred == 1) { falseNegPos++; } } } System.out.println("Correct Predictions: " + correctCount + " / 30"); System.out.println("Correct Positive: " + positiveCorrect + " / 10"); System.out.println("Correct Neutral: " + neutralCorrect + " / 10"); System.out.println("Correct Negative: " + negativeCorrect + " / 10"); System.out.println("False Positive as Neutral: " + falsePosNeu); System.out.println("False Positive as Negative: " + falsePosNeg); System.out.println("False Neutral as Positive: " + falseNeuPos); System.out.println("False Neutral as Negative: " + falseNeuNeg); System.out.println("False Negative as Positive: " + falseNegPos); System.out.println("False Negative as Neutral: " + falseNegNeu); } } exit(); case 5: exit(); } } }
From source file:bluevia.examples.MODemo.java
/** * @param args/*from ww w. jav a 2 s .c o m*/ */ public static void main(String[] args) throws IOException { BufferedReader iReader = null; String apiDataFile = "API-AccessToken.ini"; String consumer_key; String consumer_secret; String registrationId; OAuthConsumer apiConsumer = null; HttpURLConnection request = null; URL moAPIurl = null; Logger logger = Logger.getLogger("moSMSDemo.class"); int i = 0; int rc = 0; Thread mThread = Thread.currentThread(); try { System.setProperty("debug", "1"); iReader = new BufferedReader(new FileReader(apiDataFile)); // Private data: consumer info + access token info + phone info consumer_key = iReader.readLine(); consumer_secret = iReader.readLine(); registrationId = iReader.readLine(); // Set up the oAuthConsumer while (true) { try { logger.log(Level.INFO, String.format("#%d: %s\n", ++i, "Requesting messages...")); apiConsumer = new DefaultOAuthConsumer(consumer_key, consumer_secret); apiConsumer.setMessageSigner(new HmacSha1MessageSigner()); moAPIurl = new URL("https://api.bluevia.com/services/REST/SMS/inbound/" + registrationId + "/messages?version=v1&alt=json"); request = (HttpURLConnection) moAPIurl.openConnection(); request.setRequestMethod("GET"); apiConsumer.sign(request); StringBuffer doc = new StringBuffer(); BufferedReader br = null; rc = request.getResponseCode(); if (rc == HttpURLConnection.HTTP_OK) { br = new BufferedReader(new InputStreamReader(request.getInputStream())); String line = br.readLine(); while (line != null) { doc.append(line); line = br.readLine(); } System.out.printf("Output message: %s\n", doc.toString()); try { JSONObject apiResponse1 = new JSONObject(doc.toString()); String aux = apiResponse1.getString("receivedSMS"); if (aux != null) { String szMessage; String szOrigin; String szDate; JSONObject smsPool = apiResponse1.getJSONObject("receivedSMS"); JSONArray smsInfo = smsPool.optJSONArray("receivedSMS"); if (smsInfo != null) { for (i = 0; i < smsInfo.length(); i++) { szMessage = smsInfo.getJSONObject(i).getString("message"); szOrigin = smsInfo.getJSONObject(i).getJSONObject("originAddress") .getString("phoneNumber"); szDate = smsInfo.getJSONObject(i).getString("dateTime"); System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate, szOrigin, szMessage); } } else { JSONObject sms = smsPool.getJSONObject("receivedSMS"); szMessage = sms.getString("message"); szOrigin = sms.getJSONObject("originAddress").getString("phoneNumber"); szDate = sms.getString("dateTime"); System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate, szOrigin, szMessage); } } } catch (JSONException e) { System.err.println("JSON error: " + e.getMessage()); } } else if (rc == HttpURLConnection.HTTP_NO_CONTENT) System.out.printf("No content\n"); else System.err.printf("Error: %d:%s\n", rc, request.getResponseMessage()); request.disconnect(); } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } mThread.sleep(15000); } } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } }