protected void createDefenseMissile(String whoLaunchMeId, String targetId, int destructTime) { // must use final for inner thread final int tempDestructTime = destructTime; final String tempLauncherId = whoLaunchMeId, tempTargetId = targetId; Thread temp = new Thread( threadGroup, new Runnable() { @Override public void run() { try { // wait until launch time in XML sleep(tempDestructTime * Utils.SECOND); // update the war if (tempLauncherId.charAt(0) == 'D') { war.interceptGivenMissile(tempLauncherId, tempTargetId); } else war.interceptGivenLauncher(tempLauncherId, tempTargetId); } catch (InterruptedException e) { // System.out.println("The program is close before expected"); // System.out.println(e.getStackTrace()); } } }); temp.start(); }
/** * @param args 1. rddl description file name (can be directory), in RDDL format, with complete * path 2. (optional) port number 3. (optional) random seed */ public static void main(String[] args) { // StateViz state_viz = new GenericScreenDisplay(true); StateViz state_viz = new NullScreenDisplay(false); ArrayList<RDDL> rddls = new ArrayList<RDDL>(); int port = PORT_NUMBER; if (args.length < 1) { System.out.println( "usage: rddlfilename (optional) portnumber random-seed state-viz-class-name"); System.out.println("\nexample 1: Server rddlfilename"); System.out.println("example 2: Server rddlfilename 2323"); System.out.println("example 3: Server rddlfilename 2323 0 rddl.viz.GenericScreenDisplay"); System.exit(1); } try { // Load RDDL files RDDL rddl = new RDDL(); File f = new File(args[0]); if (f.isDirectory()) { for (File f2 : f.listFiles()) if (f2.getName().endsWith(".rddl")) { System.out.println("Loading: " + f2); rddl.addOtherRDDL(parser.parse(f2)); } } else rddl.addOtherRDDL(parser.parse(f)); if (args.length > 1) { port = Integer.valueOf(args[1]); } ServerSocket socket1 = new ServerSocket(port); if (args.length > 2) { Server.rand = new Random(Integer.valueOf(args[2])); } else { Server.rand = new Random(DEFAULT_SEED); } if (args.length > 3) { state_viz = (StateViz) Class.forName(args[3]).newInstance(); } System.out.println("RDDL Server Initialized"); while (true) { Socket connection = socket1.accept(); Runnable runnable = new Server(connection, ++ID, rddl, state_viz); Thread thread = new Thread(runnable); thread.start(); } } catch (Exception e) { // TODO Auto-generated catch block System.out.println(e); e.printStackTrace(); } }
@Override public BufferedImage composeImageForSector( Sector sector, int canvasWidth, int canvasHeight, double aspectRatio, int levelNumber, String mimeType, boolean abortOnError, BufferedImage image, int timeout) throws Exception { if (sector == null) { String message = Logging.getMessage("nullValue.SectorIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } ComposeImageTile tile = new ComposeImageTile( sector, mimeType, this.getLevels().getLastLevel(), canvasWidth, canvasHeight); try { if (image == null) image = new BufferedImage(canvasWidth, canvasHeight, BufferedImage.TYPE_INT_RGB); downloadImage(tile, mimeType, timeout); Thread.sleep(1); // generates InterruptedException if thread has been interupted BufferedImage tileImage = ImageIO.read(tile.getFile()); Thread.sleep(1); // generates InterruptedException if thread has been interupted ImageUtil.mergeImage(sector, tile.getSector(), aspectRatio, tileImage, image); Thread.sleep(1); // generates InterruptedException if thread has been interupted this.firePropertyChange(AVKey.PROGRESS, 0d, 1d); } catch (InterruptedIOException e) { throw e; } catch (Exception e) { if (abortOnError) throw e; String message = Logging.getMessage("generic.ExceptionWhileRequestingImage", tile.getPath()); Logging.logger().log(java.util.logging.Level.WARNING, message, e); } return image; }
private static InputStream getAsInputStreamFromClassLoader(String filename) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); InputStream is = cl == null ? null : cl.getResourceAsStream(filename); if (is == null) { // check system class loader is = XmlConfigurator.class.getClassLoader().getResourceAsStream(filename); } return is; }
protected void createEnemyMissile( String missileId, String destination, int launchTime, int flyTime, int damage, String launcherId) { // must use final for inner thread final int tempLaunchTime = launchTime; final int tempDamage = damage; final int tempFlyTime = flyTime; final String tempLauncherId = launcherId; final String tempDestination = destination; final String tempMissileId = missileId; Thread temp = new Thread( threadGroup, new Runnable() { @Override public void run() { try { // wait until launch time in XML sleep(tempLaunchTime * Utils.SECOND); // update the id's IdGenerator.updateEnemyMissileId(tempMissileId); // add to the war war.launchEnemyMissile(tempLauncherId, tempDestination, tempDamage, tempFlyTime); } catch (InterruptedException e) { } } }); temp.start(); }
public static void main(String[] args) throws Exception { String input_file = null; XmlConfigurator conf; boolean old_format = false; for (int i = 0; i < args.length; i++) { if (args[i].equals("-old")) { old_format = true; continue; } if (args[i].equals("-file")) { input_file = args[++i]; continue; } help(); return; } if (input_file != null) { InputStream input = null; try { input = new FileInputStream(new File(input_file)); } catch (Throwable t) { } if (input == null) { try { input = new URL(input_file).openStream(); } catch (Throwable t) { } } if (input == null) input = Thread.currentThread().getContextClassLoader().getResourceAsStream(input_file); if (old_format) { String cfg = inputAsString(input); List<ProtocolConfiguration> tmp = Configurator.parseConfigurations(cfg); System.out.println(dump(tmp)); } else { conf = XmlConfigurator.getInstance(input); String tmp = conf.getProtocolStackString(); System.out.println("\n" + tmp); } } else { log.error("no input file given"); } }
public String doCommand(String cmd, String args[]) { if (cmd.equals("store")) { cmd += "Expression"; } else if (cmd.equals("assertSelected") || cmd.equals("verifySelected")) { if (args[1].startsWith(INDEX_SPECIFIER)) { cmd += "Index"; args[1] = args[1].substring(INDEX_SPECIFIER.length()); } else if (args[1].startsWith(ID_SPECIFIER)) { cmd += "Id"; args[1] = args[1].substring(ID_SPECIFIER.length()); } else if (args[1].startsWith(LABEL_SPECIFIER)) { cmd += "Label"; args[1] = args[1].substring(LABEL_SPECIFIER.length()); } else if (args[1].startsWith(VALUE_SPECIFIER)) { cmd += "Value"; args[1] = args[1].substring(VALUE_SPECIFIER.length()); } else { cmd += "Label"; } } else if (cmd.endsWith("ErrorOnNext") || cmd.endsWith("FailureOnNext")) { expectError = true; return "OK"; } else if (cmd.equals("echo")) { return "OK," + args[0]; } else if (cmd.equals("pause")) { try { Thread.sleep(Integer.parseInt(args[0])); return "OK"; } catch (InterruptedException e) { return "ERROR: pause interrupted"; } } try { String result = super.doCommand(cmd, args); if (expectError) { throw new SeleniumException("ERROR: Error expected"); } else { return result; } } catch (SeleniumException e) { if (expectError) { expectError = false; return "OK"; } else { throw e; } } }
public void parse(String xmlInputFileName, String xmlOutputFileName) throws Exception { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse( Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlInputFileName)); removeEvenNodes(document); removeSpaces(document); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, OUTPUT_KEYS_INTEND_YES); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(new File(xmlOutputFileName)); transformer.transform(source, result); } catch (ParserConfigurationException | TransformerException | SAXException | IOException e) { LOGGER.error(e.toString(), e); throw e; } }
private void processResources(Session session, Element element, HashMap additionalInformation) { dataFiles = new ArrayList(); missingDataFiles = new ArrayList(); NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); if (missingDataFiles.size() > 0) { StringBuffer message = new StringBuffer(); message.append("<html>The following data file(s) could not be located.<ul>"); for (ResourceLocator file : missingDataFiles) { if (file.isLocal()) { message.append("<li>"); message.append(file.getPath()); message.append("</li>"); } else { message.append("<li>Server: "); message.append(file.getServerURL()); message.append(" Path: "); message.append(file.getPath()); message.append("</li>"); } } message.append("</ul>"); message.append("Common reasons for this include: "); message.append("<ul><li>The session or data files have been moved.</li> "); message.append( "<li>The data files are located on a drive that is not currently accessible.</li></ul>"); message.append("</html>"); MessageUtils.showMessage(message.toString()); } if (dataFiles.size() > 0) { final List<String> errors = new ArrayList<String>(); // Load files concurrently -- TODO, put a limit on # of threads? List<Thread> threads = new ArrayList(dataFiles.size()); long t0 = System.currentTimeMillis(); int i = 0; List<Runnable> synchronousLoads = new ArrayList<Runnable>(); for (final ResourceLocator locator : dataFiles) { final String suppliedPath = locator.getPath(); final String relPath = fullToRelPathMap.get(suppliedPath); Runnable runnable = new Runnable() { public void run() { List<Track> tracks = null; try { tracks = igv.load(locator); for (Track track : tracks) { if (track == null) { log.info("Null track for resource " + locator.getPath()); continue; } String id = track.getId(); if (id == null) { log.info("Null track id for resource " + locator.getPath()); continue; } if (relPath != null) { id = id.replace(suppliedPath, relPath); } List<Track> trackList = trackDictionary.get(id); if (trackList == null) { trackList = new ArrayList(); trackDictionary.put(id, trackList); } trackList.add(track); } } catch (Exception e) { log.error("Error loading resource " + locator.getPath(), e); String ms = "<b>" + locator.getPath() + "</b><br>&nbs;p " + e.toString() + "<br>"; errors.add(ms); } } }; boolean isAlignment = locator.getPath().endsWith(".bam") || locator.getPath().endsWith(".entries") || locator.getPath().endsWith(".sam"); // Run synchronously if in batch mode or if there are no "track" elments, or if this is an // alignment file if (isAlignment || Globals.isBatch() || !hasTrackElments) { synchronousLoads.add(runnable); } else { Thread t = new Thread(runnable); threads.add(t); t.start(); } i++; } // Wait for all threads to complete for (Thread t : threads) { try { t.join(); } catch (InterruptedException ignore) { } } // Now load data that must be loaded synchronously for (Runnable runnable : synchronousLoads) { runnable.run(); } long dt = System.currentTimeMillis() - t0; log.debug("Total load time = " + dt); if (errors.size() > 0) { StringBuffer buf = new StringBuffer(); buf.append("<html>Errors were encountered loading the session:<br>"); for (String msg : errors) { buf.append(msg); } MessageUtils.showMessage(buf.toString()); } } dataFiles = null; }
/** * the constructor of the class * * @param editor the editor */ public ResourceImageManager(Editor editor) { this.editor = editor; // the listener to the svg handle changes editor .getHandlesManager() .addHandlesListener( new HandlesListener() { @Override public void handleChanged(SVGHandle currentHandle, Set<SVGHandle> handles) { // removes the frames that have been closed from the map for (SVGHandle handle : new LinkedList<SVGHandle>(handleToIdToImages.keySet())) { if (handle != null && !handles.contains(handle)) { handleToIdToImages.remove(handle); } } // removes the image representations that belongs to disposed // svg handles for (ResourceRepresentation rep : new HashSet<ResourceRepresentation>(resourceRepresentationList)) { if (rep != null && !handles.contains(rep.getSVGHandle())) { rep.dispose(); resourceRepresentationList.remove(rep); } } } }); // sets the format used to convert numbers into a string DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setDecimalSeparator('.'); format = new DecimalFormat("######.#", symbols); // the queue manager queueManager = new Thread() { @Override public void run() { Runnable runnable = null; while (true) { while (queue.size() > 0) { // getting the runnable runnable = queue.get(0); // removing it from the queue queue.remove(runnable); // running the runnable runnable.run(); runnable = null; } try { sleep(100); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } }; queueManager.start(); }
public static void main(String[] args) { String specloc = System.getProperty("spec"); if (specloc == null) { System.out.print("No spec file given, quitting"); System.exit(0); } DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z"); java.util.Date date = new java.util.Date(); String startstamp = dateFormat.format(date); boolean firstrun = true; while (true) { System.out.println("Loading XML Spec file: " + specloc); // BufferedWriter out = null; SocketAcceptor acceptor = null; SocketAcceptor statusacceptor = null; Vector<MonitorThread> monitorlist = new Vector<MonitorThread>(); try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new File(specloc)); doc.getDocumentElement().normalize(); String heartbeatportString = doc.getDocumentElement().getAttribute("heartbeatport"); String statusportString = doc.getDocumentElement().getAttribute("statusport"); String logfiledir = doc.getDocumentElement().getAttribute("logfiledir"); String masterlabel = doc.getDocumentElement().getAttribute("label"); String nodeid = doc.getDocumentElement().getAttribute("id"); String smtphost = doc.getDocumentElement().getAttribute("smtphost"); String l1mailto = doc.getDocumentElement().getAttribute("l1mailto"); String l2mailto = doc.getDocumentElement().getAttribute("l2mailto"); String l2threshold = doc.getDocumentElement().getAttribute("l2threshold"); if (heartbeatportString == null || heartbeatportString.equals("")) { System.out.println("No heartbeat specified in spec, quitting"); System.exit(0); } if (statusportString == null || statusportString.equals("")) { System.out.println("No status port specified in spec, quitting"); System.exit(0); } if (logfiledir == null || logfiledir.equals("")) { System.out.println("No logfile directory location specified in spec, quitting"); System.exit(0); } int heartbeatport = Integer.valueOf(heartbeatportString).intValue(); System.out.println("This Monitor is using port " + heartbeatport + " for heartbeat"); int statusport = Integer.valueOf(statusportString).intValue(); System.out.println("This Monitor is using port " + statusport + " for status updates"); System.out.println("Logging to directory " + logfiledir); Log log = new Log(logfiledir); log.nodelabel = masterlabel; log.setMailer(smtphost, l1mailto, l2mailto, convertStringToInt(l2threshold)); if (firstrun) { firstrun = false; log.logit("Monitor Node Started", "start", null); } log.logit("Logging started", "", null); ThreadPing threadping = new ThreadPing(log, false); Thread pinger = new Thread(threadping); threadping.thisThread = pinger; pinger.start(); log.pinger = threadping; // ShutdownHook hook = new ShutdownHook(out); // Runtime.getRuntime().addShutdownHook(hook); // Starting Heartbeat server acceptor = new NioSocketAcceptor(); acceptor.getSessionConfig().setReuseAddress(true); acceptor.getSessionConfig().setTcpNoDelay(true); acceptor.setReuseAddress(true); // acceptor.getFilterChain().addLast("logger", new LoggingFilter()); acceptor .getFilterChain() .addLast( "codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")))); acceptor.setReuseAddress(true); // acceptor.setCloseOnDeactivation(true); acceptor.getSessionConfig().setTcpNoDelay(true); acceptor.setDefaultLocalAddress(new InetSocketAddress(heartbeatport)); Vector<IoSession> sessionlist = new Vector<IoSession>(); acceptor.setHandler(new HeartBeatHandler(sessionlist)); acceptor.bind(); // Starting Path Monitoring NodeList listOfServers = doc.getElementsByTagName("check"); int totalServers = listOfServers.getLength(); System.out.println("Total # of checks: " + totalServers); // Vector<PingMonitorThread> pinglist = new Vector<PingMonitorThread>(); // Vector<PortMonitorThread> portlist = new Vector<PortMonitorThread>(); // Vector<HeartbeatMonitorThread> heartbeatlist = new Vector<HeartbeatMonitorThread>(); System.out.println(); for (int i = 0; i < totalServers; i++) { Node serverNode = listOfServers.item(i); Element serverNodeElement = (Element) serverNode; String checklabel = serverNodeElement.getAttribute("label"); String host = serverNodeElement .getElementsByTagName("host") .item(0) .getChildNodes() .item(0) .getNodeValue(); String checktype = serverNodeElement .getElementsByTagName("checktype") .item(0) .getChildNodes() .item(0) .getNodeValue(); boolean enabled = true; if (serverNodeElement.getElementsByTagName("enabled").item(0) != null && serverNodeElement .getElementsByTagName("enabled") .item(0) .getChildNodes() .item(0) .getNodeValue() .toLowerCase() .equals("false")) { enabled = false; } String successrateString = serverNodeElement .getElementsByTagName("successrate") .item(0) .getChildNodes() .item(0) .getNodeValue(); String retryrateString = serverNodeElement .getElementsByTagName("retryrate") .item(0) .getChildNodes() .item(0) .getNodeValue(); // String l2thresholdoverride = // serverNodeElement.getElementsByTagName("l2threshold").item(0).getChildNodes().item(0).getNodeValue(); String l2thresholdoverride = getElementValue("l2threshold", serverNodeElement); // String l1mailtoadd = // serverNodeElement.getElementsByTagName("l1mailto").item(0).getChildNodes().item(0).getNodeValue(); String l1mailtoadd = getElementValue("l1mailto", serverNodeElement); // String l2mailtoadd = // serverNodeElement.getElementsByTagName("l2mailto").item(0).getChildNodes().item(0).getNodeValue(); String l2mailtoadd = getElementValue("l2mailto", serverNodeElement); int l2thresholdoverrideint = convertStringToInt(l2thresholdoverride); String[] l1mailtoaddarray = new String[0]; String[] l2mailtoaddarray = new String[0]; if (!l1mailtoadd.equals("")) { l1mailtoaddarray = l1mailtoadd.split(","); } if (!l2mailtoadd.equals("")) { l2mailtoaddarray = l2mailtoadd.split(","); } // System.out.println(l1mailtoaddarray.length + "-" + l2mailtoaddarray.length); int successrate = 30; int retryrate = 30; if (host == null || host.equals("")) { System.out.println("No Host, skipping this path"); enabled = false; } if (successrateString == null || successrateString.equals("")) { System.out.println( "No Success Rate defined, using default (" + successrate + " seconds)"); } else { successrate = Integer.valueOf(successrateString).intValue(); } if (retryrateString == null || retryrateString.equals("")) { System.out.println("No retry rate defined, using default (" + retryrate + " seconds)"); } else { retryrate = Integer.valueOf(retryrateString).intValue(); } System.out.println(checklabel); if (checktype.equals("heartbeat")) { String portString = serverNodeElement .getElementsByTagName("port") .item(0) .getChildNodes() .item(0) .getNodeValue(); if (portString == null || portString.equals("")) { System.out.println("No Heartbeat, skipping this path"); } else { int heartbeat = Integer.valueOf(portString).intValue(); System.out.println("Starting Heartbeat Check:"); System.out.println("Host: " + host); System.out.println("Port: " + heartbeat); System.out.println(); HeartbeatMonitorThread m = new HeartbeatMonitorThread( host, heartbeat, log, successrate, retryrate, checklabel); m.setAlertOverride(l2thresholdoverrideint, l1mailtoaddarray, l2mailtoaddarray); Thread t = new Thread(m); m.thisthread = t; if (enabled) { t.start(); log.logit( "Starting Heartbeat Check - " + host + ":" + heartbeat, "enable-" + successrate + "-" + retryrate, m.getStatus()); } else { log.logit( "Heartbeat Check - " + host + ":" + heartbeat + " Disabled on start", "disable", m.getStatus()); } monitorlist.add(m); } } else if (checktype.equals("ping")) { System.out.println("Starting Ping Check:"); System.out.println("Host: " + host); System.out.println(); PingMonitorThread m = new PingMonitorThread(host, log, successrate, retryrate, checklabel); m.setAlertOverride(l2thresholdoverrideint, l1mailtoaddarray, l2mailtoaddarray); Thread t = new Thread(m); m.thisthread = t; if (enabled) { t.start(); log.logit( "Starting Ping Check - " + host, "enable-" + successrate + "-" + retryrate, m.getStatus()); } else { log.logit("Ping Check - " + host + " Disabled on start", "disable", m.getStatus()); } monitorlist.add(m); } else if (checktype.equals("port")) { String portString = serverNodeElement .getElementsByTagName("port") .item(0) .getChildNodes() .item(0) .getNodeValue(); if (portString == null || portString.equals("")) { System.out.println("No Port Given, skipping"); } else { int heartbeat = Integer.valueOf(portString).intValue(); System.out.println("Starting Port Check:"); System.out.println("Host: " + host); System.out.println("Port: " + heartbeat); System.out.println(); PortMonitorThread m = new PortMonitorThread(host, heartbeat, log, successrate, retryrate, checklabel); m.setAlertOverride(l2thresholdoverrideint, l1mailtoaddarray, l2mailtoaddarray); Thread t = new Thread(m); m.thisthread = t; if (enabled) { t.start(); log.logit( "Starting Port Check - " + host + ":" + heartbeat, "enable-" + successrate + "-" + retryrate, m.getStatus()); } else { log.logit( "Port Check - " + host + ":" + heartbeat + " Disabled on start", "disable", m.getStatus()); } monitorlist.add(m); } } } statusacceptor = new NioSocketAcceptor(); statusacceptor.setReuseAddress(true); // statusacceptor.getFilterChain().addLast("logger", new LoggingFilter()); statusacceptor.getSessionConfig().setTcpNoDelay(true); statusacceptor.getSessionConfig().setKeepAlive(true); statusacceptor.getSessionConfig().setBothIdleTime(5); statusacceptor.getSessionConfig().setReaderIdleTime(5); statusacceptor.getSessionConfig().setWriteTimeout(5); // statusacceptor.setReuseAddress(true); statusacceptor.setCloseOnDeactivation(true); statusacceptor.setDefaultLocalAddress(new InetSocketAddress(statusport)); statusacceptor.setHandler( new StatusHttpProtocolHandler( monitorlist, acceptor, statusacceptor, log, masterlabel, nodeid, sessionlist, startstamp)); statusacceptor.bind(); System.out.println("Status Listener activated..."); } catch (Exception e) { e.printStackTrace(); try { // out.flush(); // out.close(); } catch (Exception e2) { } try { Thread.sleep(30000); } catch (Exception e3) { } } for (int x = 0; x < monitorlist.size(); x++) { if (monitorlist.get(x).getThisThread() != null) { try { monitorlist.get(x).getThisThread().join(); } catch (Exception e) { } } } if (acceptor != null) { while (acceptor.isActive() || !acceptor.isDisposed()) { try { Thread.sleep(1000); } catch (Exception e) { } } } if (statusacceptor != null) { while (statusacceptor.isActive() || !statusacceptor.isDisposed()) { try { Thread.sleep(1000); } catch (Exception e) { } } } System.out.println("Main thread has reached end, reloading..."); /* try { Thread.sleep(9999999); } catch (Exception e) { e.printStackTrace(); } */ } }