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; } }
private static void exec(String command) { try { System.out.println("Invoking: " + command); Process p = Runtime.getRuntime().exec(command); // get standard output BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = input.readLine()) != null) { System.out.println(line); } input.close(); // get error output input = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((line = input.readLine()) != null) { System.out.println(line); } input.close(); p.waitFor(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }
public void run() throws Exception { Thread[] threads = new Thread[THREADS]; for (int i = 0; i < THREADS; i++) { try { threads[i] = new Thread(peerFactory.newClient(this), "Client " + i); } catch (Exception e) { e.printStackTrace(); return; } threads[i].start(); } try { for (int i = 0; i < THREADS; i++) { threads[i].join(); } } catch (InterruptedException e) { setFailed(); e.printStackTrace(); } if (failed) { throw new Exception("*** Test '" + peerFactory.getName() + "' failed ***"); } else { System.out.println("Test '" + peerFactory.getName() + "' completed successfully"); } }
public static void main(String[] args) { BufferedReader in; try { in = new BufferedReader( new FileReader( "/Users/rahulkhairwar/Documents/IntelliJ IDEA Workspace/Competitive " + "Programming/src/com/google/codejam16/qualificationround/inputB.txt")); OutputWriter out = new OutputWriter(System.out); Thread thread = new Thread(null, new Solver(in, out), "Solver", 1 << 28); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } out.flush(); in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public void test_getContentsFolder() { try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } // Get the content HttpMethod get_col_contents = new GetMethod( SLING_URL + COLLECTION_URL + slug + "/" + CONTENTS_FOLDER + "/" + "sling:resourceType"); try { client.executeMethod(get_col_contents); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // handle response. String response_body = ""; try { response_body = get_col_contents.getResponseBodyAsString(); } catch (IOException e) { e.printStackTrace(); } assertEquals(response_body, CONTENTS_RESOURCE_TYPE); }
// 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()); } }
/** * openConnections: open the connection to the master. has retry mechanism * * @return: true if the connection is built, false if failed */ public boolean openConnections() { _log("Try to connect to Master..."); int i = 0; while (true) { boolean isConnected = connect(); if (!isConnected) { i++; if (i == DropboxConstants.MAX_TRY) { break; } _log("Cannot connect to Master, retry " + i); try { Thread.sleep(DropboxConstants.TRY_CONNECT_MILLIS); } catch (InterruptedException e) { if (!_server.noException()) { _elog(e.toString()); } if (_server.debugMode()) { e.printStackTrace(); } _log("Retry connection is interrupted"); break; } } else { _log("Success!"); return true; } } _log("Failed"); return false; }
private void connect() throws UnknownHostException, IOException { IrcServer = new Socket(serverName, 6667); BufferedReader br = new BufferedReader( new InputStreamReader(IrcServer.getInputStream(), BotStats.getInstance().getCharset())); PrintWriter pw = new PrintWriter( new OutputStreamWriter( IrcServer.getOutputStream(), BotStats.getInstance().getCharset()), true); ih = new InputHandler(br); oh = new OutputHandler(pw); ih.start(); oh.start(); new Message("", "NICK", BotStats.getInstance().getBotname(), "").send(); new Message( "", "USER", "goat" + " nowhere.com " + serverName, BotStats.getInstance().getVersion()) .send(); // we sleep until we are connected, don't want to send these next messages too soon while (!connected) { try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } joinChannels(); }
/** * Construct a GIFEncoder. The constructor will convert the image to an indexed color array. * <B>This may take some time.</B> * * <p> * * @param image The image to encode. The image <B>must</B> be completely loaded. * @exception AWTException Will be thrown if the pixel grab fails. This can happen if Java runs * out of memory. It may also indicate that the image contains more than 256 colors. */ public GIFEncoder(Image image) throws AWTException { width_ = (short) image.getWidth(null); height_ = (short) image.getHeight(null); int values[] = new int[width_ * height_]; PixelGrabber grabber = new PixelGrabber(image, 0, 0, width_, height_, values, 0, width_); try { if (grabber.grabPixels() != true) throw new AWTException("Grabber returned false: " + grabber.status()); // $NON-NLS-1$ } catch (InterruptedException ex) { ex.printStackTrace(); } byte r[][] = new byte[width_][height_]; byte g[][] = new byte[width_][height_]; byte b[][] = new byte[width_][height_]; int index = 0; for (int y = 0; y < height_; ++y) for (int x = 0; x < width_; ++x) { r[x][y] = (byte) ((values[index] >> 16) & 0xFF); g[x][y] = (byte) ((values[index] >> 8) & 0xFF); b[x][y] = (byte) ((values[index]) & 0xFF); ++index; } ToIndexedColor(r, g, b); }
// TODO Der kommer en EOF exception når der forsøges at readObject. // TODO Brug sharedpref til at gemme og læse tamagotchi. private synchronized void loadTamagotchiFromFile() { FileInputStream fis = null; try { available.acquire(); Log.d(TAMAGOTCHI, "Loading the tamagotchi from: " + fileName); fis = this.openFileInput(fileName); ObjectInputStream is = new ObjectInputStream(fis); // is.reset(); // TODO Bug when reading a tama from filesystem // Steps to reproduce: Kill with the app context menu thingie, start app again. tama = (Tamagotchi) is.readObject(); if (tama == null) return; is.close(); fis.close(); initializePlayingfield(); Log.d(TAMAGOTCHI, "Done loading the tama"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (OptionalDataException e) { e.printStackTrace(); } catch (StreamCorruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { available.release(); } }
private void rest() { try { Thread.sleep(100); // do nothing for 1000 miliseconds (1 second) } catch (InterruptedException e) { e.printStackTrace(); } }
// TODO Make the call to save and load s.t. it cannot enter both at the same time private synchronized void saveTamagotchiFromFile() { FileOutputStream fos = null; try { available.acquire(); this.deleteFile(fileName); // TODO How to make sure that we are done deleting the file? (in a better way) // TODO Make sure that only one thread is saving a time boolean found = true; while (found) { String[] fs = this.fileList(); boolean k = false; for (int i = 0; i < fs.length; i++) { if (fs[i].equals(fileName)) k = true; } found = k; } fos = this.openFileOutput(fileName, Context.MODE_PRIVATE); ObjectOutputStream os = new ObjectOutputStream(fos); os.writeObject(tama); os.flush(); os.close(); fos.close(); Log.d(TAMAGOTCHI, "Done saving tama"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { available.release(); } }
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 CIJobStatus buildJob(CIJob job) throws PhrescoException { if (debugEnabled) { S_LOGGER.debug("Entering Method CIManagerImpl.buildJob(CIJob job)"); } cli = getCLI(job); List<String> argList = new ArrayList<String>(); argList.add(FrameworkConstants.CI_BUILD_JOB_COMMAND); argList.add(job.getName()); try { int status = cli.execute(argList); String message = FrameworkConstants.CI_BUILD_STARTED; if (status == FrameworkConstants.JOB_STATUS_NOTOK) { message = FrameworkConstants.CI_BUILD_STARTING_ERROR; } return new CIJobStatus(status, message); } finally { if (cli != null) { try { cli.close(); } catch (IOException e) { if (debugEnabled) { S_LOGGER.error(e.getLocalizedMessage()); } } catch (InterruptedException e) { if (debugEnabled) { S_LOGGER.error(e.getLocalizedMessage()); } } } } }
@SuppressWarnings("LockAcquiredButNotSafelyReleased") protected void handleLock(String[] args) { String lockStr = args[0]; String key = args[1]; Lock lock = hazelcast.getLock(key); if (lockStr.equalsIgnoreCase("lock")) { lock.lock(); println("true"); } else if (lockStr.equalsIgnoreCase("unlock")) { lock.unlock(); println("true"); } else if (lockStr.equalsIgnoreCase("trylock")) { String timeout = args.length > 2 ? args[2] : null; if (timeout == null) { println(lock.tryLock()); } else { long time = Long.valueOf(timeout); try { println(lock.tryLock(time, TimeUnit.SECONDS)); } catch (InterruptedException e) { e.printStackTrace(); } } } }
public void zipTest(String fileName, String aspectjar, boolean isInJar) throws IOException { File inFile = new File(fileName); File outFile = new File(outDir, inFile.getName()); BcelWorld world = new BcelWorld(); // BcelWeaver weaver1 = new BcelWeaver(world); BcelWeaver weaver = new BcelWeaver(world); long startTime = System.currentTimeMillis(); // ensure that a fast cpu doesn't complete file write within 1000ms of start try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } weaver.addJarFile(inFile, new File("."), false); if (aspectjar != null) { if (isInJar) { weaver.addJarFile(new File(aspectjar), new File("."), false); } else { weaver.addLibraryJarFile(new File(aspectjar)); } } weaver.addLibraryJarFile(new File(BcweaverTests.TESTDATA_PATH + "/Regex.jar")); // ??? Collection woven = weaver.weave(outFile); long stopTime = System.currentTimeMillis(); System.out.println( "handled " + woven.size() + " entries, in " + (stopTime - startTime) / 1000. + " seconds"); // last mod times on linux (at least) are only accurate to the second. // with fast disks and a fast cpu the following test can fail if the write completes less than // 1000 milliseconds after the start of the test, hence the 1000ms delay added above. assertTrue(outFile.lastModified() > startTime); }
protected void handleQTake(String[] args) { try { println(getQueue().take()); } catch (InterruptedException e) { e.printStackTrace(); } }
private void tracksRun() throws IOException { while (running) { try { if (tracksMsgReady) { p("ready to send Tracks"); tracksMsgReady = !(sendTracks()); Thread.sleep(TRACKS_DELAY); } else { int[][] targets = {{1, 1}, {100, 100}, {100, 10}}; int[][] lasers = {{22, 54}}; tracksMsgReady = setTracks( System.currentTimeMillis(), this.sysStatus.OPERATIONAL, targets, lasers, true); // setup tracks message } } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // end while loop } // End tracksRun method
private void reconnect() { connected = false; while (true) { try { connect(); return; } catch (UnknownHostException uhe) { System.out.println("Hmmn unknown host, will wait 400 seconds then try connecting again.. "); } catch (IOException ioe) { System.out.println("IOException, waiting 400 secs then retry. "); } catch (Exception e) { System.err.println("Unexpected exception while trying reconnect() :"); e.printStackTrace(); } try { sleep(400000); } catch (InterruptedException e) { System.err.println("Interrupted from sleep between reconnect attempts :"); e.printStackTrace(); } catch (Exception e) { System.err.println("Unexpected exception while sleeping between reconnects :"); e.printStackTrace(); } } }
private void imageRun() { while (running) { try { if (imageMsgReady) { imageMsgReady = !(sendImage()); Thread.sleep(IMAGE_DELAY); } else { byte[] serialImage = new byte[(channels * sizeX * sizeY)]; Random generator = new Random(); int index = 0; for (int i = 0; i < channels; i++) { for (int j = 0; j < sizeY; j++) { for (int k = 0; k < sizeX; k++) { serialImage[index++] = (byte) generator.nextInt(128); // Generate random number 0-127 MAX_SIZE for byte } } } imageMsgReady = setImage( System.currentTimeMillis(), channels, sizeX, sizeY, com.google.protobuf.ByteString.copyFrom(serialImage)); // setup status message } } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // end while loop } // End tracksRun method
public void run() { while (true) { for (Map.Entry<String, Integer> entry : information.entrySet()) { String key = entry.getKey(); Integer value = entry.getValue(); if (mi.information_old.containsKey(key)) { Integer value_i = mi.information_old.get(key); if ((value - value_i) > get_spam_time(key)) { if (!mi.spammy.containsKey(key)) { send_message("REGISTERED " + key + " AS A SPAMMY EVENT!"); mi.spammy.put(key, 0); } else { Integer j = mi.spammy.get(key); mi.spammy.put(key, (j + 1)); } } mi.information_old.put(key, value); } else { mi.information_old.put(key, value); } } try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } }
/** Reads the view from the specified uri. */ @Override public void read(URI f, URIChooser chooser) throws IOException { try { final Drawing drawing = createDrawing(); InputFormat inputFormat = drawing.getInputFormats().get(0); inputFormat.read(f, drawing, true); SwingUtilities.invokeAndWait( new Runnable() { @Override public void run() { view.getDrawing().removeUndoableEditListener(undo); view.setDrawing(drawing); view.getDrawing().addUndoableEditListener(undo); undo.discardAllEdits(); } }); } catch (InterruptedException e) { InternalError error = new InternalError(); e.initCause(e); throw error; } catch (InvocationTargetException e) { InternalError error = new InternalError(); e.initCause(e); throw error; } }
public void run() { MOVE_PREV = MOVE_DOWN; System.out.println("INIT!"); map = new int[mapX][mapY]; for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[i].length; j++) { map[i][j] = 0; } } map[blockP.x][blockP.y] = 1; // map[0][20] = 1; StdDraw.setXscale(-1.0, 1.0); StdDraw.setYscale(-1.0, 1.0); // initial values // double vx = 0.015, vy = 0.023; // velocity // main animation loop while (true) { drawGame(); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } movePrev(); } }
public static void sleep(int secs) { try { Thread.sleep(secs * 1000); } catch (InterruptedException e) { e.printStackTrace(); } }
public void test_getTagsFolder() { try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } String response_body = ""; HttpMethod get_col_tags = new GetMethod( SLING_URL + COLLECTION_URL + slug + "/" + TAGS_FOLDER + "/" + "sling:resourceType"); try { client.executeMethod(get_col_tags); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { response_body = get_col_tags.getResponseBodyAsString(); } catch (IOException e) { e.printStackTrace(); } assertEquals(response_body, TAGS_RESOURCE_TYPE); get_col_tags.releaseConnection(); }
@Override public byte[] read(final String uri) { try { return ugi.doAs( new PrivilegedExceptionAction<byte[]>() { @Override public byte[] run() throws IOException { byte[] result; Path path = new Path(uri); SequenceFile.Reader reader = new SequenceFile.Reader(hdfsConfiguration, SequenceFile.Reader.file(path)); // SequenceFile.Reader reader = new SequenceFile.Reader(hdfsConfiguration); HDFSByteChunk chunk = new HDFSByteChunk(); // reader.getCurrentValue(chunk); IntWritable key = new IntWritable(); reader.next(key, chunk); result = chunk.getData(); return result; } }); } catch (IOException e) { e.printStackTrace(); return new byte[0]; } catch (InterruptedException e) { e.printStackTrace(); } return new byte[0]; }
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"); }
private SequenceFile.Writer getWriterFor(final String uri) { try { return ugi.doAs( new PrivilegedExceptionAction<SequenceFile.Writer>() { @Override public SequenceFile.Writer run() throws IOException { SequenceFile.Writer.Option keyClass = SequenceFile.Writer.keyClass(IntWritable.class); SequenceFile.Writer.Option valueClass = SequenceFile.Writer.valueClass(HDFSByteChunk.class); SequenceFile.Writer.Option fileName = SequenceFile.Writer.file(new Path(basePath.toUri().toString() + "/" + uri)); SequenceFile.Writer writer = null; writer = SequenceFile.createWriter(hdfsConfiguration, keyClass, valueClass, fileName); return writer; } }); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return null; }
public void generateDiagram(String outputDirectory, File dotFile) { try { Runtime run = Runtime.getRuntime(); Process pr = run.exec( "dot " + dotFile.getAbsolutePath() + " -Tpng -o" + outputDirectory + FILE_SEPARATOR + "graph.png"); pr.waitFor(); // BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream())); // should the output be really printed? // String line; // while ( ( line = buf.readLine() ) != null ) // { // System.out.println(line) ; // } // FIXME how to handle exceptions in listener? } catch (IOException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (InterruptedException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } }
void noncritical() { try { this.sleep(sleeptime); } catch (InterruptedException e) { e.printStackTrace(); } }