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

The following examples show how to use java.io.OutputStreamWriter#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: InterfaceB_EngineBasedServer.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

        OutputStreamWriter outputWriter = ServletUtils.prepareResponse(response);
        StringBuilder output = new StringBuilder();
        output.append("<response>");
        output.append(processPostQuery(request));
        output.append("</response>");
        if (_engine.enginePersistenceFailure())
        {
            _log.fatal("************************************************************");
            _log.fatal("A failure has occurred whilst persisting workflow state to the");
            _log.fatal("database. Check the status of the database connection defined");
            _log.fatal("for the YAWL service, and restart the YAWL web application.");
            _log.fatal("Further information may be found within the Tomcat log files.");
            _log.fatal("************************************************************");
            response.sendError(500, "Database persistence failure detected");
        }
        outputWriter.write(output.toString());
        outputWriter.flush();
        outputWriter.close();
        //todo find out how to provide a meaningful 500 message in the format of  a fault message.
    }
 
Example 2
Source File: MetricsHttpServer.java    From dts with Apache License 2.0 6 votes vote down vote up
public void handle(HttpExchange t) throws IOException {
    String query = t.getRequestURI().getRawQuery();
    ByteArrayOutputStream response = this.response.get();
    response.reset();
    OutputStreamWriter osw = new OutputStreamWriter(response);
    TextFormat.write004(osw, registry.filteredMetricFamilySamples(parseQuery(query)));
    osw.flush();
    osw.close();
    response.flush();
    response.close();
    t.getResponseHeaders().set("Content-Type", TextFormat.CONTENT_TYPE_004);
    t.getResponseHeaders().set("Content-Length", String.valueOf(response.size()));
    if (shouldUseCompression(t)) {
        t.getResponseHeaders().set("Content-Encoding", "gzip");
        t.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
        final GZIPOutputStream os = new GZIPOutputStream(t.getResponseBody());
        response.writeTo(os);
        os.finish();
    } else {
        t.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.size());
        response.writeTo(t.getResponseBody());
    }
    t.close();
}
 
Example 3
Source File: FileLog.java    From Yahala-Messenger with MIT License 5 votes vote down vote up
public FileLog() {
    if (!BuildVars.DEBUG_VERSION) {
        return;
    }
    dateFormat = FastDateFormat.getInstance("dd_MM_yyyy_HH_mm_ss", Locale.US);
    File sdCard = ApplicationLoader.applicationContext.getExternalFilesDir(null);
    if (sdCard == null) {
        return;
    }
    File dir = new File(sdCard.getAbsolutePath() + "/logs");
    if (dir == null) {
        return;
    }
    dir.mkdirs();
    currentFile = new File(dir, dateFormat.format(System.currentTimeMillis()) + ".txt");
    if (currentFile == null) {
        return;
    }
    try {
        currentFile.createNewFile();
        FileOutputStream stream = new FileOutputStream(currentFile);
        streamWriter = new OutputStreamWriter(stream);
        streamWriter.write("-----start log " + dateFormat.format(System.currentTimeMillis()) + "-----\n");
        streamWriter.flush();
        logQueue = new DispatchQueue("logQueue");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 4
Source File: ZipDatasetSource.java    From java-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Copy data from a reader to a ZipOutputStream.
 * @param reader a Reader open on the input dataset/member in the default EBCDIC encoding
 * @param zipOutStream the target ZipOutputStram
 * @param targetEncoding the target encoding for the ZipOutputStream
 * @throws IOException
 * @throws UnsupportedEncodingException
 */
private void copyData(Reader reader, 
						ZipOutputStream zipOutStream, 
						String targetEncoding) 
	throws IOException, UnsupportedEncodingException 
{
	char[] cbuf = new char[BUFSIZE];
	int nRead;
	// wrap the zipOutputStream in a Writer that encodes to the target encoding
	OutputStreamWriter osw = new OutputStreamWriter(zipOutStream, targetEncoding);
	while ((nRead = reader.read(cbuf)) != -1) {
		osw.write(cbuf, 0, nRead);
	}
	osw.flush(); // flush any buffered data to the ZipOutputStream
}
 
Example 5
Source File: ProtobufHttpMessageConverter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected void writeInternal(Message message, HttpOutputMessage outputMessage)
		throws IOException, HttpMessageNotWritableException {

	MediaType contentType = outputMessage.getHeaders().getContentType();
	if (contentType == null) {
		contentType = getDefaultContentType(message);
		Assert.state(contentType != null, "No content type");
	}
	Charset charset = contentType.getCharset();
	if (charset == null) {
		charset = DEFAULT_CHARSET;
	}

	if (PROTOBUF.isCompatibleWith(contentType)) {
		setProtoHeader(outputMessage, message);
		CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputMessage.getBody());
		message.writeTo(codedOutputStream);
		codedOutputStream.flush();
	}
	else if (TEXT_PLAIN.isCompatibleWith(contentType)) {
		OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputMessage.getBody(), charset);
		TextFormat.print(message, outputStreamWriter);
		outputStreamWriter.flush();
		outputMessage.getBody().flush();
	}
	else if (this.protobufFormatSupport != null) {
		this.protobufFormatSupport.print(message, outputMessage.getBody(), contentType, charset);
		outputMessage.getBody().flush();
	}
}
 
Example 6
Source File: RunnerRestStopCluster.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleSend(HttpURLConnection hconn) throws IOException {
     OutputStreamWriter wr = new OutputStreamWriter(hconn.getOutputStream());
     wr.write("clusterName=" + ((CommandTarget)command).target);
     wr.flush();
     wr.close();
}
 
Example 7
Source File: JsonParserBase.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
/**
 * Compose a resource to a stream, possibly using pretty presentation for a human reader (used in the spec, for example, but not normally in production)
 * @throws IOException 
 */
@Override
public void compose(OutputStream stream, Resource resource) throws IOException {
  OutputStreamWriter osw = new OutputStreamWriter(stream, "UTF-8");
  if (style == OutputStyle.CANONICAL)
    json = new JsonCreatorCanonical(osw);
  else
    json = new JsonCreatorDirect(osw); // use this instead of Gson because this preserves decimal formatting
  json.setIndent(style == OutputStyle.PRETTY ? "  " : "");
  json.beginObject();
  composeResource(resource);
  json.endObject();
  json.finish();
  osw.flush();
}
 
Example 8
Source File: XElement.java    From open-ig with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Save this XML into the supplied output stream.
 * @param stream the output stream
 * @throws IOException on error
 */
public void save(OutputStream stream) throws IOException {
	OutputStreamWriter out = new OutputStreamWriter(stream, "UTF-8");
	try {
		save(out);
	} finally {
		out.flush();
	}
}
 
Example 9
Source File: JsonParserBase.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
@Override
public void compose(OutputStream stream, DataType type, String rootName) throws IOException {
  OutputStreamWriter osw = new OutputStreamWriter(stream, "UTF-8");
  if (style == OutputStyle.CANONICAL)
    json = new JsonCreatorCanonical(osw);
  else
    json = new JsonCreatorDirect(osw);// use this instead of Gson because this preserves decimal formatting
  json.setIndent(style == OutputStyle.PRETTY ? "  " : "");
  json.beginObject();
  composeTypeInner(type);
  json.endObject();
  json.finish();
  osw.flush();
}
 
Example 10
Source File: AbstractCharBasedFormatter.java    From jigsaw-payment with Apache License 2.0 5 votes vote down vote up
@Override
public void print(UnknownFieldSet fields, OutputStream output, Charset cs)
		throws IOException {
	OutputStreamWriter writer = new OutputStreamWriter(output, cs);
	print(fields, writer);
	writer.flush();
}
 
Example 11
Source File: RunnerRestSetProperty.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleSend(HttpURLConnection hconn) throws IOException {
     OutputStreamWriter wr = new OutputStreamWriter(hconn.getOutputStream());
     CommandSetProperty spCommand = (CommandSetProperty) command;
     StringBuilder data = new StringBuilder();
     data.append("values=");
     data.append(spCommand.property);
     data.append("=\"");
     data.append(spCommand.value);
     data.append("\"");
     wr.write(data.toString());
     wr.flush();
     wr.close();
}
 
Example 12
Source File: TextFile.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public static void stringToFile(String content, File file) throws IOException {
  OutputStreamWriter sw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
  sw.write('\ufeff');  // Unicode BOM, translates to UTF-8 with the configured outputstreamwriter
  sw.write(content);
  sw.flush();
  sw.close();
}
 
Example 13
Source File: ToolUtil.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * Writes a content object into a set of output files. The content is one of {@link Doc}, {@link
 * String} or {@code byte[]}.
 */
public static void writeFiles(Map<String, ?> content, String baseName) throws IOException {

  for (Map.Entry<String, ?> entry : content.entrySet()) {
    File outputFile =
        Strings.isNullOrEmpty(baseName)
            ? new File(entry.getKey())
            : new File(baseName, entry.getKey());
    outputFile.getParentFile().mkdirs();
    OutputStream outputStream = new FileOutputStream(outputFile);
    OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
    try {
      Object value = entry.getValue();
      if (value instanceof Doc) {
        writer.write(((Doc) value).prettyPrint());
        writer.flush();
      } else if (value instanceof String) {
        writer.write((String) value);
        writer.flush();
      } else if (value instanceof byte[]) {
        outputStream.write((byte[]) value);
        outputStream.flush();
      } else {
        throw new IllegalArgumentException("Expected one of Doc, String, or byte[]");
      }
    } finally {
      writer.close();
    }
  }
}
 
Example 14
Source File: OpenConfig.java    From letv with Apache License 2.0 5 votes vote down vote up
private void a(String str, String str2) {
    try {
        if (this.d != null) {
            str = str + "." + this.d;
        }
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(this.c.openFileOutput(str, 0), Charset.forName("UTF-8"));
        outputStreamWriter.write(str2);
        outputStreamWriter.flush();
        outputStreamWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 15
Source File: OutputStreamWriterDemo.java    From code with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteChar() throws IOException {
    // 1、创建字符输出流
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("osw2.txt"));

    // 2、写数据
    // public void write(int c):写一个字符
    // osw.write('a');
    // osw.write(97);
    // 为什么数据没有进去呢?
    // 原因是:字符 = 2字节
    // 文件中数据存储的基本单位是字节。
    // void flush()

    // public void write(char[] cbuf):写一个字符数组
    // char[] chs = {'a','b','c','d','e'};
    // osw.write(chs);

    // public void write(char[] cbuf,int off,int len):写一个字符数组的一部分
    // osw.write(chs,1,3);

    // public void write(String str):写一个字符串
    // osw.write("我爱林青霞");

    // public void write(String str,int off,int len):写一个字符串的一部分
    osw.write("我爱林青霞", 2, 3);

    // 刷新缓冲区
    osw.flush();
    // osw.write("我爱林青霞", 2, 3);

    // 3、释放资源
    osw.close();
    // java.io.IOException: Stream closed
    // osw.write("我爱林青霞", 2, 3);
}
 
Example 16
Source File: Util.java    From edslite with GNU General Public License v2.0 5 votes vote down vote up
public static void writeAll(OutputStream out, CharSequence content) throws IOException
{		
	OutputStreamWriter w = new OutputStreamWriter(out);
	try
	{
		w.append(content);
	}
	finally
	{
		w.flush();
	}
}
 
Example 17
Source File: SSL_Client_json_simple.java    From firehose_examples with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static void RunClient(String machineName) {
    System.out.println(" Running Client");
    try {
        SSLSocket ssl_socket;
        ssl_socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(machineName, 1501);
        // enable certifcate validation:
        SSLParameters sslParams = new SSLParameters();
        sslParams.setEndpointIdentificationAlgorithm("HTTPS");
        sslParams.setProtocols(new String[] {"TLSv1.2"});
        ssl_socket.setSSLParameters(sslParams);

        if (useCompression) {
            initiation_command += " compression gzip";
        }

        initiation_command += "\n";
        
        //send your initiation command
        OutputStreamWriter writer = new OutputStreamWriter(ssl_socket.getOutputStream(), "UTF8");
        writer.write(initiation_command);
        writer.flush();

        InputStream inputStream = ssl_socket.getInputStream();
        if (useCompression) {
            inputStream = new java.util.zip.GZIPInputStream(inputStream);
        }

        // read messages from FlightAware
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String message = null;
        int limit = 5; //limit number messages for testing
        while (limit > 0 && (message = reader.readLine()) != null) {
            System.out.println("msg: " + message + "\n");
            parse_json(message);
            limit--;
        }

        //done, close everything
        writer.close();
        reader.close();
        inputStream.close();
        ssl_socket.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 18
Source File: RepoTransferReceiverImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Generate the requsite
 */
public void generateRequsite(String transferId, OutputStream out) throws TransferException
{
    log.debug("Generate Requsite for transfer:" + transferId);
    try
    {
        File snapshotFile = getSnapshotFile(transferId);

        if (snapshotFile.exists())
        {
            log.debug("snapshot does exist");
            SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
            SAXParser parser = saxParserFactory.newSAXParser();
            OutputStreamWriter dest = new OutputStreamWriter(out, "UTF-8");

            XMLTransferRequsiteWriter writer = new XMLTransferRequsiteWriter(dest);
            TransferManifestProcessor processor = manifestProcessorFactory.getRequsiteProcessor(
                    RepoTransferReceiverImpl.this,
                    transferId,
                    writer);

            XMLTransferManifestReader reader = new XMLTransferManifestReader(processor);

            /**
             * Now run the parser
             */
            parser.parse(snapshotFile, reader);

            /**
             * And flush the destination in case any content remains in the writer.
             */
            dest.flush();

        }
        log.debug("Generate Requsite done transfer:" + transferId);

    }
    catch (Exception ex)
    {
        if (TransferException.class.isAssignableFrom(ex.getClass()))
        {
            throw (TransferException) ex;
        }
        else
        {
            throw new TransferException(MSG_ERROR_WHILE_GENERATING_REQUISITE, ex);
        }
    }
}
 
Example 19
Source File: WebServiceProxy.java    From HTTP-RPC with Apache License 2.0 3 votes vote down vote up
private void encodeApplicationXWWWFormURLEncodedRequest(OutputStream outputStream) throws IOException {
    OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);

    writer.append(encodeQuery());

    writer.flush();
}
 
Example 20
Source File: CDWExporter.java    From synthea with Apache License 2.0 3 votes vote down vote up
/**
 * Helper method to write a line to a File.
 * Extracted to a separate method here to make it a little easier to replace implementations.
 *
 * @param line The line to write
 * @param writer The place to write it
 * @throws IOException if an I/O error occurs
 */
private static void write(String line, OutputStreamWriter writer) throws IOException {
  synchronized (writer) {
    writer.write(line);
    writer.flush();
  }
}