List of usage examples for java.io PrintStream flush
public void flush()
From source file:org.exjello.mail.ExchangeConnection.java
private void findInbox() throws Exception { inbox = null;// ww w .j av a 2 s. c o m drafts = null; submissionUri = null; sentitems = null; outbox = null; HttpClient client = getClient(); ExchangeMethod op = new ExchangeMethod(PROPFIND_METHOD, server + "/exchange/" + mailbox); op.setHeader("Content-Type", XML_CONTENT_TYPE); op.setHeader("Depth", "0"); op.setHeader("Brief", "t"); op.setRequestEntity(createFindInboxEntity()); InputStream stream = null; try { int status = client.executeMethod(op); stream = op.getResponseBodyAsStream(); if (status >= 300) { throw new IllegalStateException("Unable to obtain inbox."); } SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); SAXParser parser = spf.newSAXParser(); parser.parse(stream, new DefaultHandler() { private final StringBuilder content = new StringBuilder(); public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { content.setLength(0); } public void characters(char[] ch, int start, int length) throws SAXException { content.append(ch, start, length); } public void endElement(String uri, String localName, String qName) throws SAXException { if (!HTTPMAIL_NAMESPACE.equals(uri)) return; if ("inbox".equals(localName)) { ExchangeConnection.this.inbox = content.toString(); } else if ("drafts".equals(localName)) { ExchangeConnection.this.drafts = content.toString(); } else if ("sentitems".equals(localName)) { ExchangeConnection.this.sentitems = content.toString(); } else if ("outbox".equals(localName)) { ExchangeConnection.this.outbox = content.toString(); } else if ("sendmsg".equals(localName)) { ExchangeConnection.this.submissionUri = content.toString(); } } }); stream.close(); stream = null; } finally { try { if (stream != null) { byte[] buf = new byte[65536]; try { if (session.getDebug()) { PrintStream log = session.getDebugOut(); log.println("Response Body:"); int count; while ((count = stream.read(buf, 0, 65536)) != -1) { log.write(buf, 0, count); } log.flush(); log.println(); } else { while (stream.read(buf, 0, 65536) != -1) ; } } catch (Exception ignore) { } finally { try { stream.close(); } catch (Exception ignore2) { } } } } finally { op.releaseConnection(); } } }
From source file:org.exjello.mail.Exchange2003Connection.java
public InputStream getInputStream(ExchangeMessage message) throws Exception { synchronized (this) { if (!isConnected()) { throw new IllegalStateException("Not connected."); }//from w w w . j a v a 2 s . c o m HttpClient client = getClient(); GetMethod op = new GetMethod(escape(message.getUrl())); op.setRequestHeader("Translate", "F"); InputStream stream = null; try { int status = client.executeMethod(op); stream = op.getResponseBodyAsStream(); if (status >= 300) { throw new IllegalStateException("Unable to obtain inbox: " + status); } final File tempFile = File.createTempFile("exmail", null, null); tempFile.deleteOnExit(); OutputStream output = new FileOutputStream(tempFile); byte[] buf = new byte[65536]; int count; while ((count = stream.read(buf, 0, 65536)) != -1) { output.write(buf, 0, count); } output.flush(); output.close(); stream.close(); stream = null; return new CachedMessageStream(tempFile, (ExchangeFolder) message.getFolder()); } finally { try { if (stream != null) { byte[] buf = new byte[65536]; try { if (session.getDebug()) { PrintStream log = session.getDebugOut(); log.println("Response Body:"); int count; while ((count = stream.read(buf, 0, 65536)) != -1) { log.write(buf, 0, count); } log.flush(); log.println(); } else { while (stream.read(buf, 0, 65536) != -1) ; } } catch (Exception ignore) { } finally { try { stream.close(); } catch (Exception ignore2) { } } } } finally { op.releaseConnection(); } } } }
From source file:org.exjello.mail.Exchange2003Connection.java
private void listFolder(DefaultHandler handler, String folder) throws Exception { synchronized (this) { if (!isConnected()) { throw new IllegalStateException("Not connected."); }//from w w w .ja v a 2 s.co m HttpClient client = getClient(); ExchangeMethod op = new ExchangeMethod(SEARCH_METHOD, folder); op.setHeader("Content-Type", XML_CONTENT_TYPE); if (limit > 0) op.setHeader("Range", "rows=0-" + limit); op.setHeader("Brief", "t"); /* Mirco: Manage of custom query */ if ((filterLastCheck == null || "".equals(filterLastCheck)) && (filterFrom == null || "".equals(filterFrom)) && (filterNotFrom == null || "".equals(filterNotFrom)) && (filterTo == null || "".equals(filterTo))) { op.setRequestEntity(unfiltered ? createAllInboxEntity() : createUnreadInboxEntity()); } else { op.setRequestEntity( createCustomInboxEntity(unfiltered, filterLastCheck, filterFrom, filterNotFrom, filterTo)); } InputStream stream = null; try { int status = client.executeMethod(op); stream = op.getResponseBodyAsStream(); if (status >= 300) { throw new IllegalStateException("Unable to obtain " + folder + "."); } SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); SAXParser parser = spf.newSAXParser(); parser.parse(stream, handler); stream.close(); stream = null; } finally { try { if (stream != null) { byte[] buf = new byte[65536]; try { if (session.getDebug()) { PrintStream log = session.getDebugOut(); log.println("Response Body:"); int count; while ((count = stream.read(buf, 0, 65536)) != -1) { log.write(buf, 0, count); } log.flush(); log.println(); } else { while (stream.read(buf, 0, 65536) != -1) ; } } catch (Exception ignore) { } finally { try { stream.close(); } catch (Exception ignore2) { } } } } finally { op.releaseConnection(); } } } }
From source file:com.act.lcms.MS2Simple.java
private void plot(List<Pair<MS2Collected, Integer>> ms2Spectra, Double mz, List<Double> ms2SearchMZs, String outPrefix, String fmt) throws IOException { String outPDF = outPrefix + "." + fmt; String outDATA = outPrefix + ".data"; // Write data output to outfile PrintStream out = new PrintStream(new FileOutputStream(outDATA)); List<String> plotID = new ArrayList<>(ms2Spectra.size()); for (Pair<MS2Collected, Integer> pair : ms2Spectra) { MS2Collected yzSlice = pair.getLeft(); String caption;//from ww w . java 2 s . c o m if (ms2SearchMZs != null && ms2SearchMZs.size() > 0) { caption = String.format("target: %.4f, time: %.4f, volts: %.4f, %d / %d matches", yzSlice.triggerMass, yzSlice.triggerTime, yzSlice.voltage, pair.getRight() == null ? 0 : pair.getRight(), ms2SearchMZs.size()); } else { caption = String.format("target: %.4f, time: %.4f, volts: %.4f", yzSlice.triggerMass, yzSlice.triggerTime, yzSlice.voltage); } plotID.add(caption); // Compute the total intensity on the fly so we can plot on a percentage scale. double maxIntensity = 0.0; for (YZ yz : yzSlice.ms2) { if (yz.intensity > maxIntensity) { maxIntensity = yz.intensity; } } // print out the spectra to outDATA for (YZ yz : yzSlice.ms2) { out.format("%.4f\t%.4f\n", yz.mz, 100.0 * yz.intensity / maxIntensity); out.flush(); } // delimit this dataset from the rest out.print("\n\n"); } // close the .data out.close(); // render outDATA to outPDF using gnuplot // 105.0 here means 105% for the y-range of a [0%:100%] plot. We want to leave some buffer space at // at the top, and hence we go a little outside of the 100% max range. /* We intend to plot the fragmentation pattern, and so do not expect to see fragments that are bigger than the * original selected molecule. We truncate the x-range to the specified m/z but since that will make values close * to the max hard to see we add a buffer and truncate the plot in the x-range to m/z + 50.0. */ new Gnuplotter().plot2DImpulsesWithLabels(outDATA, outPDF, plotID.toArray(new String[plotID.size()]), mz + 50.0, "mz", 105.0, "intensity (%)", fmt); }
From source file:se.sics.kompics.p2p.experiment.dsl.SimulationScenario.java
/** * Save simulation command line./* w ww . jav a 2 s . co m*/ * * @param args * the args */ private void saveSimulationCommandLine(final LinkedList<String> args) { File file = null; try { // Windows batch file file = new File(directory + "run-simulation.bat"); PrintStream ps = new PrintStream(file); for (String arg : args) { ps.println(arg.replaceAll(directory, "") + "\t^"); // ps.println(arg + "\t^"); } ps.println(";"); ps.flush(); ps.close(); // Linux/Unix Bash script file = new File(directory + "run-simulation.sh"); ps = new PrintStream(file); ps.println("#!/bin/bash"); ps.println(); for (String arg : args) { ps.println(arg.replaceAll(directory, "") + "\t\\"); // ps.println(arg + "\t\\"); } ps.println(";"); ps.flush(); ps.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.vonglasow.michael.satstat.ui.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); defaultUEH = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { Context c = getApplicationContext(); File dumpDir = c.getExternalFilesDir(null); DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.ROOT); fmt.setTimeZone(TimeZone.getTimeZone("UTC")); String fileName = String.format("satstat-%s.log", fmt.format(new Date(System.currentTimeMillis()))); File dumpFile = new File(dumpDir, fileName); PrintStream s; try { InputStream buildInStream = getResources().openRawResource(R.raw.build); s = new PrintStream(dumpFile); s.append("SatStat build: "); int i; try { i = buildInStream.read(); while (i != -1) { s.write(i);/*from ww w . j ava2 s. c o m*/ i = buildInStream.read(); } buildInStream.close(); } catch (IOException e1) { e1.printStackTrace(); } s.append("\n\n"); e.printStackTrace(s); s.flush(); s.close(); Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri contentUri = Uri.fromFile(dumpFile); mediaScanIntent.setData(contentUri); c.sendBroadcast(mediaScanIntent); } catch (FileNotFoundException e2) { e2.printStackTrace(); } defaultUEH.uncaughtException(t, e); } }); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); mSharedPreferences.registerOnSharedPreferenceChangeListener(this); prefUnitType = mSharedPreferences.getBoolean(Const.KEY_PREF_UNIT_TYPE, prefUnitType); prefKnots = mSharedPreferences.getBoolean(Const.KEY_PREF_KNOTS, prefKnots); prefCoord = Integer .valueOf(mSharedPreferences.getString(Const.KEY_PREF_COORD, Integer.toString(prefCoord))); prefUtc = mSharedPreferences.getBoolean(Const.KEY_PREF_UTC, prefUtc); prefCid = mSharedPreferences.getBoolean(Const.KEY_PREF_CID, prefCid); prefCid2 = mSharedPreferences.getBoolean(Const.KEY_PREF_CID2, prefCid2); prefWifiSort = Integer .valueOf(mSharedPreferences.getString(Const.KEY_PREF_WIFI_SORT, Integer.toString(prefWifiSort))); prefMapOffline = mSharedPreferences.getBoolean(Const.KEY_PREF_MAP_OFFLINE, prefMapOffline); prefMapPath = mSharedPreferences.getString(Const.KEY_PREF_MAP_PATH, prefMapPath); ActionBar actionBar = getSupportActionBar(); setContentView(R.layout.activity_main); // Find out default screen orientation Configuration config = getResources().getConfiguration(); WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE); int rot = wm.getDefaultDisplay().getRotation(); isWideScreen = (config.orientation == Configuration.ORIENTATION_LANDSCAPE && (rot == Surface.ROTATION_0 || rot == Surface.ROTATION_180) || config.orientation == Configuration.ORIENTATION_PORTRAIT && (rot == Surface.ROTATION_90 || rot == Surface.ROTATION_270)); Log.d(TAG, "isWideScreen=" + Boolean.toString(isWideScreen)); // Create the adapter that will return a fragment for each of the // primary sections of the app. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); Context ctx = new ContextThemeWrapper(getApplication(), R.style.AppTheme); mTabLayout = new TabLayout(ctx); LinearLayout.LayoutParams mTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); mTabLayout.setLayoutParams(mTabLayoutParams); for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { TabLayout.Tab newTab = mTabLayout.newTab(); newTab.setIcon(mSectionsPagerAdapter.getPageIcon(i)); mTabLayout.addTab(newTab); } actionBar.setDisplayShowCustomEnabled(true); actionBar.setCustomView(mTabLayout); mTabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager)); mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout)); // This is needed by the mapsforge library. AndroidGraphicFactory.createInstance(this.getApplication()); // Get system services for event delivery locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mOrSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); mAccSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mGyroSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); mMagSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); mLightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); mProximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); mPressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE); mHumiditySensor = sensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY); mTempSensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE); telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); }
From source file:org.exjello.mail.Exchange2003Connection.java
public void send(MimeMessage message) throws Exception { Address[] bccRecipients = message.getRecipients(Message.RecipientType.BCC); if (bccRecipients == null || bccRecipients.length == 0) { bccRecipients = null;//from w w w . j ava 2 s . c o m } message.setRecipients(Message.RecipientType.BCC, (Address[]) null); synchronized (this) { if (!isConnected()) { throw new IllegalStateException("Not connected."); } if (!canSend()) { throw new IllegalStateException("Unable to access outbox."); } HttpClient client = getClient(); String path = drafts; if (!path.endsWith("/")) path += "/"; String messageName = generateMessageName(); path += escape(messageName + ".eml"); PutMethod op = new PutMethod(path); op.setRequestHeader("Content-Type", MESSAGE_CONTENT_TYPE); op.setRequestEntity(createMessageEntity(message)); InputStream stream = null; try { int status = client.executeMethod(op); stream = op.getResponseBodyAsStream(); if (status >= 300) { throw new IllegalStateException("Unable to post message to draft folder."); } } finally { try { if (stream != null) { byte[] buf = new byte[65536]; try { if (session.getDebug()) { PrintStream log = session.getDebugOut(); log.println("Response Body:"); int count; while ((count = stream.read(buf, 0, 65536)) != -1) { log.write(buf, 0, count); } log.flush(); log.println(); } else { while (stream.read(buf, 0, 65536) != -1) ; } } catch (Exception ignore) { } finally { try { stream.close(); } catch (Exception ignore2) { } } } } finally { op.releaseConnection(); } } if (bccRecipients != null) { ExchangeMethod patch = new ExchangeMethod(PROPPATCH_METHOD, path); patch.setHeader("Content-Type", XML_CONTENT_TYPE); patch.addHeader("Depth", "0"); patch.addHeader("Translate", "f"); patch.addHeader("Brief", "t"); patch.setRequestEntity(createAddBccEntity(bccRecipients)); stream = null; try { int status = client.executeMethod(patch); stream = patch.getResponseBodyAsStream(); if (status >= 300) { throw new IllegalStateException("Unable to add BCC recipients. Status: " + status); } } finally { try { if (stream != null) { byte[] buf = new byte[65536]; try { if (session.getDebug()) { PrintStream log = session.getDebugOut(); log.println("Response Body:"); int count; while ((count = stream.read(buf, 0, 65536)) != -1) { log.write(buf, 0, count); } log.flush(); log.println(); } else { while (stream.read(buf, 0, 65536) != -1) ; } } catch (Exception ignore) { } finally { try { stream.close(); } catch (Exception ignore2) { } } } } finally { patch.releaseConnection(); } } } ExchangeMethod move = new ExchangeMethod(MOVE_METHOD, path); String destination = submissionUri; if (!destination.endsWith("/")) destination += "/"; move.setHeader("Destination", destination); stream = null; try { int status = client.executeMethod(move); stream = move.getResponseBodyAsStream(); if (status >= 300) { throw new IllegalStateException("Unable to move message to outbox: Status " + status); } } finally { try { if (stream != null) { byte[] buf = new byte[65536]; try { if (session.getDebug()) { PrintStream log = session.getDebugOut(); log.println("Response Body:"); int count; while ((count = stream.read(buf, 0, 65536)) != -1) { log.write(buf, 0, count); } log.flush(); log.println(); } else { while (stream.read(buf, 0, 65536) != -1) ; } } catch (Exception ignore) { } finally { try { stream.close(); } catch (Exception ignore2) { } } } } finally { move.releaseConnection(); } } if (session.getDebug()) { session.getDebugOut().println("Sent successfully."); } } }
From source file:cpcc.vvrte.services.js.JavascriptServiceTest.java
@Test public void shouldHandleVvRte() throws IOException, InterruptedException { MyBuiltInFunctions functions = new MyBuiltInFunctions(); JavascriptService jss = new JavascriptServiceImpl(logger, serviceResources, functions); jss.addAllowedClassRegex("cpcc.vvrte.services.js.JavascriptServiceTest\\$MyBuiltInFunctions"); ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream stdOut = new PrintStream(out, true); VvRteFunctions.setStdOut(stdOut);/* w w w.ja v a2 s . c o m*/ InputStream scriptStream = this.getClass().getResourceAsStream("simple-vv.js"); String script = IOUtils.toString(scriptStream, "UTF-8"); assertThat(script).isNotNull().isNotEmpty(); VirtualVehicle vv = new VirtualVehicle(); vv.setId(123); vv.setCode(script); vv.setApiVersion(1); vv.setUuid("599c6710-a042-11e5-a0fb-83f9ea30f21e"); functions.setMigrate(true); JavascriptWorker sut = jss.createWorker(vv, false); sut.run(); // System.out.println("shouldHandleVvRte() result1: '" + sut.getResult() + "'"); // System.out.println("shouldHandleVvRte() output1: '" + out.toString("UTF-8") + "'"); assertThat(sut.getWorkerState()).isNotNull().isEqualTo(VirtualVehicleState.INTERRUPTED); InputStream resultStream = this.getClass().getResourceAsStream("simple-vv-expected-result-1.txt"); String expectedResult = IOUtils.toString(resultStream, "UTF-8"); assertThat(out.toString("UTF-8")).isNotNull().isEqualTo(expectedResult); functions.setMigrate(false); byte[] snapshot = sut.getSnapshot(); vv.setContinuation(snapshot); sut = jss.createWorker(vv, true); sut.run(); stdOut.flush(); assertThat(sut.getWorkerState()).isNotNull().isEqualTo(VirtualVehicleState.FINISHED); // System.out.println("shouldHandleVvRte() result2: '" + x.getResult() + "'"); // System.out.println("shouldHandleVvRte() output2: '" + out.toString("UTF-8") + "'"); resultStream = this.getClass().getResourceAsStream("simple-vv-expected-result-2.txt"); expectedResult = IOUtils.toString(resultStream, "UTF-8"); assertThat(out.toString("UTF-8")).isNotNull().isEqualTo(expectedResult); verify(sessionManager, times(6)).commit(); verify(perthreadManager, times(2)).cleanup(); }
From source file:org.testeditor.fixture.swt.SwtBotFixture.java
/** * Returns true if the application is launched. * //from w w w . j a v a 2 s . co m * @return true, if the server is ready. */ private boolean isLaunched() { try { Socket client = getSocket(); LOGGER.info("Is server ready for " + testName + "?"); PrintStream os = new PrintStream(client.getOutputStream(), false, CHARSET_UTF_8); os.println("isLaunched"); os.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), CHARSET_UTF_8)); String s = in.readLine(); LOGGER.info(s); client.close(); return Boolean.valueOf(s); } catch (UnknownHostException e) { LOGGER.error("isLaunched UnknownHostException: ", e); } catch (ConnectException e) { LOGGER.trace("Server not available."); } catch (IOException e) { LOGGER.error("isLaunched IOException: ", e); } return false; }
From source file:org.broad.igv.tools.IgvTools.java
private void GFFToBed(String ifile, String ofile) throws FileNotFoundException { IGVBEDCodec outCodec = new IGVBEDCodec(); GFFParser parser = new GFFParser(); GFFCodec codec = null;/* ww w .ja va 2s . c o m*/ try { codec = (GFFCodec) CodecFactory.getCodec(ifile, null); } catch (Exception e) { throw new IllegalArgumentException("Input file is not recognized as a GFF"); } BufferedReader reader = null; PrintStream outStream = System.out; if (!ofile.equals(STDOUT_FILE_STR)) { outStream = new PrintStream(new FileOutputStream(ofile)); } try { reader = ParsingUtils.openBufferedReader(ifile); List<Feature> features = parser.loadFeatures(reader, null, codec); for (Feature feat : features) { String encoded = outCodec.encode(feat); outStream.print(encoded); outStream.print('\n'); } } catch (IOException e) { log.error(e.getMessage(), e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } if (outStream != null) { outStream.flush(); outStream.close(); } } }