Java Code Examples for java.io.OutputStream.flush()

The following are Jave code examples for showing how to use flush() of the java.io.OutputStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: unitimes   File: RoomPictureServlet.java   View Source Code Vote up 7 votes
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	String idStr = request.getParameter("id");
	if (idStr != null) {
		Long id = Long.valueOf(idStr);
		LocationPicture picture = null;
		if (id >= 0) {
			picture = LocationPictureDAO.getInstance().get(id);
		} else {
			Map<Long, LocationPicture> temp = (Map<Long, LocationPicture>)request.getSession().getAttribute(TEMP_ROOM_PICTURES);
			if (temp != null)
				picture = temp.get(id);
		}
		if (picture != null) {
			response.setContentType(picture.getContentType());
			response.setHeader( "Content-Disposition", "attachment; filename=\"" + picture.getFileName() + "\"" );
			OutputStream out = response.getOutputStream(); 
			out.write(picture.getDataFile());
			out.flush();
		} else {
			new ServletException("Room picture of the given id does not exist.");
		}
	}
	new ServletException("No room picture id provided.");
}
 
Example 2
Project: stage-job   File: JobApiController.java   View Source Code Vote up 7 votes
@RequestMapping(AdminBiz.MAPPING)
@PermessionLimit(limit=false)
public void api(HttpServletRequest request, HttpServletResponse response) throws IOException {

    // invoke
    RpcResponse rpcResponse = doInvoke(request);

    // serialize response
    byte[] responseBytes = HessianSerializer.serialize(rpcResponse);

    response.setContentType("text/html;charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);
    //baseRequest.setHandled(true);

    OutputStream out = response.getOutputStream();
    out.write(responseBytes);
    out.flush();
}
 
Example 3
Project: hadoop   File: TestAtomicFileOutputStream.java   View Source Code Vote up 6 votes
/**
 * Test case where there is no existing file
 */
@Test
public void testOverwriteFile() throws IOException {
  assertTrue("Creating empty dst file", DST_FILE.createNewFile());
  
  OutputStream fos = new AtomicFileOutputStream(DST_FILE);
  
  assertTrue("Empty file still exists", DST_FILE.exists());
  fos.write(TEST_STRING.getBytes());
  fos.flush();
  
  // Original contents still in place
  assertEquals("", DFSTestUtil.readFile(DST_FILE));

  fos.close();

  // New contents replace original file
  String readBackData = DFSTestUtil.readFile(DST_FILE);
  assertEquals(TEST_STRING, readBackData);
}
 
Example 4
Project: GitHub   File: URLConnectionTest.java   View Source Code Vote up 6 votes
@Test public void fullyBufferedPostIsTooLong() throws Exception {
  server.enqueue(new MockResponse().setBody("A"));

  connection = urlFactory.open(server.url("/b").url());
  connection.setRequestProperty("Content-Length", "3");
  connection.setRequestMethod("POST");
  OutputStream out = connection.getOutputStream();
  out.write('a');
  out.write('b');
  out.write('c');
  try {
    out.write('d');
    out.flush();
    fail();
  } catch (IOException expected) {
  }
}
 
Example 5
Project: boohee_v5.6   File: a.java   View Source Code Vote up 6 votes
protected static final String a(Bitmap bitmap, String str, String str2) {
    File file = new File(str);
    if (!file.exists()) {
        file.mkdirs();
    }
    String stringBuffer = new StringBuffer(str).append(str2).toString();
    File file2 = new File(stringBuffer);
    if (file2.exists()) {
        file2.delete();
    }
    if (bitmap != null) {
        try {
            OutputStream fileOutputStream = new FileOutputStream(file2);
            bitmap.compress(CompressFormat.JPEG, 80, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
            bitmap.recycle();
            return stringBuffer;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
    }
    return null;
}
 
Example 6
Project: boohee_v5.6   File: SimpleMultipartEntity.java   View Source Code Vote up 6 votes
public void writeTo(OutputStream out) throws IOException {
    out.write(this.header);
    SimpleMultipartEntity.this.updateProgress((long) this.header.length);
    FileInputStream inputStream = new FileInputStream(this.file);
    byte[] tmp = new byte[4096];
    while (true) {
        int bytesRead = inputStream.read(tmp);
        if (bytesRead != -1) {
            out.write(tmp, 0, bytesRead);
            SimpleMultipartEntity.this.updateProgress((long) bytesRead);
        } else {
            out.write(SimpleMultipartEntity.CR_LF);
            SimpleMultipartEntity.this.updateProgress((long) SimpleMultipartEntity.CR_LF
                    .length);
            out.flush();
            AsyncHttpClient.silentCloseInputStream(inputStream);
            return;
        }
    }
}
 
Example 7
Project: minion-android   File: CompileActivity.java   View Source Code Vote up 5 votes
private void bytesToStorage(byte[] data) {
    OutputStream outputStream = null;
    try {
        outputStream = storage.write();
        outputStream.write(data);
        outputStream.flush();
    } catch (IOException ignored) {
    } finally {
        safeClose(outputStream);
    }
}
 
Example 8
Project: pokemon   File: LocalStorageImageUtil.java   View Source Code Vote up 5 votes
@Override
public ResponseEntity<StreamingResponseBody> readFile(String fileLocation, String imageDir, String id,
		String fileName) {
	StreamingResponseBody streamingResponseBody = new StreamingResponseBody() {

		@Override
		public void writeTo(OutputStream outputStream) {
			try {

				String fileStr = fileLocation + File.separator + imageDir + File.separator + id + File.separator
						+ fileName;

				RandomAccessFile file = new RandomAccessFile(fileStr, "r");
				FileChannel inChannel = file.getChannel();
				ByteBuffer buffer = ByteBuffer.allocate(1024);
				while (inChannel.read(buffer) > 0) {
					buffer.flip();
					for (int i = 0; i < buffer.limit(); i++) {
						outputStream.write(buffer.get());
					}
					buffer.clear();
					outputStream.flush();
				}
				inChannel.close();
				file.close();

			} catch (IOException e) {
				logger.error("Image Not Found : error " + e.getMessage());
				throw new ResourceNotFoundException("Image Not Found : " + id + "/" + fileName);
			}
		}
	};

	HttpHeaders headers = new HttpHeaders();
	headers.add(HttpHeaders.CONTENT_TYPE, "image/*");
	return new ResponseEntity<StreamingResponseBody>(streamingResponseBody, headers, HttpStatus.OK);
}
 
Example 9
Project: bdf2   File: DeploymentPage.java   View Source Code Vote up 5 votes
private Throwable deployProcessToServer() {
	Throwable throwable = null;
	try {
		HttpURLConnection conn = this.buildHttpURLConnection();
		StringBuffer sb = new StringBuffer();
		sb.append("--");
		sb.append(BOUNDARY);
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data; name=\"processzipfile\"; filename=\"processzipfile.zip\"\r\n");
		sb.append("Content-Type:application/x-zip-compressed\r\n\r\n");
		byte[] data = sb.toString().getBytes();
		byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
		OutputStream os = conn.getOutputStream();
		os.write(data);
		String tempProcessZipFile=this.buildTempDeploymentZipFile();
		FileInputStream fis=new FileInputStream(tempProcessZipFile);
		int rn2;  
           byte[] buf2 = new byte[1024];  
           while((rn2=fis.read(buf2, 0, 1024))>0){     
               os.write(buf2,0,rn2);  
           }
           os.write(end_data);  
           os.flush();  
           os.close();  
           fis.close();
           InputStream is = conn.getInputStream();  
           byte[] inbuf = new byte[1024];  
           int rn;  
           while((rn=is.read(inbuf,0,1024))>0){  
               System.out.write(inbuf,0,rn);  
           }  
           is.close();  
           File file=new File(tempProcessZipFile);
           if(file.exists())file.delete();
	} catch (Exception e) {
		throwable = e;
	}
	return throwable;
}
 
Example 10
Project: boohee_v5.6   File: WechatHelper.java   View Source Code Vote up 5 votes
private void a(Context context, String str, String str2, String str3, Bitmap bitmap, int i, k kVar) {
    IMediaObject wXVideoObject = new WXVideoObject();
    wXVideoObject.videoUrl = str3;
    WXMediaMessage wXMediaMessage = new WXMediaMessage();
    wXMediaMessage.title = str;
    wXMediaMessage.description = str2;
    wXMediaMessage.mediaObject = wXVideoObject;
    OutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.PNG, 100, byteArrayOutputStream);
    byteArrayOutputStream.flush();
    byteArrayOutputStream.close();
    wXMediaMessage.thumbData = a(context, byteArrayOutputStream.toByteArray());
    a(wXMediaMessage, "video", i, kVar);
}
 
Example 11
Project: NISTGammaSearch   File: DataBaseHelper.java   View Source Code Vote up 5 votes
private void copyDataBase() throws IOException
{
    InputStream mInput = mContext.getAssets().open(DB_NAME_ELEMENTS);
    String outFileName = DB_PATH + DB_NAME_ELEMENTS;
    OutputStream mOutput = new FileOutputStream(outFileName);
    byte[] mBuffer = new byte[1024];
    int mLength;
    while ((mLength = mInput.read(mBuffer))>0)
    {
        mOutput.write(mBuffer, 0, mLength);
    }
    mOutput.flush();
    mOutput.close();
    mInput.close();
}
 
Example 12
Project: googles-monorepo-demo   File: FileBackedOutputStreamTest.java   View Source Code Vote up 5 votes
private static void write(
    OutputStream out, byte[] b, int off, int len, boolean singleByte)
    throws IOException {
  if (singleByte) {
    for (int i = off; i < off + len; i++) {
      out.write(b[i]);
    }
  } else {
    out.write(b, off, len);
  }
  out.flush(); // for coverage
}
 
Example 13
Project: nh-micro   File: IO.java   View Source Code Vote up 5 votes
/**
 * @param inputStream
 * @param outputStream
 * @param bufferSize
 * @throws IOException
 */
public static void copy(InputStream inputStream, OutputStream outputStream, int bufferSize) throws IOException {
    int length = 0;
    byte[] buffer = new byte[bufferSize];

    while((length = inputStream.read(buffer, 0, bufferSize)) > -1) {
        outputStream.write(buffer, 0, length);
    }

    outputStream.flush();
}
 
Example 14
Project: FirefoxData-android   File: SerializableEntity.java   View Source Code Vote up 5 votes
public void writeTo(final OutputStream outstream) throws IOException {
    Args.notNull(outstream, "Output stream");
    if (this.objSer == null) {
        final ObjectOutputStream out = new ObjectOutputStream(outstream);
        out.writeObject(this.objRef);
        out.flush();
    } else {
        outstream.write(this.objSer);
        outstream.flush();
    }
}
 
Example 15
Project: thornsec-core   File: SSHExec.java   View Source Code Vote up 5 votes
public void run() {
	OutputStream write = p.getOutputStream();
	try {
		write.write(input.getBytes());
		write.flush();
		write.close();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 16
Project: incubator-netbeans   File: KVFile.java   View Source Code Vote up 5 votes
public void store(File file) throws IOException {
    OutputStream os = null; 
    try {
        File parent = file.getParentFile();
        if(parent!=null && !parent.exists()) {
            parent.mkdirs();
        }
        os = FileUtils.createOutputStream(file);            
        for (Iterator it = getMap().keySet().iterator(); it.hasNext();) {
            Key key = (Key) it.next();
            byte[] value = (byte[]) getMap().get(key);                
            
            StringBuffer sb = new StringBuffer();
            sb.append("K "); // NOI18N
            sb.append(key.getName().length());
            sb.append("\n"); // NOI18N
            sb.append(key.getName());
            sb.append("\n"); // NOI18N
            sb.append("V "); // NOI18N
            sb.append(value.length);
            sb.append("\n"); // NOI18N
            os.write(sb.toString().getBytes("UTF8"));    
            os.write(value);            
            os.write("\n".getBytes()); // NOI18N
        }
        os.write("END\n".getBytes()); // NOI18N
        os.flush();
        
    } finally {
        if(os != null) {
            try {
                os.close();    
            } catch (IOException ex) {
                Subversion.LOG.log(Level.INFO, null, ex);
            }                
        }            
    }        
}
 
Example 17
Project: boohee_v5.6   File: BitmapUtils.java   View Source Code Vote up 5 votes
public static void saveBitmap(String str, Bitmap bitmap) {
    try {
        OutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream
                (getFileName(str)));
        int i = 100;
        if (bitmap.getRowBytes() * bitmap.getHeight() > COMPRESS_FLAG) {
            i = 80;
        }
        bitmap.compress(CompressFormat.PNG, i, bufferedOutputStream);
        bufferedOutputStream.flush();
        bufferedOutputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 18
Project: nest-spider   File: ElasticsearchDAO.java   View Source Code Vote up 4 votes
/**
 * 导出数据
 * @param builder
 * @param labelsSupplier
 * @param contentSupplier
 * @param out  经过分词器的输出流
 */
protected void exportData(QueryBuilder builder, Function<SearchResponse, List<List<String>>> labelsSupplier, 
		Function<SearchResponse, List<String>> contentSupplier, OutputStream out) {
	final int size = 50;
	String scrollId = null;
	int page = 1;
	while(true) {
		LOG.debug("正在输出第" + page + "页,query:" + builder);
		SearchResponse response;
		if(StringUtils.isBlank(scrollId)) {
			response = search().setQuery(builder).setSize(size)
					.setScroll(SCROLL_TIMEOUT).get();
			scrollId = response.getScrollId();
		} else {
			response = client.prepareSearchScroll(scrollId)
					.setScroll(SCROLL_TIMEOUT).get();
		}
		final List<List<String>> labels = labelsSupplier.apply(response);
		final List<String> contentList = contentSupplier.apply(response);
		Preconditions.checkNotNull(labels);
		Preconditions.checkNotNull(contentList);
		if(contentList.size()<=0)
			break;
		//开始分词
		List<String> combine;
		if(labels.size() > 0) {
			combine = labels.stream().map(list -> list.parallelStream().collect(Collectors.joining("/")))
					.collect(Collectors.toList());
			for(int i = 0;i<labels.size();i++) 
				combine.set(i, combine.get(i) + " " + contentList.get(i));
		} else
			combine = contentList;
		page++;
		try {
			IOUtils.write(combine.stream().collect(Collectors.joining("\n")) + "\n", out, "utf-8");
			out.flush();
		} catch(IOException e) {
			LOG.error("文件写出错误, 由于 " + e.getLocalizedMessage());
		}
	}
}
 
Example 19
Project: GitHub   File: StringBody.java   View Source Code Vote up 4 votes
@Override
public void writeTo(OutputStream out) throws IOException {
    out.write(content);
    out.flush();
}
 
Example 20
Project: openjdk-jdk10   File: ExportableBlockCipher.java   View Source Code Vote up 4 votes
void doClientSide() throws Exception {

        /*
         * Wait for server to get started.
         */
        while (!serverReady) {
            Thread.sleep(50);
        }

        SSLSocketFactory sslsf =
            (SSLSocketFactory) SSLSocketFactory.getDefault();
        SSLSocket sslSocket = (SSLSocket)
            sslsf.createSocket("localhost", serverPort);

        // enable TLSv1.1 only
        sslSocket.setEnabledProtocols(new String[] {"TLSv1.1"});

        // enable a exportable block cipher
        sslSocket.setEnabledCipherSuites(
            new String[] {"SSL_RSA_EXPORT_WITH_DES40_CBC_SHA"});

        InputStream sslIS = sslSocket.getInputStream();
        OutputStream sslOS = sslSocket.getOutputStream();

        boolean interrupted = false;
        try {
            sslOS.write('B');
            sslOS.flush();
            sslIS.read();
        } catch (SSLException ssle) {
            // get the expected exception
            interrupted = true;
        } finally {
            sslSocket.close();
        }

        if (!interrupted) {
            throw new SSLHandshakeException(
                "A weak cipher suite is negotiated, " +
                "TLSv1.1 must not negotiate the exportable cipher suites.");
        }
    }