List of usage examples for java.util.logging Logger getLogger
@CallerSensitive public static Logger getLogger(String name)
From source file:DaytimeServer.java
public static void main(String args[]) { try { // Handle startup exceptions at the end of this block // Get an encoder for converting strings to bytes CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder(); // Allow an alternative port for testing with non-root accounts int port = 13; // RFC867 specifies this port. if (args.length > 0) port = Integer.parseInt(args[0]); // The port we'll listen on SocketAddress localport = new InetSocketAddress(port); // Create and bind a tcp channel to listen for connections on. ServerSocketChannel tcpserver = ServerSocketChannel.open(); tcpserver.socket().bind(localport); // Also create and bind a DatagramChannel to listen on. DatagramChannel udpserver = DatagramChannel.open(); udpserver.socket().bind(localport); // Specify non-blocking mode for both channels, since our // Selector object will be doing the blocking for us. tcpserver.configureBlocking(false); udpserver.configureBlocking(false); // The Selector object is what allows us to block while waiting // for activity on either of the two channels. Selector selector = Selector.open(); // Register the channels with the selector, and specify what // conditions (a connection ready to accept, a datagram ready // to read) we'd like the Selector to wake up for. // These methods return SelectionKey objects, which we don't // need to retain in this example. tcpserver.register(selector, SelectionKey.OP_ACCEPT); udpserver.register(selector, SelectionKey.OP_READ); // This is an empty byte buffer to receive emtpy datagrams with. // If a datagram overflows the receive buffer size, the extra bytes // are automatically discarded, so we don't have to worry about // buffer overflow attacks here. ByteBuffer receiveBuffer = ByteBuffer.allocate(0); // Now loop forever, processing client connections for (;;) { try { // Handle per-connection problems below // Wait for a client to connect selector.select();//w w w. jav a2s .com // If we get here, a client has probably connected, so // put our response into a ByteBuffer. String date = new java.util.Date().toString() + "\r\n"; ByteBuffer response = encoder.encode(CharBuffer.wrap(date)); // Get the SelectionKey objects for the channels that have // activity on them. These are the keys returned by the // register() methods above. They are returned in a // java.util.Set. Set keys = selector.selectedKeys(); // Iterate through the Set of keys. for (Iterator i = keys.iterator(); i.hasNext();) { // Get a key from the set, and remove it from the set SelectionKey key = (SelectionKey) i.next(); i.remove(); // Get the channel associated with the key Channel c = (Channel) key.channel(); // Now test the key and the channel to find out // whether something happend on the TCP or UDP channel if (key.isAcceptable() && c == tcpserver) { // A client has attempted to connect via TCP. // Accept the connection now. SocketChannel client = tcpserver.accept(); // If we accepted the connection successfully, // the send our respone back to the client. if (client != null) { client.write(response); // send respone client.close(); // close connection } } else if (key.isReadable() && c == udpserver) { // A UDP datagram is waiting. Receive it now, // noting the address it was sent from. SocketAddress clientAddress = udpserver.receive(receiveBuffer); // If we got the datagram successfully, send // the date and time in a response packet. if (clientAddress != null) udpserver.send(response, clientAddress); } } } catch (java.io.IOException e) { // This is a (hopefully transient) problem with a single // connection: we log the error, but continue running. // We use our classname for the logger so that a sysadmin // can configure logging for this server independently // of other programs. Logger l = Logger.getLogger(DaytimeServer.class.getName()); l.log(Level.WARNING, "IOException in DaytimeServer", e); } catch (Throwable t) { // If anything else goes wrong (out of memory, for example) // then log the problem and exit. Logger l = Logger.getLogger(DaytimeServer.class.getName()); l.log(Level.SEVERE, "FATAL error in DaytimeServer", t); System.exit(1); } } } catch (Exception e) { // This is a startup error: there is no need to log it; // just print a message and exit System.err.println(e); System.exit(1); } }
From source file:edu.umn.msi.gx.mztosqlite.MzToSQLite.java
public static void main(String[] args) { try {//from w w w. j a va 2s. co m MzToSQLite mzToSQLite = new MzToSQLite(); mzToSQLite.parseOptions(args); mzToSQLite.processFiles(); } catch (Exception ex) { Logger.getLogger(MzToSQLite.class.getName()).log(Level.SEVERE, null, ex); System.exit(1); } }
From source file:at.tuwien.ifs.feature.evaluation.SimilarityRetrievalWriter.java
public static void main(String[] args) throws SOMToolboxException, IOException { // register and parse all options JSAPResult config = OptionFactory.parseResults(args, OPTIONS); File inputVectorFile = config.getFile("inputVectorFile"); String outputDirStr = AbstractOptionFactory.getFilePath(config, "outputDirectory"); File outputDirBase = new File(outputDirStr); outputDirBase.mkdirs();//from w ww . j a v a2 s. co m String metricName = config.getString("metric"); DistanceMetric metric = AbstractMetric.instantiateNice(metricName); int neighbours = config.getInt("numberNeighbours"); int startIndex = config.getInt("startIndex"); int numberItems = config.getInt("numberItems", -1); try { SOMLibSparseInputData data = new SOMLibSparseInputData(inputVectorFile.getAbsolutePath()); int endIndex = data.numVectors(); if (numberItems != -1) { if (startIndex + numberItems > endIndex) { System.out.println("Specified number of items (" + numberItems + ") exceeds maximum (" + data.numVectors() + "), limiting to " + (endIndex - startIndex) + "."); } else { endIndex = startIndex + numberItems; } } StdErrProgressWriter progress = new StdErrProgressWriter(endIndex - startIndex, "processing vector "); // SortedSet<InputDistance> distances; for (int inputDatumIndex = startIndex; inputDatumIndex < endIndex; inputDatumIndex++) { InputDatum inputDatum = data.getInputDatum(inputDatumIndex); String inputLabel = inputDatum.getLabel(); if (inputDatumIndex == -1) { throw new IllegalArgumentException( "Input with label '" + inputLabel + "' not found in vector file '" + inputVectorFile + "'; possible labels are: " + StringUtils.toString(data.getLabels(), 15)); } File outputDir = new File(outputDirBase, inputLabel.charAt(2) + "/" + inputLabel.charAt(3) + "/" + inputLabel.charAt(4)); outputDir.mkdirs(); File outputFile = new File(outputDir, inputLabel + ".txt"); boolean fileExistsAndValid = false; if (outputFile.exists()) { // check if it the valid data String linesInvalid = ""; int validLineCount = 0; ArrayList<String> lines = FileUtils.readLinesAsList(outputFile.getAbsolutePath()); for (String string : lines) { if (string.trim().length() == 0) { continue; } String[] parts = string.split("\t"); if (parts.length != 2) { linesInvalid += "Line '" + string + "' invalid - contains " + parts.length + " elements.\n"; } else if (!NumberUtils.isNumber(parts[1])) { linesInvalid = "Line '" + string + "' invalid - 2nd part is not a number.\n"; } else { validLineCount++; } } if (validLineCount != neighbours) { linesInvalid = "Not enough valid lines; expected " + neighbours + ", found " + validLineCount + ".\n"; } fileExistsAndValid = true; if (org.apache.commons.lang.StringUtils.isNotBlank(linesInvalid)) { System.out.println("File " + outputFile.getAbsolutePath() + " exists, but is not valid:\n" + linesInvalid); } } if (fileExistsAndValid) { Logger.getLogger("at.tuwien.ifs.feature.evaluation").finer( "File " + outputFile.getAbsolutePath() + " exists and is valid; not recomputing"); } else { PrintWriter p = new PrintWriter(outputFile); SmallestElementSet<InputDistance> distances = data.getNearestDistances(inputDatumIndex, neighbours, metric); for (InputDistance inputDistance : distances) { p.println(inputDistance.getInput().getLabel() + "\t" + inputDistance.getDistance()); } p.close(); } progress.progress(); } } catch (IllegalArgumentException e) { System.out.println(e.getMessage() + ". Aborting."); System.exit(-1); } }
From source file:Graph_with_jframe_and_arduino.java
public static void main(String[] args) { // create and configure the window JFrame window = new JFrame(); window.setTitle("Sensor Graph GUI"); window.setSize(600, 400);//from www. ja v a2s. c om window.setLayout(new BorderLayout()); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create a drop-down box and connect button, then place them at the top of the window JComboBox<String> portList_combobox = new JComboBox<String>(); Dimension d = new Dimension(300, 100); portList_combobox.setSize(d); JButton connectButton = new JButton("Connect"); JPanel topPanel = new JPanel(); topPanel.add(portList_combobox); topPanel.add(connectButton); window.add(topPanel, BorderLayout.NORTH); //pause button JButton Pause_btn = new JButton("Start"); // populate the drop-down box SerialPort[] portNames; portNames = SerialPort.getCommPorts(); //check for new port available Thread thread_port = new Thread() { @Override public void run() { while (true) { SerialPort[] sp = SerialPort.getCommPorts(); if (sp.length > 0) { for (SerialPort sp_name : sp) { int l = portList_combobox.getItemCount(), i; for (i = 0; i < l; i++) { //check port name already exist or not if (sp_name.getSystemPortName().equalsIgnoreCase(portList_combobox.getItemAt(i))) { break; } } if (i == l) { portList_combobox.addItem(sp_name.getSystemPortName()); } } } else { portList_combobox.removeAllItems(); } portList_combobox.repaint(); } } }; thread_port.start(); for (SerialPort sp_name : portNames) portList_combobox.addItem(sp_name.getSystemPortName()); //for(int i = 0; i < portNames.length; i++) // portList.addItem(portNames[i].getSystemPortName()); // create the line graph XYSeries series = new XYSeries("line 1"); XYSeries series2 = new XYSeries("line 2"); XYSeries series3 = new XYSeries("line 3"); XYSeries series4 = new XYSeries("line 4"); for (int i = 0; i < 100; i++) { series.add(x, 0); series2.add(x, 0); series3.add(x, 0); series4.add(x, 10); x++; } XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(series); dataset.addSeries(series2); XYSeriesCollection dataset2 = new XYSeriesCollection(); dataset2.addSeries(series3); dataset2.addSeries(series4); //create jfree chart JFreeChart chart = ChartFactory.createXYLineChart("Sensor Readings", "Time (seconds)", "Arduino Reading", dataset); JFreeChart chart2 = ChartFactory.createXYLineChart("Sensor Readings", "Time (seconds)", "Arduino Reading 2", dataset2); //color render for chart 1 XYLineAndShapeRenderer r1 = new XYLineAndShapeRenderer(); r1.setSeriesPaint(0, Color.RED); r1.setSeriesPaint(1, Color.GREEN); r1.setSeriesShapesVisible(0, false); r1.setSeriesShapesVisible(1, false); XYPlot plot = chart.getXYPlot(); plot.setRenderer(0, r1); plot.setRenderer(1, r1); plot.setBackgroundPaint(Color.WHITE); plot.setDomainGridlinePaint(Color.DARK_GRAY); plot.setRangeGridlinePaint(Color.blue); //color render for chart 2 XYLineAndShapeRenderer r2 = new XYLineAndShapeRenderer(); r2.setSeriesPaint(0, Color.BLUE); r2.setSeriesPaint(1, Color.ORANGE); r2.setSeriesShapesVisible(0, false); r2.setSeriesShapesVisible(1, false); XYPlot plot2 = chart2.getXYPlot(); plot2.setRenderer(0, r2); plot2.setRenderer(1, r2); ChartPanel cp = new ChartPanel(chart); ChartPanel cp2 = new ChartPanel(chart2); //multiple graph container JPanel graph_container = new JPanel(); graph_container.setLayout(new BoxLayout(graph_container, BoxLayout.X_AXIS)); graph_container.add(cp); graph_container.add(cp2); //add chart panel in main window window.add(graph_container, BorderLayout.CENTER); //window.add(cp2, BorderLayout.WEST); window.add(Pause_btn, BorderLayout.AFTER_LAST_LINE); Pause_btn.setEnabled(false); //pause btn action Pause_btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (Pause_btn.getText().equalsIgnoreCase("Pause")) { if (chosenPort.isOpen()) { try { Output.write(0); } catch (IOException ex) { Logger.getLogger(Graph_with_jframe_and_arduino.class.getName()).log(Level.SEVERE, null, ex); } } Pause_btn.setText("Start"); } else { if (chosenPort.isOpen()) { try { Output.write(1); } catch (IOException ex) { Logger.getLogger(Graph_with_jframe_and_arduino.class.getName()).log(Level.SEVERE, null, ex); } } Pause_btn.setText("Pause"); } throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); // configure the connect button and use another thread to listen for data connectButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (connectButton.getText().equals("Connect")) { // attempt to connect to the serial port chosenPort = SerialPort.getCommPort(portList_combobox.getSelectedItem().toString()); chosenPort.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0); if (chosenPort.openPort()) { Output = chosenPort.getOutputStream(); connectButton.setText("Disconnect"); Pause_btn.setEnabled(true); portList_combobox.setEnabled(false); } // create a new thread that listens for incoming text and populates the graph Thread thread = new Thread() { @Override public void run() { Scanner scanner = new Scanner(chosenPort.getInputStream()); while (scanner.hasNextLine()) { try { String line = scanner.nextLine(); int number = Integer.parseInt(line); series.add(x, number); series2.add(x, number / 2); series3.add(x, number / 1.5); series4.add(x, number / 5); if (x > 100) { series.remove(0); series2.remove(0); series3.remove(0); series4.remove(0); } x++; window.repaint(); } catch (Exception e) { } } scanner.close(); } }; thread.start(); } else { // disconnect from the serial port chosenPort.closePort(); portList_combobox.setEnabled(true); Pause_btn.setEnabled(false); connectButton.setText("Connect"); } } }); // show the window window.setVisible(true); }
From source file:di.uniba.it.tee2.wiki.Wikidump2IndexMT.java
/** * language xml_dump output_dir n_thread encoding * * @param args the command line arguments *//* w w w .j av a 2 s . c o m*/ public static void main(String[] args) { try { CommandLine cmd = cmdParser.parse(options, args); if (cmd.hasOption("l") && cmd.hasOption("d") && cmd.hasOption("o")) { encoding = cmd.getOptionValue("e", "UTF-8"); minTextLegth = Integer.parseInt(cmd.getOptionValue("m", "4000")); /*if (cmd.hasOption("p")) { pageLimit = Integer.parseInt(cmd.getOptionValue("p")); }*/ int nt = Integer.parseInt(cmd.getOptionValue("n", "2")); Wikidump2IndexMT builder = new Wikidump2IndexMT(); builder.init(cmd.getOptionValue("l"), cmd.getOptionValue("o"), nt); //attach a shutdown hook Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { try { Wikidump2IndexMT.tee.close(); } catch (Exception ex) { Logger.getLogger(Wikidump2IndexMT.class.getName()).log(Level.SEVERE, null, ex); } } })); builder.build(cmd.getOptionValue("d"), cmd.getOptionValue("l")); } else { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("Index Wikipedia dump (multi threads)", options, true); } } catch (Exception ex) { Logger.getLogger(Wikidump2IndexMT.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:javadepchecker.Main.java
/** * @param args the command line arguments *//* w w w .j av a 2s.co m*/ public static void main(String[] args) throws IOException { int exit = 0; try { CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption("h", "help", false, "print help"); options.addOption("i", "image", true, "image directory"); options.addOption("v", "verbose", false, "print verbose output"); CommandLine line = parser.parse(options, args); String[] files = line.getArgs(); if (line.hasOption("h") || files.length == 0) { HelpFormatter h = new HelpFormatter(); h.printHelp("java-dep-check [-i <image] <package.env>+", options); } else { image = line.getOptionValue("i", ""); for (String arg : files) { if (line.hasOption('v')) System.out.println("Checking " + arg); if (!checkPkg(new File(arg))) { exit = 1; } } } } catch (ParseException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } System.exit(exit); }
From source file:javadepchecker.Main.java
/** * @param args the command line arguments *//*from ww w.j av a2 s .c o m*/ public static void main(String[] args) throws IOException { int exit = 0; try { CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption("h", "help", false, "print help"); options.addOption("i", "image", true, "image directory"); options.addOption("v", "verbose", false, "print verbose output"); CommandLine line = parser.parse(options, args); String[] files = line.getArgs(); if (line.hasOption("h") || files.length == 0) { HelpFormatter h = new HelpFormatter(); h.printHelp("java-dep-check [-i <image] <package.env>+", options); } else { image = line.getOptionValue("i", ""); for (String arg : files) { if (line.hasOption('v')) { System.out.println("Checking " + arg); } if (!checkPkg(new File(arg))) { exit = 1; } } } } catch (ParseException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } System.exit(exit); }
From source file:com.quangphuong.crawler.util.HighlightsOfflineCrawler.java
public static void main(String[] args) { webClient.getOptions().setJavaScriptEnabled(false); webClient.getOptions().setCssEnabled(false); webClient.getOptions().setThrowExceptionOnFailingStatusCode(false); // webClient.setJavaScriptTimeout(2 * 1000); int y = startY; int m = startM; int d = startD; int date = 0; File f = new File(cachePath); if (f.exists() && !f.isDirectory()) { date = (Integer) ObjectIO.read(cachePath); y = date / 10000;/*from w ww . jav a 2 s . c o m*/ m = date % 10000; d = m % 100; System.out.println("D: " + d + "-M: " + m + "-Y: " + y); } boolean goNext = true; while (date != stopDate) { date = y + m + d; // Crawler String dateStr = String.valueOf(date); String link = AppConstant.videoPrefix + dateStr; try { System.out.println("Link: " + link); HtmlPage page = webClient.getPage(link); goNext = page.getWebResponse().getStatusCode() != 503; List<HtmlElement> tables = (List<HtmlElement>) page.getByXPath(AppConstant.hightlightTables); int count = 0; String kind = ""; String tournament = ""; for (HtmlElement table : tables) { count++; //Get kind HtmlElement span = table.getFirstByXPath(AppConstant.highlightKind); if (span != null && span.getAttribute("class").equals("whitetitle")) { kind = span.getTextContent(); System.out.println(kind); } // Get Tournament if (table.getAttribute("background") != null && !"".equals(table.getAttribute("background"))) { HtmlElement el = table.getFirstByXPath(AppConstant.highlightTournament); tournament = el.getTextContent(); System.out.println(tournament); } else // Get matches { if (count != 1 && (table.getAttribute("bgcolor").equals(""))) { List<HtmlElement> matches = (List<HtmlElement>) table .getByXPath(AppConstant.highlightMatches); for (HtmlElement el : matches) { // System.out.println(el.asXml()); HtmlElement tmp = el.getFirstByXPath(AppConstant.highlightMatch); String match = tmp.getTextContent().trim(); tmp = el.getFirstByXPath(AppConstant.highlightMatchTime); String time = tmp.getTextContent().trim(); tmp = el.getFirstByXPath(AppConstant.highlightMatchLogoTeam1); String logoTeam1; try { logoTeam1 = tmp.getAttribute("src"); } catch (Exception e) { logoTeam1 = ""; } tmp = el.getFirstByXPath(AppConstant.highlightMatchScore); String score = tmp.getTextContent().trim(); tmp = el.getFirstByXPath(AppConstant.highlightMatchLogoTeam2); String logoTeam2; try { logoTeam2 = tmp.getAttribute("src"); } catch (Exception e) { logoTeam2 = ""; } // webClient.waitForBackgroundJavaScript(10 * 1000); tmp = el.getFirstByXPath(AppConstant.highlightMatchLink); String highlightLink; try { highlightLink = tmp.getAttribute("href"); } catch (Exception e) { highlightLink = ""; } tmp = el.getFirstByXPath(AppConstant.highlightMatchFullLink); String fullMatchLink; try { fullMatchLink = tmp.getAttribute("href"); } catch (Exception e) { fullMatchLink = ""; } tmp = el.getFirstByXPath(AppConstant.highlightMatchLongLink); String longHighlightLink; try { longHighlightLink = tmp.getAttribute("href"); } catch (Exception e) { longHighlightLink = ""; } System.out.println("----" + match + "-" + time + "-" + logoTeam1 + "-" + score + "-" + logoTeam2 + "-" + highlightLink + "-" + fullMatchLink + "-" + longHighlightLink); // System.out.println("kindddddddddddddddd: " + kind); Highlight highlight = new Highlight(0, kind, tournament, match, logoTeam1, logoTeam2, highlightLink, longHighlightLink, fullMatchLink, score, dateStr, time); DBWrapper dBWrapper = new DBWrapper(false); dBWrapper.updateEntity(highlight); } } } } // System.out.println("-------------------"); // System.out.println("Page memory: " + Agent.sizeOf(page)); } catch (Exception ex) { Logger.getLogger(HighlightsOfflineCrawler.class.getName()).log(Level.SEVERE, null, ex); } ObjectIO.write(cachePath, date); if (goNext) { if (m == 1200 && isLastDayOfMonth(d, m, y)) { y += 10000; m = 100; d = 1; } else if (isLastDayOfMonth(d, m, y)) { m += 100; d = 1; } else { d += 1; } } } }
From source file:com.game.ui.views.PlayerEditor.java
public static void main(String[] args) { try {//from w w w. j av a 2 s. c o m GameBean.doInit(); if (GameBean.weaponDetails.size() > 0) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); frame.add(new PlayerEditor()); frame.setName("Frame"); frame.pack(); frame.setVisible(true); } } catch (Exception ex) { Logger.getLogger(PlayerEditor.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:Trabalho.HistogramaHSB.java
public static void main(String[] args) throws IOException { EventQueue.invokeLater(() -> { try {//www . j av a 2 s .co m new HistogramaHSB().mostraTela(); } catch (IOException ex) { Logger.getLogger(HistogramaHSB.class.getName()).log(Level.SEVERE, null, ex); } }); }