List of usage examples for java.io BufferedOutputStream flush
@Override public synchronized void flush() throws IOException
From source file:com.ettrema.httpclient.Host.java
/** * * @param path - the path to get, relative to the base path of the host * @param file - the file to write content to * @param listener// w ww .java 2s. c o m * @throws IOException * @throws NotFoundException * @throws com.ettrema.httpclient.HttpException * @throws com.ettrema.httpclient.Utils.CancelledException * @throws NotAuthorizedException * @throws BadRequestException * @throws ConflictException */ public synchronized void doGet(Path path, final java.io.File file, ProgressListener listener) throws IOException, NotFoundException, com.ettrema.httpclient.HttpException, CancelledException, NotAuthorizedException, BadRequestException, ConflictException { LogUtils.trace(log, "doGet", path); if (fileSyncer != null) { fileSyncer.download(this, path, file, listener); } else { String url = this.buildEncodedUrl(path); transferService.get(url, new StreamReceiver() { @Override public void receive(InputStream in) throws IOException { OutputStream out = null; BufferedOutputStream bout = null; try { out = FileUtils.openOutputStream(file); bout = new BufferedOutputStream(out); IOUtils.copy(in, bout); bout.flush(); } finally { IOUtils.closeQuietly(bout); IOUtils.closeQuietly(out); } } }, null, listener); } }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
/** * //from w w w .j av a 2s . c o m * @param message * @param type set to 5 when sending a PKI request, 3 when sending a PKIConf * @return * @throws IOException * @throws NoSuchProviderException */ protected byte[] sendCmpTcp(byte[] message, int type) throws IOException, NoSuchProviderException { final String host = getProperty("tcpCmpProxyIP", this.CMP_HOST); final int port = getProperty("tcpCmpProxyPort", PORT_NUMBER); try { final Socket socket = new Socket(host, port); final byte[] msg = createTcpMessage(message); try { final BufferedOutputStream os = new BufferedOutputStream(socket.getOutputStream()); os.write(msg); os.flush(); DataInputStream dis = new DataInputStream(socket.getInputStream()); // Read the length, 32 bits final int len = dis.readInt(); log.info("Got a message claiming to be of length: " + len); // Read the version, 8 bits. Version should be 10 (protocol draft nr // 5) final int ver = dis.readByte(); log.info("Got a message with version: " + ver); assertEquals(ver, 10); // Read flags, 8 bits for version 10 final byte flags = dis.readByte(); log.info("Got a message with flags (1 means close): " + flags); // Check if the client wants us to close the connection (LSB is 1 in // that case according to spec) // Read message type, 8 bits final int msgType = dis.readByte(); log.info("Got a message of type: " + msgType); assertEquals(msgType, type); // Read message final ByteArrayOutputStream baos = new ByteArrayOutputStream(3072); while (dis.available() > 0) { baos.write(dis.read()); } log.info("Read " + baos.size() + " bytes"); final byte[] respBytes = baos.toByteArray(); assertNotNull(respBytes); assertTrue(respBytes.length > 0); return respBytes; } finally { socket.close(); } } catch (ConnectException e) { assertTrue("This test requires a CMP TCP listener to be configured on " + host + ":" + port + ". Edit conf/cmptcp.properties and redeploy.", false); } catch (EOFException e) { assertTrue("Response was malformed.", false); } catch (Exception e) { e.printStackTrace(); assertTrue(false); } return null; }
From source file:com.shigeodayo.ardrone.utils.ARDroneInfo.java
private boolean connectToDroneThroughFtp() { FTPClient client = new FTPClient(); BufferedOutputStream bos = null; try {//from w ww . j a va 2 s . c o m client.connect(ARDroneConstants.IP_ADDRESS, ARDroneConstants.FTP_PORT); if (!client.login("anonymous", "")) { ARDrone.error("Login failed", this); return false; } client.setFileType(FTP.BINARY_FILE_TYPE); bos = new BufferedOutputStream(new OutputStream() { @Override public void write(int arg0) throws IOException { //System.out.println("aa:" + (char)arg0); switch (count) { case 0: major = arg0 - '0'; break; case 2: minor = arg0 - '0'; break; case 4: revision = arg0 - '0'; break; default: break; } count++; } }); if (!client.retrieveFile("/" + VERSION_FILE_NAME, bos)) { ARDrone.error("Cannot find \"" + VERSION_FILE_NAME + "\"", this); return false; } bos.flush(); //System.out.print("major:" + major); //System.out.print(" minor:" + minor); //System.out.println(" revision:" + revision); //System.out.println("done"); } catch (IOException e) { e.printStackTrace(); return false; } finally { try { if (bos != null) { bos.flush(); bos.close(); } client.disconnect(); } catch (IOException e) { e.printStackTrace(); return false; } } return true; }
From source file:org.apache.axis.SOAPPart.java
/** * Get the contents of this Part (not the headers!), as a byte * array. This will force buffering of the message. * * @return an array of bytes containing a byte representation of this Part * @throws AxisFault if this Part can't be serialized to the byte array *//* w ww .j a v a 2 s. c o m*/ public byte[] getAsBytes() throws AxisFault { log.debug("Enter: SOAPPart::getAsBytes"); if (currentForm == FORM_OPTIMIZED) { log.debug("Exit: SOAPPart::getAsBytes"); try { return ((ByteArray) currentMessage).toByteArray(); } catch (IOException e) { throw AxisFault.makeFault(e); } } if (currentForm == FORM_BYTES) { log.debug("Exit: SOAPPart::getAsBytes"); return (byte[]) currentMessage; } if (currentForm == FORM_BODYINSTREAM) { try { getAsSOAPEnvelope(); } catch (Exception e) { log.fatal(Messages.getMessage("makeEnvFail00"), e); log.debug("Exit: SOAPPart::getAsBytes"); return null; } } if (currentForm == FORM_INPUTSTREAM) { // Assumes we don't need a content length try { InputStream inp = null; byte[] buf = null; try { inp = (InputStream) currentMessage; ByteArrayOutputStream baos = new ByteArrayOutputStream(); buf = new byte[4096]; int len; while ((len = inp.read(buf, 0, 4096)) != -1) baos.write(buf, 0, len); buf = baos.toByteArray(); } finally { if (inp != null && currentMessage instanceof org.apache.axis.transport.http.SocketInputStream) inp.close(); } setCurrentForm(buf, FORM_BYTES); log.debug("Exit: SOAPPart::getAsBytes"); return (byte[]) currentMessage; } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); } log.debug("Exit: SOAPPart::getAsBytes"); return null; } if (currentForm == FORM_SOAPENVELOPE || currentForm == FORM_FAULT) { currentEncoding = XMLUtils.getEncoding(msgObject, null); ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream os = new BufferedOutputStream(baos); try { this.writeTo(os); os.flush(); } catch (Exception e) { throw AxisFault.makeFault(e); } setCurrentForm(baos.toByteArray(), FORM_BYTES); if (log.isDebugEnabled()) { log.debug("Exit: SOAPPart::getAsBytes(): " + currentMessage); } return (byte[]) currentMessage; } if (currentForm == FORM_STRING) { // If the current message was already converted from // a byte[] to String, return the byte[] representation // (this is done to avoid unnecessary conversions) if (currentMessage == currentMessageAsString && currentMessageAsBytes != null) { if (log.isDebugEnabled()) { log.debug("Exit: SOAPPart::getAsBytes()"); } return currentMessageAsBytes; } // Save this message in case it is requested later in getAsString currentMessageAsString = (String) currentMessage; try { currentEncoding = XMLUtils.getEncoding(msgObject, null); setCurrentForm(((String) currentMessage).getBytes(currentEncoding), FORM_BYTES); } catch (UnsupportedEncodingException ue) { setCurrentForm(((String) currentMessage).getBytes(), FORM_BYTES); } currentMessageAsBytes = (byte[]) currentMessage; log.debug("Exit: SOAPPart::getAsBytes"); return (byte[]) currentMessage; } log.error(Messages.getMessage("cantConvert00", "" + currentForm)); log.debug("Exit: SOAPPart::getAsBytes"); return null; }
From source file:de.lazyzero.kkMulticopterFlashTool.utils.Zip.java
public static File unzipFile(File zipFile, File file) { System.out.println("path to zipFile: " + zipFile.getPath()); System.out.println("file to extract: " + file.getPath()); String fileName = null;//from w ww . j a va2s . co m try { zipFile.mkdir(); BufferedOutputStream dest = null; BufferedInputStream is = null; ZipEntry entry; ZipFile zipfile = new ZipFile(zipFile); Enumeration e = zipfile.entries(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); // System.out.println(entry.getName()); if (entry.getName().substring(entry.getName().indexOf("/") + 1).equals(file.getName())) { // if (entry.getName().contains(file.getName())){ System.out.println("firmware to extract found."); String tempFolder = System.getProperty("user.dir") + File.separatorChar + "tmp" + File.separatorChar; if (System.getProperty("os.name").toLowerCase().contains("mac")) { tempFolder = System.getProperty("user.home") + "/Library/Preferences/kkMulticopterFlashTool/"; } String newDir; if (entry.getName().indexOf("/") == -1) { newDir = zipFile.getName().substring(0, zipFile.getName().indexOf(".")); } else { newDir = entry.getName().substring(0, entry.getName().indexOf("/")); } String folder = tempFolder + newDir; System.out.println("Create folder: " + folder); if ((new File(folder).mkdir())) { System.out.println("Done."); ; } System.out.println("Extracting: " + entry); is = new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[] = new byte[2048]; fileName = tempFolder + entry.getName(); FileOutputStream fos = new FileOutputStream(tempFolder + entry.getName()); dest = new BufferedOutputStream(fos, 2048); while ((count = is.read(data, 0, 2048)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); is.close(); break; } } } catch (ZipException e) { zipFile.delete(); kk.err(Translatrix._("error.zipfileDamaged")); kk.err(Translatrix._("reportProblem")); } catch (Exception e) { e.printStackTrace(); } return new File(fileName); }
From source file:adams.flow.sink.DownloadFile.java
/** * Executes the flow item.//from ww w . java2s . c o m * * @return null if everything is fine, otherwise error message */ @Override @MixedCopyright(author = "http://stackoverflow.com/users/2920131/lboix", license = License.CC_BY_SA_3, url = "http://stackoverflow.com/a/13122190", note = "handling basic authentication") protected String doExecute() { String result; URL url; BufferedInputStream input; BufferedOutputStream output; FileOutputStream fos; byte[] buffer; int len; int count; URLConnection conn; String basicAuth; input = null; output = null; fos = null; try { if (m_InputToken.getPayload() instanceof String) url = new URL((String) m_InputToken.getPayload()); else url = (URL) m_InputToken.getPayload(); conn = url.openConnection(); if (url.getUserInfo() != null) { basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes())); conn.setRequestProperty("Authorization", basicAuth); } input = new BufferedInputStream(conn.getInputStream()); fos = new FileOutputStream(m_OutputFile.getAbsoluteFile()); output = new BufferedOutputStream(fos); buffer = new byte[m_BufferSize]; count = 0; while ((len = input.read(buffer)) > 0) { count++; output.write(buffer, 0, len); if (count % 100 == 0) output.flush(); } output.flush(); result = null; } catch (Exception e) { result = handleException("Problem downloading '" + m_InputToken.getPayload() + "': ", e); } finally { FileUtils.closeQuietly(input); FileUtils.closeQuietly(output); FileUtils.closeQuietly(fos); } return result; }
From source file:com.wyp.module.controller.LicenseController.java
/** * /* ww w. ja v a 2 s.co m*/ * @param response * @param responseJson * @param type */ private void repsonseJsonResult(HttpServletResponse response, String responseJson, String type) { BufferedOutputStream buff = null; StringBuffer write = new StringBuffer(); ServletOutputStream outStr = null; try { outStr = response.getOutputStream();// buff = new BufferedOutputStream(outStr); // ?json?text if ("json".equals(type)) { response.setContentType("application/json");// write.append(responseJson); } else { // ** response.setContentType("text/plain");// response.addHeader("Content-Disposition", "attachment;filename=license.asc");// filename??O String enter = "\r\n"; // json? List<Object> list = parseLicenses(responseJson); for (int i = 0; i < list.size(); i++) { write.append(list.get(i)); write.append(enter); } } buff.write(write.toString().getBytes("UTF-8")); buff.flush(); buff.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { buff.close(); outStr.close(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.hichinaschool.flashcards.libanki.Utils.java
public static boolean unzipFiles(ZipFile zipFile, String targetDirectory, String[] zipEntries, HashMap<String, String> zipEntryToFilenameMap) { byte[] buf = new byte[FILE_COPY_BUFFER_SIZE]; File dir = new File(targetDirectory); if (!dir.exists() && !dir.mkdirs()) { Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Could not create target directory: " + targetDirectory); return false; }/*from www. j av a 2 s .c om*/ if (zipEntryToFilenameMap == null) { zipEntryToFilenameMap = new HashMap<String, String>(); } BufferedInputStream zis = null; BufferedOutputStream bos = null; try { for (String requestedEntry : zipEntries) { ZipEntry ze = zipFile.getEntry(requestedEntry); if (ze != null) { String name = ze.getName(); if (zipEntryToFilenameMap.containsKey(name)) { name = zipEntryToFilenameMap.get(name); } File destFile = new File(dir, name); File parentDir = destFile.getParentFile(); if (!parentDir.exists() && !parentDir.mkdirs()) { return false; } if (!ze.isDirectory()) { // Log.i(AnkiDroidApp.TAG, "uncompress " + name); zis = new BufferedInputStream(zipFile.getInputStream(ze)); bos = new BufferedOutputStream(new FileOutputStream(destFile), FILE_COPY_BUFFER_SIZE); int n; while ((n = zis.read(buf, 0, FILE_COPY_BUFFER_SIZE)) != -1) { bos.write(buf, 0, n); } bos.flush(); bos.close(); zis.close(); } } } } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while unzipping archive.", e); return false; } finally { try { if (bos != null) { bos.close(); } } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while closing output stream.", e); } try { if (zis != null) { zis.close(); } } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while closing zip input stream.", e); } } return true; }
From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
private void runSimultaneousDataExchange(boolean useTunnel, int nclients) throws IOException, InterruptedException, NoSuchAlgorithmException { long t0 = System.currentTimeMillis(); final int nMsgs = 50; final Map<String, MessageDigest> digestMsgsRecvdAtServer = new HashMap<String, MessageDigest>(); final Map<String, MessageDigest> digestMsgsSentByClients = new HashMap<String, MessageDigest>(); final Map<String, MessageDigest> digestMsgsRecvdAtClients = new HashMap<String, MessageDigest>(); for (int c = 0; c < nclients; c++) { digestMsgsRecvdAtServer.put(Integer.toString(c), MessageDigest.getInstance("MD5")); digestMsgsSentByClients.put(Integer.toString(c), MessageDigest.getInstance("MD5")); digestMsgsRecvdAtClients.put(Integer.toString(c), MessageDigest.getInstance("MD5")); }//from w w w. java2s . c om final MessageDigest digestMsgsSentByServer = MessageDigest.getInstance("MD5"); for (int i = 0; i < nMsgs; i++) { digestMsgsSentByServer.update(TalkPastServer.generateMsgFromServer(i).getBytes()); } String hashOfMsgsSentByServer = Hex.encodeHexString(digestMsgsSentByServer.digest()); MockServer talkPastServer = startTalkPastServer(nMsgs, digestMsgsRecvdAtServer); int targetPort = talkPastServer.getServerSocketPort(); Tunnel tunnel = null; MockServer proxyServer = null; if (useTunnel) { proxyServer = startConnectProxyServer(); tunnel = Tunnel.build("localhost", talkPastServer.getServerSocketPort(), "localhost", proxyServer.getServerSocketPort()); targetPort = tunnel.getPort(); } try { List<EasyThread> clientThreads = new ArrayList<EasyThread>(); final int portToUse = targetPort; for (int c = 0; c < nclients; c++) { final int clientId = c; clientThreads.add(new EasyThread() { @Override void runQuietly() throws Exception { long t = System.currentTimeMillis(); LOG.info("\t" + clientId + ": Client starting"); final MessageDigest digestMsgsRecvdAtClient = digestMsgsRecvdAtClients .get(Integer.toString(clientId)); //final SocketChannel client = SocketChannel.open(); // tunnel test hangs for some reason with SocketChannel final Socket client = new Socket(); client.connect(new InetSocketAddress("localhost", portToUse)); EasyThread serverReaderThread = new EasyThread() { @Override public void runQuietly() { try { BufferedReader clientIn = new BufferedReader( new InputStreamReader(client.getInputStream())); String line = clientIn.readLine(); while (line != null && !line.equals("Goodbye")) { //LOG.info("\t" + clientId + ": Server said [" + line.substring(0, 32) + "... ]"); digestMsgsRecvdAtClient.update(line.getBytes()); digestMsgsRecvdAtClient.update("\n".getBytes()); line = clientIn.readLine(); } } catch (IOException e) { e.printStackTrace(); } LOG.info("\t" + clientId + ": Client done reading"); } }.startThread(); MessageDigest hashMsgsFromClient = digestMsgsSentByClients.get(Integer.toString(clientId)); BufferedOutputStream clientOut = new BufferedOutputStream(client.getOutputStream()); for (int i = 0; i < nMsgs; i++) { String msg = clientId + ":" + i + " " + StringUtils.repeat("Blahhh Blahhh ", 10000) + "\n"; //LOG.info(clientId + " sending " + msg.length() + " bytes"); byte[] bytes = msg.getBytes(); hashMsgsFromClient.update(bytes); clientOut.write(bytes); MockServer.sleepQuietly(2); } clientOut.write(("Goodbye\n".getBytes())); clientOut.flush(); LOG.info("\t" + clientId + ": Client done writing in " + (System.currentTimeMillis() - t) + " ms"); serverReaderThread.join(); LOG.info("\t" + clientId + ": Client done in " + (System.currentTimeMillis() - t) + " ms"); client.close(); } }.startThread()); } for (Thread clientThread : clientThreads) { clientThread.join(); } LOG.info("All data transfer done in " + (System.currentTimeMillis() - t0) + " ms"); } finally { talkPastServer.stopServer(); if (tunnel != null) { proxyServer.stopServer(); tunnel.close(); assertFalse(tunnel.isTunnelThreadAlive()); assertEquals(proxyServer.getNumConnects(), nclients); } Map<String, String> hashOfMsgsRecvdAtServer = new HashMap<String, String>(); Map<String, String> hashOfMsgsSentByClients = new HashMap<String, String>(); Map<String, String> hashOfMsgsRecvdAtClients = new HashMap<String, String>(); for (int c = 0; c < nclients; c++) { String client = Integer.toString(c); hashOfMsgsRecvdAtServer.put(client, Hex.encodeHexString(digestMsgsRecvdAtServer.get(client).digest())); hashOfMsgsSentByClients.put(client, Hex.encodeHexString(digestMsgsSentByClients.get(client).digest())); hashOfMsgsRecvdAtClients.put(client, Hex.encodeHexString(digestMsgsRecvdAtClients.get(client).digest())); } LOG.info("\tComparing client sent to server received"); assertEquals(hashOfMsgsSentByClients, hashOfMsgsRecvdAtServer); LOG.info("\tComparing server sent to client received"); for (String hashOfMsgsRecvdAtClient : hashOfMsgsRecvdAtClients.values()) { assertEquals(hashOfMsgsSentByServer, hashOfMsgsRecvdAtClient); } LOG.info("\tDone"); } }
From source file:com.nit.libanki.Utils.java
public static boolean unzipFiles(ZipFile zipFile, String targetDirectory, String[] zipEntries, HashMap<String, String> zipEntryToFilenameMap) { byte[] buf = new byte[FILE_COPY_BUFFER_SIZE]; File dir = new File(targetDirectory); if (!dir.exists() && !dir.mkdirs()) { Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Could not create target directory: " + targetDirectory); return false; }/* w w w . java2 s.co m*/ if (zipEntryToFilenameMap == null) { zipEntryToFilenameMap = new HashMap<String, String>(); } BufferedInputStream zis = null; BufferedOutputStream bos = null; try { for (String requestedEntry : zipEntries) { ZipArchiveEntry ze = zipFile.getEntry(requestedEntry); if (ze != null) { String name = ze.getName(); if (zipEntryToFilenameMap.containsKey(name)) { name = zipEntryToFilenameMap.get(name); } File destFile = new File(dir, name); File parentDir = destFile.getParentFile(); if (!parentDir.exists() && !parentDir.mkdirs()) { return false; } if (!ze.isDirectory()) { // Log.i(AnkiDroidApp.TAG, "uncompress " + name); zis = new BufferedInputStream(zipFile.getInputStream(ze)); bos = new BufferedOutputStream(new FileOutputStream(destFile), FILE_COPY_BUFFER_SIZE); int n; while ((n = zis.read(buf, 0, FILE_COPY_BUFFER_SIZE)) != -1) { bos.write(buf, 0, n); } bos.flush(); bos.close(); zis.close(); } } } } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while unzipping archive.", e); return false; } finally { try { if (bos != null) { bos.close(); } } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while closing output stream.", e); } try { if (zis != null) { zis.close(); } } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "Utils.unzipFiles: Error while closing zip input stream.", e); } } return true; }