List of usage examples for java.io BufferedWriter flush
public void flush() throws IOException
From source file:com.allblacks.utils.web.HttpUtil.java
/** * Gets data from URL as char[] throws {@link RuntimeException} If anything * goes wrong/* ww w . ja va 2s. c o m*/ * * @return The content of the URL as a char[] * @throws java.io.IOException */ public char[] postDataAsCharArray(String url, String contentType, String contentName, char[] content) throws IOException { URLConnection urlc = null; OutputStream os = null; InputStream is = null; CharArrayWriter dat = null; BufferedReader reader = null; String boundary = "" + new Date().getTime(); try { urlc = new URL(url).openConnection(); urlc.setDoOutput(true); urlc.setRequestProperty(HttpUtil.CONTENT_TYPE, "multipart/form-data; boundary=---------------------------" + boundary); String message1 = "-----------------------------" + boundary + HttpUtil.BNL; message1 += "Content-Disposition: form-data; name=\"nzbfile\"; filename=\"" + contentName + "\"" + HttpUtil.BNL; message1 += "Content-Type: " + contentType + HttpUtil.BNL; message1 += HttpUtil.BNL; String message2 = HttpUtil.BNL + "-----------------------------" + boundary + "--" + HttpUtil.BNL; os = urlc.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, Charset.forName(HttpUtil.UTF_8))); writer.write(message1); writer.write(content); writer.write(message2); writer.flush(); dat = new CharArrayWriter(); if (urlc.getContentEncoding() != null && urlc.getContentEncoding().equalsIgnoreCase(HttpUtil.GZIP)) { is = new GZIPInputStream(urlc.getInputStream()); } else { is = urlc.getInputStream(); } reader = new BufferedReader(new InputStreamReader(is, Charset.forName(HttpUtil.UTF_8))); int c; while ((c = reader.read()) != -1) { dat.append((char) c); } } catch (IOException exception) { throw exception; } finally { try { reader.close(); os.close(); is.close(); } catch (Exception e) { // we do not care about this } } return dat.toCharArray(); }
From source file:net.arccotangent.pacchat.net.ConnectionHandler.java
public void run() { try {/*from w w w .j a va2 s . c om*/ String line1 = input.readLine(); switch (line1) { case "101 ping": ch_log.i("Client pinged us, responding with an acknowledgement."); output.write("102 pong"); output.newLine(); output.flush(); output.close(); break; case "302 request key update": ch_log.i("Client is requesting a key update."); KeyUpdate update = new KeyUpdate(ip); KeyUpdateManager.addPendingUpdate(connection_id, update); while (KeyUpdateManager.getUpdate(connection_id).isProcessed()) { try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } boolean accepted = KeyUpdateManager.getUpdate(connection_id).isAccepted(); KeyUpdateManager.completeIncomingUpdate(connection_id, KeyUpdateManager.getUpdate(connection_id)); if (accepted) { ch_log.i("Accepting key update"); try { output.write("303 update"); output.newLine(); output.flush(); String pubkeyB64 = input.readLine(); byte[] pubEncoded = Base64.decodeBase64(pubkeyB64); X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); output.close(); input.close(); KeyManager.saveKeyByIP(ip, keyFactory.generatePublic(pubSpec)); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { ch_log.e("Error updating sender's key!"); e.printStackTrace(); } } else { ch_log.i("Rejecting key update."); output.write("304 no update"); output.newLine(); output.flush(); output.close(); } break; case "301 getkey": ch_log.i("Client requested our public key, sending."); String pubkeyB64 = Base64.encodeBase64String(Main.getKeypair().getPublic().getEncoded()); output.write(pubkeyB64); output.newLine(); output.flush(); output.close(); break; case "200 encrypted message": //incoming encrypted message ch_log.i("Client sent an encrypted message, attempting verification and decryption."); PrivateKey privkey = Main.getKeypair().getPrivate(); String cryptedMsg = input.readLine() + "\n" + input.readLine() + "\n" + input.readLine(); ch_log.i("Checking for sender's public key."); if (KeyManager.checkIfIPKeyExists(ip)) { ch_log.i("Public key found."); } else { ch_log.i("Public key not found, requesting key from their server."); try { Socket socketGetkey = new Socket(); socketGetkey.connect(new InetSocketAddress(InetAddress.getByName(ip), Server.PORT), 1000); BufferedReader inputGetkey = new BufferedReader( new InputStreamReader(socketGetkey.getInputStream())); BufferedWriter outputGetkey = new BufferedWriter( new OutputStreamWriter(socketGetkey.getOutputStream())); outputGetkey.write("301 getkey"); outputGetkey.newLine(); outputGetkey.flush(); String sender_pubkeyB64 = inputGetkey.readLine(); byte[] pubEncoded = Base64.decodeBase64(sender_pubkeyB64); X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubEncoded); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); outputGetkey.close(); inputGetkey.close(); KeyManager.saveKeyByIP(ip, keyFactory.generatePublic(pubSpec)); } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) { ch_log.e("Error saving sender's key!"); e.printStackTrace(); } } PacchatMessage message = MsgCrypto.decryptAndVerifyMessage(cryptedMsg, privkey, KeyManager.loadKeyByIP(ip)); String msg = message.getMessage(); boolean verified = message.isVerified(); boolean decrypted = message.isDecryptedSuccessfully(); String ANSI_RESET = "\u001B[0m"; String ANSI_CYAN = "\u001B[36m"; String ANSI_BOLD = "\u001B[1m"; if (verified && decrypted) { ch_log.i("Acknowledging message."); output.write("201 message acknowledgement"); output.newLine(); output.flush(); output.close(); System.out.println(ANSI_BOLD + ANSI_CYAN + "-----BEGIN MESSAGE-----" + ANSI_RESET); System.out.println(ANSI_BOLD + ANSI_CYAN + msg + ANSI_RESET); System.out.println(ANSI_BOLD + ANSI_CYAN + "-----END MESSAGE-----" + ANSI_RESET); } else if (!verified && decrypted) { ch_log.w("Notifying client that message authenticity was not verified."); output.write("203 unable to verify"); output.newLine(); output.flush(); output.close(); System.out.println(ANSI_BOLD + ANSI_CYAN + "-----BEGIN MESSAGE-----" + ANSI_RESET); System.out.println(ANSI_BOLD + ANSI_CYAN + msg + ANSI_RESET); System.out.println(ANSI_BOLD + ANSI_CYAN + "-----END MESSAGE-----" + ANSI_RESET); } else if (!verified) { ch_log.w("Notifying client that message could not be decrypted."); output.write("202 unable to decrypt"); output.newLine(); output.flush(); output.close(); } break; case "201 message acknowledgement": ch_log.i("Client sent an invalid message acknowledgement."); output.write("400 invalid transmission header"); output.newLine(); output.flush(); output.close(); case "202 unable to decrypt": ch_log.i("Client sent an invalid 'unable to decrypt' transmission."); output.write("400 invalid transmission header"); output.newLine(); output.flush(); output.close(); case "203 unable to verify": ch_log.i("Client sent an invalid 'unable to verify' transmission."); output.write("400 invalid transmission header"); output.newLine(); output.flush(); output.close(); default: ch_log.i("Client sent an invalid request header: " + line1); output.write("400 invalid transmission header"); output.newLine(); output.flush(); output.close(); break; } } catch (IOException e) { ch_log.e("Error in connection handler " + connection_id); e.printStackTrace(); } }
From source file:gmgen.plugin.PlayerCharacterOutput.java
String getExportToken(String token) { try {/* w w w .java 2s . co m*/ StringWriter retWriter = new StringWriter(); BufferedWriter bufWriter = new BufferedWriter(retWriter); ExportHandler export = new ExportHandler(new File("")); export.replaceTokenSkipMath(pc, token, bufWriter); retWriter.flush(); try { bufWriter.flush(); } catch (IOException e) { // TODO - Handle Exception } return retWriter.toString(); } catch (Exception e) { System.out.println("Failure fetching token: " + token); return ""; } }
From source file:com.mendhak.gpslogger.common.network.CertificateValidationWorkflow.java
@Override public void run() { try {//w w w. ja v a 2 s. co m LOG.debug("Beginning certificate validation - will connect directly to {} port {}", host, String.valueOf(port)); try { LOG.debug("Trying handshake first in case the socket is SSL/TLS only"); connectToSSLSocket(null); postValidationHandler.post(new Runnable() { @Override public void run() { onWorkflowFinished(context, null, true); } }); } catch (final Exception e) { if (Networks.extractCertificateValidationException(e) != null) { throw e; } LOG.debug("Direct connection failed or no certificate was presented", e); if (serverType == ServerType.HTTPS) { postValidationHandler.post(new Runnable() { @Override public void run() { onWorkflowFinished(context, e, false); } }); return; } LOG.debug("Now attempting to connect over plain socket"); Socket plainSocket = new Socket(host, port); plainSocket.setSoTimeout(30000); BufferedReader reader = new BufferedReader(new InputStreamReader(plainSocket.getInputStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(plainSocket.getOutputStream())); String line; if (serverType == ServerType.SMTP) { LOG.debug("CLIENT: EHLO localhost"); writer.write("EHLO localhost\r\n"); writer.flush(); line = reader.readLine(); LOG.debug("SERVER: " + line); } String command = "", regexToMatch = ""; if (serverType == ServerType.FTP) { LOG.debug("FTP type server"); command = "AUTH SSL\r\n"; regexToMatch = "(?:234.*)"; } else if (serverType == ServerType.SMTP) { LOG.debug("SMTP type server"); command = "STARTTLS\r\n"; regexToMatch = "(?i:220 .* Ready.*)"; } LOG.debug("CLIENT: " + command); LOG.debug("(Expecting regex {} in response)", regexToMatch); writer.write(command); writer.flush(); while ((line = reader.readLine()) != null) { LOG.debug("SERVER: " + line); if (line.matches(regexToMatch)) { LOG.debug("Elevating socket and attempting handshake"); connectToSSLSocket(plainSocket); postValidationHandler.post(new Runnable() { @Override public void run() { onWorkflowFinished(context, null, true); } }); return; } } LOG.debug("No certificates found. Giving up."); postValidationHandler.post(new Runnable() { @Override public void run() { onWorkflowFinished(context, null, false); } }); } } catch (final Exception e) { LOG.debug("", e); postValidationHandler.post(new Runnable() { @Override public void run() { onWorkflowFinished(context, e, false); } }); } }
From source file:com.github.seqware.queryengine.system.Utility.java
/** * <p>dumpVCFFromFeatureSetID.</p> * * @param fSet a {@link com.github.seqware.queryengine.model.FeatureSet} object. * @param file a {@link java.lang.String} object. *//* ww w. ja v a 2s.co m*/ public static boolean dumpFromMapReducePlugin(String header, Reference ref, FeatureSet fSet, Class<? extends PluginInterface> arbitraryPlugin, String file, Object... params) { BufferedWriter outputStream = null; try { if (file != null) { outputStream = new BufferedWriter(new FileWriter(file)); } else { outputStream = new BufferedWriter(new OutputStreamWriter(System.out)); } if (header != null) { outputStream.append(header); } } catch (IOException e) { Logger.getLogger(Utility.class.getName()).fatal("Exception thrown starting export to file:", e); System.exit(-1); } if (SWQEFactory.getQueryInterface() instanceof MRHBasePersistentBackEnd) { if (SWQEFactory.getModelManager() instanceof MRHBaseModelManager) { try { QueryFuture<File> future = SWQEFactory.getQueryInterface().getFeaturesByPlugin(0, arbitraryPlugin, ref, params); File get = future.get(); Collection<File> listFiles = FileUtils.listFiles(get, new WildcardFileFilter("part*"), DirectoryFileFilter.DIRECTORY); for (File f : listFiles) { BufferedReader in = new BufferedReader(new FileReader(f)); IOUtils.copy(in, outputStream); in.close(); } get.deleteOnExit(); assert (outputStream != null); outputStream.flush(); outputStream.close(); return true; } catch (IOException e) { Logger.getLogger(VCFDumper.class.getName()).fatal("Exception thrown exporting to file:", e); System.exit(-1); } catch (Exception e) { Logger.getLogger(VCFDumper.class.getName()) .fatal("MapReduce exporting failed, falling-through to normal exporting to file", e); } } } return false; }
From source file:com.commander4j.util.JUtility.java
public synchronized static void writeToTextFile(String filename, String text) { BufferedWriter bw = null; try {/*from ww w.ja v a 2s . c o m*/ bw = new BufferedWriter(new FileWriter(filename, true)); bw.write(text); bw.newLine(); bw.flush(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { // always close the file if (bw != null) { try { bw.close(); } catch (IOException ioe2) { } } } }
From source file:com.thoughtworks.go.api.base.JsonOutputWriter.java
private void bufferWriterAndFlushWhenDone(Writer writer, Consumer<BufferedWriter> consumer) { BufferedWriter bufferedWriter = (writer instanceof BufferedWriter) ? (BufferedWriter) writer : new BufferedWriter(writer, 32 * 1024); try {/* w w w.j a va2 s . c om*/ try { consumer.accept(bufferedWriter); } finally { bufferedWriter.flush(); } } catch (IOException e) { throw new RuntimeException(e); } }
From source file:ch.vorburger.webdriver.reporting.TestCaseReportWriter.java
void addTestClassNameToJS(String className) { BufferedWriter bw = null; try {/*from w ww . j a v a 2 s .co m*/ bw = new BufferedWriter(new FileWriter(jsFile, true)); bw.write("testClassArray.push(\"" + className + "\");"); bw.newLine(); bw.flush(); } catch (IOException ioe) { // DO Nothing } finally { // always close the file if (bw != null) try { bw.close(); } catch (IOException ioe2) { // just ignore it } } // end try/catch/finally }
From source file:ch.vorburger.webdriver.reporting.TestCaseReportWriter.java
void addFailedTestClassNameToJS(String className) { BufferedWriter bw = null; try {/*from w w w . j a va 2 s .c om*/ bw = new BufferedWriter(new FileWriter(jsFile, true)); bw.write("failedTestClassArray.push(\"" + className + "\");"); bw.newLine(); bw.flush(); } catch (IOException ioe) { // DO Nothing } finally { // always close the file if (bw != null) try { bw.close(); } catch (IOException ioe2) { // just ignore it } } // end try/catch/finally }
From source file:com.amazonaws.mobileconnectors.kinesis.kinesisrecorder.FileRecordStore.java
public boolean put(final String record) throws IOException { boolean success = false; BufferedWriter writer = null; accessLock.lock();// w ww.j a v a2 s. c o m try { writer = tryInitializeWriter(); if (recordFile.length() + record.getBytes(StringUtils.UTF8).length <= maxStorageSize) { writer.write(record); writer.newLine(); writer.flush(); success = true; } } finally { if (writer != null) { writer.close(); } accessLock.unlock(); } return success; }