public static boolean testCommand( final Context context, final String command, final String contains, final List<String> arguments) { try { final List<String> commandAndArgs = new ArrayList<String>(); commandAndArgs.add(command); commandAndArgs.addAll(arguments); final ProcessBuilder pb = new ProcessBuilder(commandAndArgs); logCommand(context, pb); final Process compilation = pb.start(); final ConsumeStream result = ConsumeStream.start(compilation.getInputStream(), null); final ConsumeStream error = ConsumeStream.start(compilation.getErrorStream(), null); compilation.waitFor(); result.join(); error.join(); return error.output.toString().contains(contains) || result.output.toString().contains(contains); } catch (IOException ex) { context.log(ex.getMessage()); return false; } catch (InterruptedException ex) { context.log(ex.getMessage()); return false; } }
public static void main(String[] args) { long head = 0; num_thread = Integer.parseInt(args[0]); long total = Long.parseLong(args[1]); section = total / ((long) num_thread); sectionHead = new long[num_thread]; long start = System.currentTimeMillis(); Thread[] threads = new Thread[num_thread]; for (int i = 0; i < num_thread; i++) { threads[i] = new Thread(new CoinFlip(i)); threads[i].start(); } for (int j = 0; j < num_thread; j++) { try { threads[j].join(); head = head + sectionHead[j]; } catch (InterruptedException e) { System.out.println( "Thread interrupted. Exception: " + e.toString() + " Message: " + e.getMessage()); return; } } long end = System.currentTimeMillis(); System.out.println(head + " heads in " + args[1] + " coin tosses"); System.out.println("Elapsed time: " + ((end - start)) + "ms"); }
// Method: runTest // Runs the script specified in the test case object public void runTest() { try { Process p = Runtime.getRuntime().exec(this.execCommandLine); InputStreamReader esr = new InputStreamReader(p.getErrorStream()); BufferedReader ereader = new BufferedReader(esr); InputStreamReader isr = new InputStreamReader(p.getInputStream()); BufferedReader ireader = new BufferedReader(isr); String line = null; String line1 = null; while ((line = ireader.readLine()) != null) { // System.out.println("Output: " + line); System.out.println(line); } while ((line1 = ereader.readLine()) != null) { System.err.println("Error: " + line1); } int exitValue = p.waitFor(); tcInstanceTools.LogMessage('d', "Test Case exit value: " + exitValue); if (exitValue == 0) { setTestCaseResult(Result.Pass); } else { setTestCaseResult(Result.Fail); } } catch (IOException ioe) { System.out.println("Error: " + ioe.getMessage()); } catch (InterruptedException e) { System.out.println("Error: " + e.getMessage()); } }
private void setExecutablePermissions(File gradleHome) { if (isWindows()) { return; } File gradleCommand = new File(gradleHome, "bin/gradle"); String errorMessage = null; try { ProcessBuilder pb = new ProcessBuilder("chmod", "755", gradleCommand.getCanonicalPath()); Process p = pb.start(); if (p.waitFor() == 0) { System.out.println("Set executable permissions for: " + gradleCommand.getAbsolutePath()); } else { BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream())); errorMessage = ""; String line; while ((line = is.readLine()) != null) { errorMessage += line + System.getProperty("line.separator"); } } } catch (IOException e) { errorMessage = e.getMessage(); } catch (InterruptedException e) { errorMessage = e.getMessage(); } if (errorMessage != null) { System.out.println( "Could not set executable permissions for: " + gradleCommand.getAbsolutePath()); System.out.println("Please do this manually if you want to use the Gradle UI."); } }
private void parseImage(Image image, File file) throws Exception { try { // Detects the file type BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputStream = new FileInputStream(file); ParseContext parseContext = new ParseContext(); // Parser AutoDetectParser parser = new AutoDetectParser(); parser.parse(inputStream, handler, metadata, parseContext); // Image field setting String date; if (metadata.getDate(metadata.ORIGINAL_DATE) != null) { date = metadata.getDate(metadata.ORIGINAL_DATE).toString(); } else if (metadata.getDate(TikaCoreProperties.CREATED) != null) { date = metadata.getDate(TikaCoreProperties.CREATED).toString(); } else if (metadata.getDate(DublinCore.CREATED) != null) { date = metadata.getDate(DublinCore.CREATED).toString(); } else if (metadata.getDate(TikaCoreProperties.METADATA_DATE) != null) { date = metadata.getDate(TikaCoreProperties.METADATA_DATE).toString(); } else if (metadata.getDate(DublinCore.MODIFIED) != null) { date = metadata.getDate(DublinCore.MODIFIED).toString(); } else { // Current date+time metadata.set(Metadata.DATE, new Date()); date = metadata.get(Metadata.DATE); } image.setLongitude(metadata.get(Geographic.LONGITUDE)); image.setLatitude(metadata.get(Geographic.LATITUDE)); ImageOperations.setMetadataParsingFinished(); if (date != null) { image.setDate(date.toString()); } else { image.setDate(null); } image.setLongitude(image.getLongitude()); image.setLatitude(image.getLatitude()); aPII.reverseGeocode(image); ImageOperations.setReverseGeocodeFinished(); ImageOperations iO = new ImageOperations(); iO.doOCR(image, file); ImageOperations.setOcrFinished(); } catch (IOException e) { System.out.println(e.getMessage()); } catch (TikaException te) { System.out.println(te.getMessage()); } catch (SAXException se) { System.out.println(se.getMessage()); } catch (InterruptedException ie) { System.out.println(ie.getMessage()); } catch (IM4JavaException je) { je.printStackTrace(); } }
/** * Set the internal {@see org.apache.zookeeper.ZooKeeper} delegate. Also implicitly closes any * delegate that was previously set. * * @param zookeeper */ public void setZookeeper(ZooKeeper zookeeper) { if (null != this.zookeeper) { try { this.zookeeper.close(); } catch (InterruptedException e) { log.error(e.getMessage(), e); } } this.zookeeper = zookeeper; }
// This may be aborted if there are stagnant requests sitting in queue. // This needs fixed to discard outstanding save requests. public synchronized void forceSave() { try { Future<?> future = delayedSave(configFile); if (future != null) { future.get(); } } catch (InterruptedException ex) { LOGGER.log(Level.SEVERE, ex.getMessage(), ex); } catch (ExecutionException ex) { LOGGER.log(Level.SEVERE, ex.getMessage(), ex); } }
public void stop() { if (streamReader == null || !streamReader.isAlive()) { System.out.println("Camera already stopped"); return; } keepAlive = false; try { streamReader.join(); } catch (InterruptedException e) { System.err.println(e.getMessage()); } }
/** * Returns control when task is complete. * * @param json * @param logger */ private String waitForDeploymentCompletion(JSON json, OctopusApi api, Log logger) { final long WAIT_TIME = 5000; final double WAIT_RANDOM_SCALER = 100.0; JSONObject jsonObj = (JSONObject) json; String id = jsonObj.getString("TaskId"); Task task = null; String lastState = "Unknown"; try { task = api.getTask(id); } catch (IOException ex) { logger.error("Error getting task: " + ex.getMessage()); return null; } logger.info("Task info:"); logger.info("\tId: " + task.getId()); logger.info("\tName: " + task.getName()); logger.info("\tDesc: " + task.getDescription()); logger.info("\tState: " + task.getState()); logger.info("\n\nStarting wait..."); boolean completed = task.getIsCompleted(); while (!completed) { try { task = api.getTask(id); } catch (IOException ex) { logger.error("Error getting task: " + ex.getMessage()); return null; } completed = task.getIsCompleted(); lastState = task.getState(); logger.info("Task state: " + lastState); if (completed) { break; } try { Thread.sleep(WAIT_TIME + (long) (Math.random() * WAIT_RANDOM_SCALER)); } catch (InterruptedException ex) { logger.info("Wait interrupted!"); logger.info(ex.getMessage()); completed = true; // bail out of wait loop } } logger.info("Wait complete!"); return lastState; }
/** Обработчик всех событий помещенных в очередь */ void processEvents() { for (; ; ) { WatchKey key; try { key = watcher.take(); } catch (InterruptedException x) { LOG.log(Level.SEVERE, x.getMessage()); return; } Path dir = keys.get(key); if (dir == null) { LOG.log(Level.SEVERE, "Входной каталог не найден!"); continue; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind kind = event.kind(); // TODO - подумать над обработчиком события OVERFLOW if (kind == OVERFLOW) { continue; } WatchEvent<Path> ev = cast(event); Path name = ev.context(); Path child = dir.resolve(name); // логируем событие if (kind == ENTRY_CREATE) { LOG.log(Level.FINEST, "{0}: {1}", new Object[] {event.kind().name(), child}); Runnable worker = new WorkerThread(child); executor.execute(worker); } } boolean valid = key.reset(); if (!valid) { keys.remove(key); if (keys.isEmpty()) { break; } } } }
public void run() { while (1 == 1) { System.out.println("Start run OneTimeTimer.bat..."); try { Runtime rt = Runtime.getRuntime(); // this.sProcess = rt.exec("GuardEternal.bat"); this.sProcess = rt.exec("OneTimeTimer.bat"); Process pr = this.sProcess; BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream())); this.sProcessReader = input; String line = null; System.out.println( "========================= OneTimeTimer.bat Start ========================="); while ((line = input.readLine()) != null) { System.out.println(line); } int exitVal = pr.waitFor(); System.out.println( "========================= OneTimeTimer.bat end ========================="); } catch (Exception e) { System.out.println("Execute bat failed: " + e.getMessage()); } try { System.out.println("Sleep 10 mins"); Thread.sleep(10 * 60 * 1000); } catch (InterruptedException e) { System.out.println("Server thread sleep(1000) failed: " + e.getMessage()); } } }
private static BufferedImage convertToBufferedImage(Image image) throws IOException { if (image instanceof BufferedImage) { return (BufferedImage) image; } else { MediaTracker tracker = new MediaTracker(null /*not sure how this is used*/); tracker.addImage(image, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { throw new IOException(e.getMessage()); } BufferedImage bufImage = new BufferedImage( image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics g = bufImage.createGraphics(); g.drawImage(image, 0, 0, null); return bufImage; } }
public String getStatusDetails(String process, String statusUrl, int expectedCount) { try { Thread.sleep(2 * 1000); int time = 0; reader = new StatusReader(); String status = null; while (true) { status = reader.getDetails(process, statusUrl, expectedCount); if (status == null) { time += 5 * 1000; if (time >= timeout * fivSec) return status; Thread.sleep(fivSec); continue; } else break; } return status; } catch (InterruptedException e) { e.printStackTrace(); return e.getMessage(); } }
public String checkStatus(String process, String statusUrl, int expectedCount) { try { Thread.sleep(2 * 1000); int time = 0; reader = new StatusReader(); Status status = Status.Pending; while (true) { status = reader.getStatus(process, statusUrl, expectedCount); if (status.equals(Status.Pending)) { time += 5 * 1000; if (time >= timeout * fivSec) return status.Timeout.getText(); Thread.sleep(fivSec); continue; } else break; } return status.getText(); } catch (InterruptedException e) { e.printStackTrace(); return e.getMessage(); } }
public void run() { String messageString; long lastActivity = System.currentTimeMillis(); while (keeprunning) { try { if (in.ready()) { messageString = in.readLine(); if (messageString == null) continue; Message m = new Message(messageString); if (m.getCommand().matches("\\d+")) try { int intcommand = Integer.parseInt(m.getCommand()); if (intcommand == Constants.RPL_ENDOFMOTD) { System.err.println("MOTD SEEN, must be connected."); if (connected) joinChannels(); connected = true; } else if (intcommand == Constants.ERR_NICKNAMEINUSE) { System.err.println("NICKNAMEINUSE"); namecount++; BotStats.getInstance().setBotname(botdefaultname + namecount); new Message("", "NICK", BotStats.getInstance().getBotname(), "").send(); new Message( "", "USER", BotStats.getInstance().getBotname() + " nowhere.com " + BotStats.getInstance().getServername(), BotStats.getInstance().getClientName() + " v." + BotStats.getInstance().getVersion()) .send(); System.err.println("Setting nick to:" + botdefaultname + namecount); } } catch (NumberFormatException nfe) { // we ignore this System.err.println("Unknown command:" + m.getCommand()); } if (m.getCommand().equals("PING")) { outqueue.add(new Message("", "PONG", "", m.getTrailing())); if (debug) System.out.println("PUNG at " + new Date()); } else if (BotStats.getInstance().containsIgnoreName(m.getSender())) { if (debug) System.out.println("Ignored: " + m); } else { inqueue.add(m); // add to inqueue if (debug) System.out.println(m.toString()); // System.out.println("Inbuffer: prefix: " + m.prefix + " params: " + m.params + " // trailing:" // + m.trailing + " command:" + m.command + " sender: " + m.sender + "\n " // + "isCTCP:" + m.isCTCP + " isPrivate:" + m.isPrivate + " CTCPCommand:" + // m.CTCPCommand // + " CTCPMessage:" + m.CTCPMessage); } lastActivity = System.currentTimeMillis(); } else { if (System.currentTimeMillis() - lastActivity > 400000) { System.err.println("400 seconds since last activity! Attempting reconnect"); in.close(); oh.disconnect(); keeprunning = false; reconnect(); return; } sleep(100); } } catch (IOException ioe) { System.out.println("EOF on connection: " + ioe.getMessage()); } catch (InterruptedException ie) { System.out.println("Interrupted: " + ie.getMessage()); } catch (Exception e) { System.err.println("Unexpected exception in InputHandler :"); e.printStackTrace(); } } }