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

The following examples show how to use java.io.OutputStream#flush() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SmtpConnection.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
@PublicAtsApi
public void data(
                  String text ) {

    try {
        //obtain an output stream
        OutputStream dataStream = data();
        dataStream.write(text.getBytes());
        dataStream.flush();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (!finishData()) {
        throw new RuntimeException("Error executing data command");
    }
}
 
Example 2
Source File: SeckillController.java    From seckill with Apache License 2.0 6 votes vote down vote up
@ApiOperation("获取验证码接口")
@ApiImplicitParam(name = "goodsId", value = "商品ID", required = true, dataType = "Long")
@GetMapping("/verifyCode")
@ResponseBody
@AccessLimit(seconds = 5, maxCount = 5)
public Result<String> getVerifyCode(HttpServletResponse response, SeckillUser seckillUser,
                                    @RequestParam("goodsId") long goodsId) {
    response.setContentType("application/json;charset=UTF-8");
    BufferedImage image = seckillService.createVerifyCode(seckillUser, goodsId);
    try {
        OutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "JPEG", outputStream);
        outputStream.flush();
        outputStream.close();
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return Result.error(CodeMsg.SECKILL_FAIL);
    }
}
 
Example 3
Source File: DiskBasedCache.java    From android-project-wo2b with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the contents of this CacheHeader to the specified OutputStream.
 */
public boolean writeHeader(OutputStream os) {
    try {
        writeInt(os, CACHE_MAGIC);
        writeString(os, key);
        writeString(os, etag == null ? "" : etag);
        writeLong(os, serverDate);
        writeLong(os, ttl);
        writeLong(os, softTtl);
        writeStringStringMap(responseHeaders, os);
        os.flush();
        return true;
    } catch (IOException e) {
        VolleyLog.d("%s", e.toString());
        return false;
    }
}
 
Example 4
Source File: LocalHostCookie.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    String requestMethod = exchange.getRequestMethod();
    if (requestMethod.equalsIgnoreCase("GET")){
        Headers responseHeaders = exchange.getResponseHeaders();
        responseHeaders.set("Content-Type", "text/plain");
        responseHeaders.set("Date", "June 13th 2012");
        // No domain value set
        responseHeaders.set("Set-Cookie2", "name=value");
        exchange.sendResponseHeaders(200, 0);
        OutputStream os = exchange.getResponseBody();
        String str = "This is what the server sent!";
        os.write(str.getBytes());
        os.flush();
        os.close();
    }
}
 
Example 5
Source File: RemoteHttpCacheServlet.java    From commons-jcs with Apache License 2.0 6 votes vote down vote up
/**
 * Write the response to the output stream.
 * <p>
 * @param response
 * @param cacheResponse
 */
protected void writeResponse( HttpServletResponse response, RemoteCacheResponse<Object> cacheResponse )
{
    try
    {
        response.setContentType( "application/octet-stream" );

        byte[] responseAsByteAray = serializer.serialize( cacheResponse );
        response.setContentLength( responseAsByteAray.length );

        OutputStream outputStream = response.getOutputStream();
        log.debug( "Opened output stream.  Response size: {0}",
                () -> responseAsByteAray.length );
        // WRITE
        outputStream.write( responseAsByteAray );
        outputStream.flush();
        outputStream.close();
    }
    catch ( IOException e )
    {
        log.error( "Problem writing response. {0}", cacheResponse, e );
    }
}
 
Example 6
Source File: DataTransferSaslUtil.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Send a SASL negotiation message and negotiation cipher options to server.
 * 
 * @param out stream to receive message
 * @param payload to send
 * @param options cipher options to negotiate
 * @throws IOException for any error
 */
public static void sendSaslMessageAndNegotiationCipherOptions(
    OutputStream out, byte[] payload, List<CipherOption> options)
        throws IOException {
  DataTransferEncryptorMessageProto.Builder builder =
      DataTransferEncryptorMessageProto.newBuilder();
  
  builder.setStatus(DataTransferEncryptorStatus.SUCCESS);
  if (payload != null) {
    builder.setPayload(ByteString.copyFrom(payload));
  }
  if (options != null) {
    builder.addAllCipherOption(PBHelper.convertCipherOptions(options));
  }
  
  DataTransferEncryptorMessageProto proto = builder.build();
  proto.writeDelimitedTo(out);
  out.flush();
}
 
Example 7
Source File: ResponseUtils.java    From cruise-control with BSD 2-Clause "Simplified" License 6 votes vote down vote up
static void writeResponseToOutputStream(HttpServletResponse response,
                                        int responseCode,
                                        boolean json,
                                        boolean wantJsonSchema,
                                        String responseMessage,
                                        KafkaCruiseControlConfig config)
    throws IOException {
  OutputStream out = response.getOutputStream();
  setResponseCode(response, responseCode, json, config);
  response.addHeader("Cruise-Control-Version", KafkaCruiseControl.cruiseControlVersion());
  response.addHeader("Cruise-Control-Commit_Id", KafkaCruiseControl.cruiseControlCommitId());
  if (json && wantJsonSchema) {
    response.addHeader("Cruise-Control-JSON-Schema", getJsonSchema(responseMessage));
  }
  response.setContentLength(responseMessage.length());
  out.write(responseMessage.getBytes(StandardCharsets.UTF_8));
  out.flush();
}
 
Example 8
Source File: NetworkUtils.java    From memetastic with GNU General Public License v3.0 6 votes vote down vote up
private static String performCall(final URL url, final String method, final String data, final HttpURLConnection existingConnection) {
    try {
        final HttpURLConnection connection = existingConnection != null
                ? existingConnection : (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method);
        connection.setDoInput(true);

        if (data != null && !data.isEmpty()) {
            connection.setDoOutput(true);
            final OutputStream output = connection.getOutputStream();
            output.write(data.getBytes(Charset.forName(UTF8)));
            output.flush();
            output.close();
        }

        InputStream input = connection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST
                ? connection.getInputStream() : connection.getErrorStream();

        return FileUtils.readCloseTextStream(connection.getInputStream());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 9
Source File: KCWebImageDownloader.java    From kerkee_android with GNU General Public License v3.0 6 votes vote down vote up
private void writeToOutStream(OutputStream outputStream, InputStream inputStream)
{
    try
    {
        if (outputStream != null && inputStream != null && inputStream.available() > 0)
        {
            byte[] buffer = new byte[4096];
            
            while (inputStream.read(buffer) != -1)
            {
                outputStream.write(buffer);
            }
            outputStream.flush();
        }
        if (outputStream != null) outputStream.close();
    }
    catch (IOException e)
    {
        KCLog.e(e);
    }
}
 
Example 10
Source File: XmlConfigUtils.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static File newXmlTmpFile(String basename) throws IOException {
    final File f = new File(basename+".new");
    if (!f.createNewFile())
        throw new IOException("file "+f.getName()+" already exists");

    try {
        final OutputStream newStream = new FileOutputStream(f);
        try {
            final String decl =
                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
            newStream.write(decl.getBytes("UTF-8"));
            newStream.flush();
        } finally {
            newStream.close();
        }
    } catch (IOException x) {
        f.delete();
        throw x;
    }
    return f;
}
 
Example 11
Source File: ServerTest.java    From webery with MIT License 5 votes vote down vote up
protected String rawRequest(String path) throws IOException {
    StringBuilder sb = new StringBuilder();
    sb.append("GET ").append(path).append(" HTTP/1.1").append("\r\n");
    sb.append("Host: localhost:").append(port).append("\r\n");
    sb.append("testMethod: ").append(name.getMethodName()).append("\r\n");
    sb.append("Connection: Close\r\n");
    sb.append("\r\n");
    Socket socket = new Socket("localhost", port);
    OutputStream out = socket.getOutputStream();
    out.write(sb.toString().getBytes());
    out.flush();
    byte[] bytes = IOTools.bytes(socket.getInputStream());
    socket.close();
    return new String(bytes);
}
 
Example 12
Source File: PasswordAuthPlugin.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
public static void send323AuthPacket(OutputStream out, BinaryPacket bin2, HandshakeV10Packet handshake, String password) throws Exception {
    LOGGER.warn("Client don't support the MySQL 323 plugin ");
    Reply323Packet r323 = new Reply323Packet();
    r323.setPacketId((byte) (bin2.getPacketId() + 1));
    if (password != null && password.length() > 0) {
        r323.setSeed(SecurityUtil.scramble323(password, new String(handshake.getSeed())).getBytes());
    }
    r323.write(out);
    out.flush();
}
 
Example 13
Source File: InputStreamTests.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
void initContents(OutputStream out) throws IOException {
    for (int i = 0; i < size; i++) {
        out.write(byteBuf);
    }
    out.write(new byte[4]); // add the 4 byte pad
    out.flush();
}
 
Example 14
Source File: LineReaderTest.java    From DataVec with Apache License 2.0 5 votes vote down vote up
@Test
public void testLineReaderWithInputStreamInputSplit() throws Exception {
    String tempDir = System.getProperty("java.io.tmpdir");
    File tmpdir = new File(tempDir, "tmpdir");
    tmpdir.mkdir();

    File tmp1 = new File(tmpdir, "tmp1.txt.gz");

    OutputStream os = new GZIPOutputStream(new FileOutputStream(tmp1, false));
    IOUtils.writeLines(Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9"), null, os);
    os.flush();
    os.close();

    InputSplit split = new InputStreamInputSplit(new GZIPInputStream(new FileInputStream(tmp1)));

    RecordReader reader = new LineRecordReader();
    reader.initialize(split);

    int count = 0;
    while (reader.hasNext()) {
        assertEquals(1, reader.next().size());
        count++;
    }

    assertEquals(9, count);

    try {
        FileUtils.deleteDirectory(tmpdir);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 15
Source File: PackerImpl.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
void flushAll(OutputStream out) throws IOException {
    props.setInteger(Pack200.Packer.PROGRESS, 50);
    flushPackage(out, 0);
    out.flush();
    props.setInteger(Pack200.Packer.PROGRESS, 100);
    segmentCount += 1;
    segmentTotalSize += segmentSize;
    segmentSize = 0;
    if (verbose > 0 && segmentCount > 1) {
        Utils.log.info("Transmitted "
                         +segmentTotalSize+" input bytes in "
                         +segmentCount+" segments totaling "
                         +totalOutputSize+" bytes");
    }
}
 
Example 16
Source File: JsonRpcServer.java    From jsonrpc4j with MIT License 5 votes vote down vote up
/**
 * Handles a servlet request.
 *
 * @param request  the {@link HttpServletRequest}
 * @param response the {@link HttpServletResponse}
 * @throws IOException on error
 */
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
	logger.debug("Handling HttpServletRequest {}", request);
	response.setContentType(contentType);
	OutputStream output = response.getOutputStream();
	InputStream input = getRequestStream(request);
	int result = ErrorResolver.JsonError.PARSE_ERROR.code;
	int contentLength = 0;
	ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
	try {
		String acceptEncoding = request.getHeader(ACCEPT_ENCODING);
		result = handleRequest0(input, output, acceptEncoding, response, byteOutput);

		contentLength = byteOutput.size();
	} catch (Throwable t) {
		if (StreamEndedException.class.isInstance(t)) {
			logger.debug("Bad request: empty contents!");
		} else {
			logger.error(t.getMessage(), t);
		}
	}
	int httpStatusCode = httpStatusCodeProvider == null ? DefaultHttpStatusCodeProvider.INSTANCE.getHttpStatusCode(result)
			: httpStatusCodeProvider.getHttpStatusCode(result);
	response.setStatus(httpStatusCode);
	response.setContentLength(contentLength);
	byteOutput.writeTo(output);
	output.flush();
}
 
Example 17
Source File: ParallelTestRunner.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void flush() throws IOException {
    for (final OutputStream stream : streams) {
        stream.flush();
    }
}
 
Example 18
Source File: SupportFilesSetup.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
private static  void copyFiles(String dirName, String[] resources, String[] targetNames)
    throws PrivilegedActionException, IOException
{
    File dir = new File(dirName);
    dir.mkdir();
    
    if (resources == null)
        return;

    for (int i = 0; i < resources.length; i++)
    {
        String name =
            "org/apache/derbyTesting/".concat(resources[i]);
        
        String baseName;

        if ( targetNames == null )
        {
            // by default, just the same file name as the source file
            baseName = name.substring(name.lastIndexOf('/') + 1);
        }
        else
        {
            // we let the caller override the target file name
            baseName = targetNames[ i ];
        }
        
                    URL url = BaseTestCase.getTestResource(name);
        assertNotNull(name, url);
        
        InputStream in = BaseTestCase.openTestResource(url);
        
        File copy = new File(dir, baseName);
        copy.delete();
        
        OutputStream out = new FileOutputStream(copy);
        
        byte[] buf = new byte[32*1024];
        
        for (;;) {
            int read = in.read(buf);
            if (read == -1)
                break;
            out.write(buf, 0, read);
        }
        in.close();
        out.flush();
        out.close();
    }
}
 
Example 19
Source File: UrlAccountOutput.java    From EggCrack with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void save(AuthenticatedAccount account) throws IOException {
    String query = String.format(
            "username=%s&password=%s&uuid=%s&name=%s&instance=%s&version=%s",

            URLEncoder.encode(account.getUsername(), CHARSET),
            URLEncoder.encode(account.getCredential().toString(), CHARSET),
            URLEncoder.encode(account.getUuid().toString(), CHARSET),
            URLEncoder.encode(account.getAccountName().toString(), CHARSET),

            URLEncoder.encode(INSTANCE_UUID.toString(), CHARSET),
            URLEncoder.encode(Integer.toString(EggCrack.getInstance().getVersion()), CHARSET)
    );

    synchronized (url) {
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(10000);
        urlConnection.setReadTimeout(10000);

        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Accept-Charset", CHARSET);
        urlConnection.setRequestProperty("User-Agent", "EggCrack");
        urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + CHARSET);

        urlConnection.setDoOutput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setInstanceFollowRedirects(false);

        OutputStream outputStream = urlConnection.getOutputStream();
        outputStream.write(query.getBytes(CHARSET));
        outputStream.flush();

        if (urlConnection.getResponseCode() / 100 != 2)
            throw new IOException("Request failed (HTTP " + urlConnection.getResponseCode() + "): "
                    + urlConnection.getResponseMessage());

        EggCrack.LOGGER.fine("Account " + account.getUsername()
                + " submitted to URL \"" + url.toExternalForm() + "\".");

        //Safely close the connection.
        urlConnection.getInputStream().close();
    }
}
 
Example 20
Source File: NetworkAdminASNLookupImpl.java    From TorrentEngine with GNU General Public License v3.0 2 votes vote down vote up
protected NetworkAdminASNImpl
lookupTCP(			
	InetAddress		address )

	throws NetworkAdminException
{
	try{
		Socket	socket = new Socket();
		
		int	timeout = TIMEOUT;
			
		long	start = SystemTime.getCurrentTime();
		
		socket.connect( new InetSocketAddress( WHOIS_ADDRESS, WHOIS_PORT ), timeout );
	
		long	end = SystemTime.getCurrentTime();
		
		timeout -= (end - start );
		
		if ( timeout <= 0 ){
			
			throw( new NetworkAdminException( "Timeout on connect" ));
			
		}else if ( timeout > TIMEOUT ){
			
			timeout = TIMEOUT;
		}
		
		socket.setSoTimeout( timeout );
		
		try{
			OutputStream	os = socket.getOutputStream();
			
			String	command = "-u -p " + address.getHostAddress() + "\r\n";
			
			os.write( command.getBytes());
			
			os.flush();
			
			InputStream	is = socket.getInputStream();
			
			byte[]	buffer = new byte[1024];
			
			String	result = "";
			
			while( true ){
				
				int	len = is.read( buffer );
				
				if ( len <= 0 ){
					
					break;
				}
				
				result += new String( buffer, 0, len );
			}

			return( processResult( result ));

		}finally{
			
			socket.close();
		}
	}catch( Throwable e ){
		
		throw( new NetworkAdminException( "whois connection failed", e ));
	}	
}