List of usage examples for java.util.logging Level SEVERE
Level SEVERE
To view the source code for java.util.logging Level SEVERE.
Click Source Link
From source file:com.frostvoid.trekwar.server.TrekwarServer.java
public static void main(String[] args) { // load language try {//from w ww. j a v a2s . c o m lang = new Language(Language.ENGLISH); } catch (IOException ioe) { System.err.println("FATAL ERROR: Unable to load language file!"); System.exit(1); } System.out.println(lang.get("trekwar_server") + " " + VERSION); System.out.println("==============================================".substring(0, lang.get("trekwar_server").length() + 1 + VERSION.length())); // Handle parameters Options options = new Options(); options.addOption(OptionBuilder.withArgName("file").withLongOpt("galaxy").hasArg() .withDescription("the galaxy file to load").create("g")); //"g", "galaxy", true, "the galaxy file to load"); options.addOption(OptionBuilder.withArgName("port number").withLongOpt("port").hasArg() .withDescription("the port number to bind to (default 8472)").create("p")); options.addOption(OptionBuilder.withArgName("number").withLongOpt("save-interval").hasArg() .withDescription("how often (in turns) to save the galaxy to disk (default: 5)").create("s")); options.addOption(OptionBuilder.withArgName("log level").withLongOpt("log").hasArg() .withDescription("sets the log level: ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF") .create("l")); options.addOption("h", "help", false, "prints this help message"); CommandLineParser cliParser = new BasicParser(); try { CommandLine cmd = cliParser.parse(options, args); String portStr = cmd.getOptionValue("p"); String galaxyFileStr = cmd.getOptionValue("g"); String saveIntervalStr = cmd.getOptionValue("s"); String logLevelStr = cmd.getOptionValue("l"); if (cmd.hasOption("h")) { HelpFormatter help = new HelpFormatter(); help.printHelp("TrekwarServer", options); System.exit(0); } if (cmd.hasOption("g") && galaxyFileStr != null) { galaxyFileName = galaxyFileStr; } else { throw new ParseException("galaxy file not specified"); } if (cmd.hasOption("p") && portStr != null) { port = Integer.parseInt(portStr); if (port < 1 || port > 65535) { throw new NumberFormatException(lang.get("port_number_out_of_range")); } } else { port = 8472; } if (cmd.hasOption("s") && saveIntervalStr != null) { saveInterval = Integer.parseInt(saveIntervalStr); if (saveInterval < 1 || saveInterval > 100) { throw new NumberFormatException("Save Interval out of range (1-100)"); } } else { saveInterval = 5; } if (cmd.hasOption("l") && logLevelStr != null) { if (logLevelStr.equalsIgnoreCase("finest")) { LOG.setLevel(Level.FINEST); } else if (logLevelStr.equalsIgnoreCase("finer")) { LOG.setLevel(Level.FINER); } else if (logLevelStr.equalsIgnoreCase("fine")) { LOG.setLevel(Level.FINE); } else if (logLevelStr.equalsIgnoreCase("config")) { LOG.setLevel(Level.CONFIG); } else if (logLevelStr.equalsIgnoreCase("info")) { LOG.setLevel(Level.INFO); } else if (logLevelStr.equalsIgnoreCase("warning")) { LOG.setLevel(Level.WARNING); } else if (logLevelStr.equalsIgnoreCase("severe")) { LOG.setLevel(Level.SEVERE); } else if (logLevelStr.equalsIgnoreCase("off")) { LOG.setLevel(Level.OFF); } else if (logLevelStr.equalsIgnoreCase("all")) { LOG.setLevel(Level.ALL); } else { System.err.println("ERROR: invalid log level: " + logLevelStr); System.err.println("Run again with -h flag to see valid log level values"); System.exit(1); } } else { LOG.setLevel(Level.INFO); } // INIT LOGGING try { LOG.setUseParentHandlers(false); initLogging(); } catch (IOException ex) { System.err.println("Unable to initialize logging to file"); System.err.println(ex); System.exit(1); } } catch (Exception ex) { System.err.println("ERROR: " + ex.getMessage()); System.err.println("use -h for help"); System.exit(1); } LOG.log(Level.INFO, "Trekwar2 server " + VERSION + " starting up"); // LOAD GALAXY File galaxyFile = new File(galaxyFileName); if (galaxyFile.exists()) { try { long timer = System.currentTimeMillis(); LOG.log(Level.INFO, "Loading galaxy file {0}", galaxyFileName); ObjectInputStream ois = new ObjectInputStream(new FileInputStream(galaxyFile)); galaxy = (Galaxy) ois.readObject(); timer = System.currentTimeMillis() - timer; LOG.log(Level.INFO, "Galaxy file loaded in {0} ms", timer); ois.close(); } catch (IOException ioe) { LOG.log(Level.SEVERE, "IO error while trying to load galaxy file", ioe); } catch (ClassNotFoundException cnfe) { LOG.log(Level.SEVERE, "Unable to find class while loading galaxy", cnfe); } } else { System.err.println("Error: file " + galaxyFileName + " not found"); System.exit(1); } // if turn == 0 (start of game), execute first turn to update fog of war. if (galaxy.getCurrentTurn() == 0) { TurnExecutor.executeTurn(galaxy); } LOG.log(Level.INFO, "Current turn : {0}", galaxy.getCurrentTurn()); LOG.log(Level.INFO, "Turn speed : {0} seconds", galaxy.getTurnSpeed() / 1000); LOG.log(Level.INFO, "Save Interval : {0}", saveInterval); LOG.log(Level.INFO, "Users / max : {0} / {1}", new Object[] { galaxy.getUserCount(), galaxy.getMaxUsers() }); // START SERVER try { server = new ServerSocket(port); LOG.log(Level.INFO, "Server listening on port {0}", port); } catch (BindException be) { LOG.log(Level.SEVERE, "Error: Unable to bind to port {0}", port); System.err.println(be); System.exit(1); } catch (IOException ioe) { LOG.log(Level.SEVERE, "Error: IO error while binding to port {0}", port); System.err.println(ioe); System.exit(1); } galaxy.startup(); Thread timerThread = new Thread(new Runnable() { @Override @SuppressWarnings("SleepWhileInLoop") public void run() { while (true) { try { Thread.sleep(1000); // && galaxy.getLoggedInUsers().size() > 0 will make server pause when nobody is logged in (TESTING) if (System.currentTimeMillis() > galaxy.nextTurnDate) { StringBuffer loggedInUsers = new StringBuffer(); for (User u : galaxy.getLoggedInUsers()) { loggedInUsers.append(u.getUsername()).append(", "); } long time = TurnExecutor.executeTurn(galaxy); LOG.log(Level.INFO, "Turn {0} executed in {1} ms", new Object[] { galaxy.getCurrentTurn(), time }); LOG.log(Level.INFO, "Logged in users: " + loggedInUsers.toString()); LOG.log(Level.INFO, "===================================================================================="); if (galaxy.getCurrentTurn() % saveInterval == 0) { saveGalaxy(); } galaxy.lastTurnDate = System.currentTimeMillis(); galaxy.nextTurnDate = galaxy.lastTurnDate + galaxy.turnSpeed; } } catch (InterruptedException e) { LOG.log(Level.SEVERE, "Error in main server loop, interrupted", e); } } } }); timerThread.start(); // ACCEPT CONNECTIONS AND DELEGATE TO CLIENT SESSIONS while (true) { Socket clientConnection; try { clientConnection = server.accept(); ClientSession c = new ClientSession(clientConnection, galaxy); Thread t = new Thread(c); t.start(); } catch (IOException ex) { LOG.log(Level.SEVERE, "IO Exception while trying to handle incoming client connection", ex); } } }
From source file:eu.tango.energymodeller.EnergyModeller.java
/** * This runs the energy modeller in standalone mode. * * @param args no args are expected.//ww w . j a va 2 s. c o m */ public static void main(String[] args) { boolean running = true; try { if (new File("energy-modeller-logging.properties").exists()) { LogManager.getLogManager() .readConfiguration(new FileInputStream(new File("energy-modeller-logging.properties"))); } } catch (FileNotFoundException ex) { Logger.getLogger(EnergyModeller.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException | SecurityException ex) { Logger.getLogger(EnergyModeller.class.getName()).log(Level.SEVERE, "Could not read the energy modeller's log settings file", ex); } /** * Only the instance that is stated in standalone mode should write to * the background database and log VM data out to disk. All other * instances should read from the database only. */ EnergyModeller modeller = new EnergyModeller(true); Logger.getLogger(EnergyModeller.class.getName()).log(Level.SEVERE, "The logger for the energy modeller has now started"); while (running) { try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(EnergyModeller.class.getName()).log(Level.SEVERE, "The energy modeller was interupted.", ex); } catch (Exception ex) { Logger.getLogger(EnergyModeller.class.getName()).log(Level.SEVERE, "An unhandled exception occured", ex); running = false; } } }
From source file:uk.co.moonsit.rmi.GraphClient.java
@SuppressWarnings("SleepWhileInLoop") public static void main(String args[]) { Properties p = new Properties(); try {//w ww .j a v a 2s.com p.load(new FileReader("graph.properties")); } catch (IOException ex) { Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex); } //String[] labels = p.getProperty("labels").split(","); GraphClient demo = null; int type = 0; boolean log = false; if (args[0].equals("-l")) { log = true; } switch (type) { case 0: try { System.setProperty("java.security.policy", "file:./client.policy"); if (System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); } String name = "GraphServer"; String host = p.getProperty("host"); System.out.println(host); Registry registry = LocateRegistry.getRegistry(host); String[] list = registry.list(); for (String s : list) { System.out.println(s); } GraphDataInterface gs = null; boolean bound = false; while (!bound) { try { gs = (GraphDataInterface) registry.lookup(name); bound = true; } catch (NotBoundException e) { System.err.println("GraphServer exception:" + e.toString()); Thread.sleep(500); } } @SuppressWarnings("null") String config = gs.getConfig(); System.out.println(config); /*float[] fs = gs.getValues(); for (float f : fs) { System.out.println(f); }*/ demo = new GraphClient(gs, 1000, 700, Float.parseFloat(p.getProperty("frequency")), log); demo.init(config); demo.run(); } catch (RemoteException e) { System.err.println("GraphClient exception:" + e.toString()); } catch (FileNotFoundException ex) { Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex); } finally { if (demo != null) { demo.close(); } } break; case 1: try { demo = new GraphClient(1000, 700, Float.parseFloat(p.getProperty("frequency"))); demo.init("A^B|Time|Error|-360|360"); demo.addData(0, 1, 100); demo.addData(0, 2, 200); demo.addData(1, 1, 50); demo.addData(1, 2, 450); } catch (FileNotFoundException ex) { Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex); } break; } }
From source file:org.eclipse.lyo.client.oslc.samples.DMFormSample.java
/** * Login to the DM server and perform some OSLC actions * @param args/*ww w . j av a 2s . c o m*/ * @throws ParseException */ public static void main(String[] args) throws ParseException { Options options = new Options(); options.addOption("url", true, "url"); options.addOption("user", true, "user ID"); options.addOption("password", true, "password"); options.addOption("project", true, "project area"); CommandLineParser cliParser = new GnuParser(); //Parse the command line CommandLine cmd = cliParser.parse(options, args); if (!validateOptions(cmd)) { logger.severe( "Syntax: java <class_name> -url https://<server>:port/<context>/ -user <user> -password <password> -project \"<project_area>\""); logger.severe( "Example: java DMFormSample -url https://exmple.com:9443/dm -user ADMIN -password ADMIN -project \"JKE Banking (Design Management)\""); return; } String webContextUrl = cmd.getOptionValue("url"); String user = cmd.getOptionValue("user"); String passwd = cmd.getOptionValue("password"); String projectArea = cmd.getOptionValue("project"); try { //STEP 1: Initialize a Jazz rootservices helper and indicate we're looking for the ArchitectureManagement catalog JazzRootServicesHelper helper = new JazzRootServicesHelper(webContextUrl, OSLCConstants.OSLC_AM_V2); //STEP 2: Create a new Form Auth client with the supplied user/password //RRC is a fronting server, so need to use the initForm() signature which allows passing of an authentication URL. //For RRC, use the JTS for the authorization URL //Set the URL to access to authorize the user. For DM, this is the JTS context. //This is a bit of a hack for readability. It is assuming DM is at context /dm. Could use a regex or UriBuilder instead. String authUrl = webContextUrl.replaceFirst("/dm", "/jts"); JazzFormAuthClient client = helper.initFormClient(user, passwd, authUrl); //STEP 3: Login in to Jazz Server if (client.formLogin() == HttpStatus.SC_OK) { //STEP 4: Get the URL of the OSLC ChangeManagement catalog String catalogUrl = helper.getCatalogUrl(); //WORKAROUND: The IBM Rational Design Manager app requires an initial GET of a protected resource using */* as the Accept type client.getResource(catalogUrl, "*/*").consumeContent(); //STEP 5: Find the OSLC Service Provider for the project area we want to work with String serviceProviderUrl = client.lookupServiceProviderUrl(catalogUrl, projectArea); //STEP 6: Get the Query Capabilities URL so that we can run some OSLC queries //WORKAROUND: DM defect 39535 prevents OSLC4J from reading the DM Service Provider resource correctly //As a workaround, for now, you can hardcode the queryCapability URL. String queryCapability = client.lookupQueryCapability(serviceProviderUrl, OSLCConstants.OSLC_AM_V2, OSLCConstants.AM_RESOURCE_TYPE); //SCENARIO A: Run a query for all AM Resources with OSLC paging of 10 items per //page turned on and list the members of the result OslcQueryParameters queryParams = new OslcQueryParameters(); OslcQuery query = new OslcQuery(client, queryCapability, 10, queryParams); OslcQueryResult result = query.submit(); boolean processAsJavaObjects = true; processPagedQueryResults(result, client, processAsJavaObjects); System.out.println("\n------------------------------\n"); //TODO: Add more DM scenarios } } catch (RootServicesException re) { logger.log(Level.SEVERE, "Unable to access the Jazz rootservices document at: " + webContextUrl + "/rootservices", re); } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); } }
From source file:AwsConsoleApp.java
public static void main(String[] args) throws Exception { System.out.println("==========================================="); System.out.println("Welcome to the AWS VPN connection creator"); System.out.println("==========================================="); init();/*w w w . j a va2s . com*/ List<String> CIDRblocks = new ArrayList<String>(); String vpnType = null; String vpnGatewayId = null; String customerGatewayId = null; String customerGatewayInfoPath = null; String routes = null; options.addOption("h", "help", false, "show help."); options.addOption("vt", "vpntype", true, "Set vpn tunnel type e.g. (ipec.1)"); options.addOption("vgw", "vpnGatewayId", true, "Set AWS VPN Gateway ID e.g. (vgw-eca54d85)"); options.addOption("cgw", "customerGatewayId", true, "Set AWS Customer Gateway ID e.g. (cgw-c16e87a8)"); options.addOption("r", "staticroutes", true, "Set static routes e.g. cutomer subnet 10.77.77.0/24"); options.addOption("vi", "vpninfo", true, "path to vpn info file c:\\temp\\customerGatewayInfo.xml"); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; // Parse command line options try { cmd = parser.parse(options, args); if (cmd.hasOption("h")) help(); if (cmd.hasOption("vt")) { log.log(Level.INFO, "Using cli argument -vt=" + cmd.getOptionValue("vt")); vpnType = cmd.getOptionValue("vt"); // Whatever you want to do with the setting goes here } else { log.log(Level.SEVERE, "Missing vt option"); help(); } if (cmd.hasOption("vgw")) { log.log(Level.INFO, "Using cli argument -vgw=" + cmd.getOptionValue("vgw")); vpnGatewayId = cmd.getOptionValue("vgw"); } else { log.log(Level.SEVERE, "Missing vgw option"); help(); } if (cmd.hasOption("cgw")) { log.log(Level.INFO, "Using cli argument -cgw=" + cmd.getOptionValue("cgw")); customerGatewayId = cmd.getOptionValue("cgw"); } else { log.log(Level.SEVERE, "Missing cgw option"); help(); } if (cmd.hasOption("r")) { log.log(Level.INFO, "Using cli argument -r=" + cmd.getOptionValue("r")); routes = cmd.getOptionValue("r"); String[] routeItems = routes.split(","); CIDRblocks = Arrays.asList(routeItems); } else { log.log(Level.SEVERE, "Missing r option"); help(); } if (cmd.hasOption("vi")) { log.log(Level.INFO, "Using cli argument -vi=" + cmd.getOptionValue("vi")); customerGatewayInfoPath = cmd.getOptionValue("vi"); } else { log.log(Level.SEVERE, "Missing vi option"); help(); } } catch (ParseException e) { log.log(Level.SEVERE, "Failed to parse comand line properties", e); help(); } /* * Amazon VPC * Create and delete VPN tunnel to customer VPN hardware */ try { //String vpnType = "ipsec.1"; //String vpnGatewayId = "vgw-eca54d85"; //String customerGatewayId = "cgw-c16e87a8"; //List<String> CIDRblocks = new ArrayList<String>(); //CIDRblocks.add("10.77.77.0/24"); //CIDRblocks.add("172.16.1.0/24"); //CIDRblocks.add("172.18.1.0/24"); //CIDRblocks.add("10.66.66.0/24"); //CIDRblocks.add("10.8.1.0/24"); //String customerGatewayInfoPath = "c:\\temp\\customerGatewayInfo.xml"; Boolean staticRoutesOnly = true; List<String> connectionIds = new ArrayList<String>(); List<String> connectionIdList = new ArrayList<String>(); connectionIdList = vpnExists(connectionIds); if (connectionIdList.size() == 0) { CreateVpnConnectionRequest vpnReq = new CreateVpnConnectionRequest(vpnType, customerGatewayId, vpnGatewayId); CreateVpnConnectionResult vpnRes = new CreateVpnConnectionResult(); VpnConnectionOptionsSpecification vpnspec = new VpnConnectionOptionsSpecification(); vpnspec.setStaticRoutesOnly(staticRoutesOnly); vpnReq.setOptions(vpnspec); System.out.println("Creating VPN connection"); vpnRes = ec2.createVpnConnection(vpnReq); String vpnConnId = vpnRes.getVpnConnection().getVpnConnectionId(); String customerGatewayInfo = vpnRes.getVpnConnection().getCustomerGatewayConfiguration(); //System.out.println("Customer Gateway Info:" + customerGatewayInfo); // Write Customer Gateway Info to file System.out.println("Writing Customer Gateway Info to file:" + customerGatewayInfoPath); try (PrintStream out = new PrintStream(new FileOutputStream(customerGatewayInfoPath))) { out.print(customerGatewayInfo); } System.out.println("Creating VPN routes"); for (String destCIDR : CIDRblocks) { CreateVpnConnectionRouteRequest routeReq = new CreateVpnConnectionRouteRequest(); CreateVpnConnectionRouteResult routeRes = new CreateVpnConnectionRouteResult(); routeReq.setDestinationCidrBlock(destCIDR); routeReq.setVpnConnectionId(vpnConnId); routeRes = ec2.createVpnConnectionRoute(routeReq); } // Parse XML file File file = new File(customerGatewayInfoPath); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(customerGatewayInfoPath); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression exprGetipAddress = xpath .compile("/vpn_connection/ipsec_tunnel/vpn_gateway/tunnel_outside_address/ip_address"); NodeList vpnGateway = (NodeList) exprGetipAddress.evaluate(document, XPathConstants.NODESET); if (vpnGateway != null) { for (int i = 0; i < vpnGateway.getLength(); i++) { String vpnGatewayIP = vpnGateway.item(i).getTextContent(); System.out .println("AWS vpnGatewayIP for tunnel " + Integer.toString(i) + " " + vpnGatewayIP); } } System.out.println("=============================================="); XPathExpression exprGetKey = xpath.compile("/vpn_connection/ipsec_tunnel/ike/pre_shared_key"); NodeList presharedKeyList = (NodeList) exprGetKey.evaluate(document, XPathConstants.NODESET); if (presharedKeyList != null) { for (int i = 0; i < presharedKeyList.getLength(); i++) { String pre_shared_key = presharedKeyList.item(i).getTextContent(); System.out.println( "AWS pre_shared_key for tunnel " + Integer.toString(i) + " " + pre_shared_key); } } System.out.println("Creating VPN creation completed!"); } else { boolean yn; Scanner scan = new Scanner(System.in); System.out.println("Enter yes or no to delete VPN connection: "); String input = scan.next(); String answer = input.trim().toLowerCase(); while (true) { if (answer.equals("yes")) { yn = true; break; } else if (answer.equals("no")) { yn = false; System.exit(0); } else { System.out.println("Sorry, I didn't catch that. Please answer yes/no"); } } // Delete all existing VPN connections System.out.println("Deleting AWS VPN connection(s)"); for (String vpnConID : connectionIdList) { DeleteVpnConnectionResult delVPNres = new DeleteVpnConnectionResult(); DeleteVpnConnectionRequest delVPNreq = new DeleteVpnConnectionRequest(); delVPNreq.setVpnConnectionId(vpnConID); delVPNres = ec2.deleteVpnConnection(delVPNreq); System.out.println("Successfully deleted AWS VPN conntion: " + vpnConID); } } } catch (AmazonServiceException ase) { System.out.println("Caught Exception: " + ase.getMessage()); System.out.println("Reponse Status Code: " + ase.getStatusCode()); System.out.println("Error Code: " + ase.getErrorCode()); System.out.println("Request ID: " + ase.getRequestId()); } }
From source file:di.uniba.it.tee2.wiki.Wikidump2Index.java
/** * language xml_dump output_dir encoding * * @param args the command line arguments *//*from w ww.java 2s .c om*/ 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")); } Wikidump2Index builder = new Wikidump2Index(); builder.init(cmd.getOptionValue("l"), cmd.getOptionValue("o")); builder.build(cmd.getOptionValue("d"), cmd.getOptionValue("l")); } else { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("Index Wikipedia dump (single thread)", options, true); } } catch (Exception ex) { Logger.getLogger(Wikidump2Index.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.archivas.clienttools.arcmover.cli.ManagedCLIJob.java
@SuppressWarnings({ "UseOfSystemOutOrSystemErr" }) public static void main(String args[]) { if (LOG.isLoggable(Level.FINE)) { StringBuffer sb = new StringBuffer(); sb.append("Program Arguments").append(NEWLINE); for (int i = 0; i < args.length; i++) { sb.append(" ").append(i).append(": ").append(args[i]); sb.append(NEWLINE);// w w w.j a va 2 s . c o m } LOG.log(Level.FINE, sb.toString()); } ConfigurationHelper.validateLaunchOK(); ManagedCLIJob arcCmd = null; try { if (args[0].equals("copy")) { arcCmd = new ArcCopy(args, 2); } else if (args[0].equals("delete")) { arcCmd = new ArcDelete(args, 2); } else if (args[0].equals("metadata")) { arcCmd = new ArcMetadata(args, 2); } else { throw new RuntimeException("Unsupported operation: " + args[0]); } arcCmd.parseArgs(); if (arcCmd.shouldPrintHelp()) { System.out.println(arcCmd.helpScreen()); } else { arcCmd.execute(new PrintWriter(System.out), new PrintWriter(System.err)); } } catch (ParseException e) { System.out.println("Error: " + e.getMessage()); System.out.println(); System.out.println(arcCmd.helpScreen()); arcCmd.setExitCode(EXIT_CODE_OPTION_PARSE_ERROR); } catch (Exception e) { LOG.log(Level.SEVERE, e.getMessage(), e); System.out.println(); System.err.println("Job failed. " + e.getMessage()); if (arcCmd != null) { arcCmd.setExitCode(EXIT_CODE_DM_ERROR); } } finally { if (arcCmd != null) { arcCmd.exit(); } } }
From source file:diplomawork.controler.MainWindow.java
/** * @param args the command line arguments *//*w ww . j a v a 2 s. com*/ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(() -> { new MainWindow().setVisible(true); }); }
From source file:edu.umn.msi.gx.mztosqlite.MzToSQLite.java
public static void main(String[] args) { try {/*from ww w . j a v a 2 s. c o 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: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();/*from w ww.ja v a 2s . c o m*/ // 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); } }