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

The following are Jave code examples for showing how to use flush() of the java.io.Writer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: appinventor-extensions   File: DocumentationGenerator.java   Source Code and License Vote up 6 votes
protected final void outputResults() throws IOException {
  // Begin writing output file.
  FileObject src = createOutputFileObject(OUTPUT_FILE_NAME);
  Writer writer = src.openWriter();

  // Output table at top showing components by category.
  outputCategories(writer);

  // Components are already sorted.
  for (Map.Entry<String, ComponentInfo> entry : components.entrySet()) {
    ComponentInfo component = entry.getValue();
    outputComponent(writer, component);
  }

  // Close output file
  writer.flush();
  writer.close();
  messager.printMessage(Diagnostic.Kind.NOTE, "Wrote file " + src.toUri());
}
 
Example 2
Project: PACE   File: LocalEncryptionKeyContainer.java   Source Code and License Vote up 6 votes
/**
 * Write the encryption key container to the writer.
 *
 * @param out
 *          Output writer.
 */
public void write(Writer out) throws IOException {
  Gson gson = new GsonBuilder().enableComplexMapKeySerialization().setPrettyPrinting().create();

  JsonObject data = new JsonObject();
  data.addProperty("version", CURRENT_VERSION);

  JsonArray keys = new JsonArray();
  for (Entry<KeyLookup,Map<Integer,KeyWithVersion>> entry : encryptionKeys.entrySet()) {
    for (KeyWithVersion keyData : entry.getValue().values()) {
      JsonObject key = new JsonObject();
      if (entry.getKey().attribute != null) {
        key.addProperty("attribute", entry.getKey().attribute);
      }
      key.addProperty("id", entry.getKey().id);
      key.addProperty("version", keyData.version);
      key.addProperty("key", Base64.getEncoder().encodeToString(keyData.key));
      keys.add(key);
    }
  }
  data.add("keys", keys);

  gson.toJson(data, out);
  out.flush();
}
 
Example 3
Project: Reer   File: XmlTransformer.java   Source Code and License Vote up 5 votes
public void writeTo(OutputStream stream) {
    try {
        Writer writer = new OutputStreamWriter(stream, "UTF-8");
        doWriteTo(writer, "UTF-8");
        writer.flush();
    } catch (IOException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
 
Example 4
Project: devenv   File: CoreToolProvider.java   Source Code and License Vote up 5 votes
@Override
public void install(@NotNull ToolMetadata version, @NotNull Writer writer) throws Exception
{
    String installDir = findInstallDir();
    if (installDir == null)
    {
        throw new Exception("Must set " + envVar() + " environment variable (and ensure it's a valid directory).");
    }
    File dir = new File(installDir);
    if (dir.exists() && !IO.cleanDir(dir))
    {
        throw new Exception("Could not remove existent directory!");
    }
    //noinspection ResultOfMethodCallIgnored
    dir.mkdirs();

    writer.write("Downloading zip...\n");
    writer.flush();
    File zipFile = new File(dir, id() + "-" + version.getVersion() + ".zip");
    IO.download(version.getZipUrl(), zipFile, (1024 * 1024), totalDownload ->
    {
        try
        {
            writer.write(convertSize(totalDownload) + " ...\n");
            writer.flush();
        }
        catch (IOException ignored)
        {
        }
    });

    writer.write("Extracting zip...\n");
    writer.flush();
    IO.extract(zipFile, dir);
    //noinspection ResultOfMethodCallIgnored
    zipFile.delete();
    IO.ensureNotRoot(dir);
    writer.write("Done! Run '" + versionCmd() + "'.\n");
}
 
Example 5
Project: javaide   File: DataEntryRewriter.java   Source Code and License Vote up 5 votes
protected void copyData(InputStream  inputStream,
                        OutputStream outputStream)
throws IOException
{
    Reader reader = new BufferedReader(new InputStreamReader(inputStream));
    Writer writer = new BufferedWriter(new OutputStreamWriter(outputStream));

    copyData(reader, writer);

    writer.flush();
    outputStream.flush();
}
 
Example 6
Project: AbcPermission   File: GetPermissionsProcessor.java   Source Code and License Vote up 5 votes
/**
 * create the real file to be compiled
 */
private void createFile(String packageName, String enclosingName, String[] permissions, String methodName, String returnType) {
    try {
        Calendar calendar = Calendar.getInstance();
        String classPostfix = "" + (calendar.get(Calendar.MINUTE) + 100) + (calendar.get(Calendar.SECOND) + 100) + (calendar.get(Calendar.MILLISECOND) + 1000);
        JavaFileObject jfo = mFiler.createSourceFile(packageName + ".AutoCreate" + classPostfix, new Element[]{});
        Writer writer = jfo.openWriter();
        writer.write(CodeCreator.brewCodeNoCallback(packageName, enclosingName, permissions, classPostfix, methodName, returnType));
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
 
Example 7
Project: plugin-prov   File: TerraformResource.java   Source Code and License Vote up 5 votes
/**
 * Execute the given Terraform commands. Note there is no concurrency check for
 * now.
 */
private void executeTerraform(final Subscription subscription, final Writer out, final String[][] commands,
		final String... additionalParameters) throws InterruptedException, IOException {
	final AtomicInteger step = new AtomicInteger(0);
	// Reset the current step
	for (final String[] command : commands) {
		// Next step, another transaction
		runner.nextStep("service:prov:test:account", t -> t.setStep(TerraformStep.values()[step.get()]));

		final int code = executeTerraform(subscription, out, ArrayUtils.addAll(command, additionalParameters));
		if (code == 0) {
			// Nothing wrong, no change, only useless to go further
			log.info("Terraform paused for {} ({}) : {}", subscription.getId(), subscription, code);
			out.write("Terraform exit code " + code + " -> no need to continue");
			break;
		}
		if (code != 2) {
			// Something goes wrong
			log.error("Terraform failed for {} ({}) : {}", subscription.getId(), subscription, code);
			out.write("Terraform exit code " + code + " -> aborted");
			throw new BusinessException("aborted");
		}
		out.flush();

		// Code is correct, proceed the next command
		step.incrementAndGet();
	}
}
 
Example 8
Project: Jupiter   File: MainLogger.java   Source Code and License Vote up 5 votes
private void flushBuffer(File logFile) {
    if (logBuffer.isEmpty()) {
        try {
            synchronized (this) {
                wait(25000); // Wait for next message
            }
            Thread.sleep(5); // Buffer for 5ms to reduce back and forth between disk
        } catch (InterruptedException ignore) {
        }
    }
    try {
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logFile, true), StandardCharsets.UTF_8), 1024);
        Date now = new Date();
        String consoleDateFormat = new SimpleDateFormat("HH:mm:ss ").format(now);
        String fileDateFormat = new SimpleDateFormat("Y-M-d HH:mm:ss ").format(now);
        int count = 0;
        while (!logBuffer.isEmpty()) {
            String message = logBuffer.poll();
            if (message != null) {
                writer.write(fileDateFormat);
                writer.write(TextFormat.clean(message));
                writer.write("\r\n");
                CommandReader.getInstance().stashLine();
                System.out.println(colorize(FastAppender.get(TextFormat.AQUA, consoleDateFormat, TextFormat.RESET, message, TextFormat.RESET)));
                CommandReader.getInstance().unstashLine();
            }
        }
        writer.flush();
        writer.close();
    } catch (Exception e) {
        this.logException(e);
    }
}
 
Example 9
Project: sql-first-mapper   File: DaoWriter.java   Source Code and License Vote up 5 votes
/**
 * Write <query>.sql to resources folder
 *
 * @param queryDesc information on query
 */
private void writeResource(QueryDesc queryDesc) {
    Filer filer = processingEnv.getFiler();
    try {
        FileObject o = filer.createResource(StandardLocation.CLASS_OUTPUT,
                queryDesc.getPackageName() + ".sql", queryDesc.getMethodNameFirstUpper() + ".sql");
        Writer w = o.openWriter();
        w.append(queryDesc.getQuery());
        w.flush();
        w.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 10
Project: boohee_v5.6   File: ButterKnifeProcessor.java   Source Code and License Vote up 5 votes
public boolean process(Set<? extends TypeElement> set, RoundEnvironment env) {
    for (Entry<TypeElement, ViewInjector> entry : findAndParseTargets(env).entrySet()) {
        TypeElement typeElement = (TypeElement) entry.getKey();
        ViewInjector viewInjector = (ViewInjector) entry.getValue();
        try {
            Writer writer = this.filer.createSourceFile(viewInjector.getFqcn(), new Element[]{typeElement}).openWriter();
            writer.write(viewInjector.brewJava());
            writer.flush();
            writer.close();
        } catch (IOException e) {
            error(typeElement, "Unable to write injector for type %s: %s", typeElement, e.getMessage());
        }
    }
    return true;
}
 
Example 11
Project: plugin-vm   File: VmResource.java   Source Code and License Vote up 5 votes
/**
 * Write all execution related to given subscription, from the oldest to the
 * newest.
 */
private void writeReport(final Subscription subscription, final OutputStream output) throws IOException {
	final Writer writer = new BufferedWriter(new OutputStreamWriter(output, "cp1252"));
	final FastDateFormat df = FastDateFormat.getInstance("yyyy/MM/dd HH:mm:ss");
	writer.write("dateHMS;timestamp;operation;subscription;project;projectKey;projectName;node;trigger;succeed");
	for (final VmExecution execution : vmExecutionRepository.findAllBy("subscription.id", subscription.getId())) {
		writer.write('\n');
		writer.write(df.format(execution.getDate()));
		writer.write(';');
		writer.write(String.valueOf(execution.getDate().getTime()));
		writer.write(';');
		writer.write(execution.getOperation().name());
		writer.write(';');
		writer.write(String.valueOf(subscription.getId()));
		writer.write(';');
		writer.write(String.valueOf(subscription.getProject().getId()));
		writer.write(';');
		writer.write(subscription.getProject().getPkey());
		writer.write(';');
		writer.write(subscription.getProject().getName().replaceAll("\"", "'"));
		writer.write(';');
		writer.write(subscription.getNode().getId());
		writer.write(';');
		writer.write(execution.getTrigger());
		writer.write(';');
		writer.write(String.valueOf(execution.isSucceed()));
	}

	// Ensure buffer is flushed
	writer.flush();
}
 
Example 12
Project: r8   File: VirtualFile.java   Source Code and License Vote up 5 votes
private void writeAssignments(Map<String, Integer> assignments, Writer output)
    throws IOException{
  for (Entry<String, Integer> entry : assignments.entrySet()) {
    output.write("    ");
    PackageDistribution.formatEntry(entry, output);
    output.write("\n");
  }
  output.flush();
}
 
Example 13
Project: EvolvingNetLib   File: CCIOUtils.java   Source Code and License Vote up 4 votes
public static void write(Reader input, OutputStream output, String encoding) throws IOException {
    Writer out = new OutputStreamWriter(output, encoding);
    write(input, out);
    out.flush();
}
 
Example 14
Project: GitHub   File: IOUtils.java   Source Code and License Vote up 4 votes
public static void write(Reader input, OutputStream output) throws IOException {
    Writer out = new OutputStreamWriter(output);
    write(input, out);
    out.flush();
}
 
Example 15
Project: EvolvingNetLib   File: CCIOUtils.java   Source Code and License Vote up 4 votes
public static void write(Reader input, OutputStream output) throws IOException {
    Writer out = new OutputStreamWriter(output);
    write(input, out);
    out.flush();
}
 
Example 16
Project: apache-tomcat-7.0.73-with-comment   File: TestAbstractHttp11Processor.java   Source Code and License Vote up 4 votes
@Test
public void testRequestBodySwallowing() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    SempahoreServlet servlet = new SempahoreServlet();
    Wrapper w = Tomcat.addServlet(ctx, "Test", servlet);
    w.setAsyncSupported(true);
    ctx.addServletMapping("/test", "Test");

    tomcat.start();

    // Hand-craft the client so we have complete control over the timing
    SocketAddress addr = new InetSocketAddress("localhost", getPort());
    Socket socket = new Socket();
    socket.setSoTimeout(300000);
    socket.connect(addr,300000);
    OutputStream os = socket.getOutputStream();
    Writer writer = new OutputStreamWriter(os, "ISO-8859-1");
    InputStream is = socket.getInputStream();
    Reader r = new InputStreamReader(is, "ISO-8859-1");
    BufferedReader reader = new BufferedReader(r);

    // Write the headers
    writer.write("POST /test HTTP/1.1\r\n");
    writer.write("Host: localhost:8080\r\n");
    writer.write("Transfer-Encoding: chunked\r\n");
    writer.write("\r\n");
    writer.flush();

    validateResponse(reader);

    // Write the request body
    writer.write("2\r\n");
    writer.write("AB\r\n");
    writer.write("0\r\n");
    writer.write("\r\n");
    writer.flush();

    // Write the 2nd request
    writer.write("POST /test HTTP/1.1\r\n");
    writer.write("Host: localhost:8080\r\n");
    writer.write("Transfer-Encoding: chunked\r\n");
    writer.write("\r\n");
    writer.flush();

    // Read the 2nd response
    validateResponse(reader);

    // Write the 2nd request body
    writer.write("2\r\n");
    writer.write("AB\r\n");
    writer.write("0\r\n");
    writer.write("\r\n");
    writer.flush();

    // Done
    socket.close();
}
 
Example 17
Project: de.flapdoodle.solid   File: FlushNode.java   Source Code and License Vote up 4 votes
@Override
public void render(PebbleTemplateImpl self, Writer writer, EvaluationContextImpl context) throws IOException {
    writer.flush();
}
 
Example 18
Project: aos-FileCoreLibrary   File: Util.java   Source Code and License Vote up 4 votes
/***
 * Copies the contents of a Reader to a Writer using a
 * copy buffer of a given size and notifies the provided
 * CopyStreamListener of the progress of the copy operation by calling
 * its bytesTransferred(long, int) method after each write to the
 * destination.  If you wish to notify more than one listener you should
 * use a CopyStreamAdapter as the listener and register the additional
 * listeners with the CopyStreamAdapter.
 * <p>
 * The contents of the Reader are
 * read until its end is reached, but neither the source nor the
 * destination are closed.  You must do this yourself outside of the
 * method call.  The number of characters read/written is returned.
 * <p>
 * @param source  The source Reader.
 * @param dest    The destination writer.
 * @param bufferSize  The number of characters to buffer during the copy.
 *            A zero or negative value means to use {@link #DEFAULT_COPY_BUFFER_SIZE}.
 * @param streamSize  The number of characters in the stream being copied.
 *          Should be set to CopyStreamEvent.UNKNOWN_STREAM_SIZE if unknown.
 * @param listener  The CopyStreamListener to notify of progress.  If
 *      this parameter is null, notification is not attempted.
 * @return  The number of characters read/written in the copy operation.
 * @exception CopyStreamException  If an error occurs while reading from the
 *            source or writing to the destination.  The CopyStreamException
 *            will contain the number of bytes confirmed to have been
 *            transferred before an
 *            IOException occurred, and it will also contain the IOException
 *            that caused the error.  These values can be retrieved with
 *            the CopyStreamException getTotalBytesTransferred() and
 *            getIOException() methods.
 ***/
public static final long copyReader(Reader source, Writer dest,
                                    int bufferSize, long streamSize,
                                    CopyStreamListener listener)
throws CopyStreamException
{
    int chars;
    long total = 0;
    char[] buffer = new char[bufferSize >= 0 ? bufferSize : DEFAULT_COPY_BUFFER_SIZE];

    try
    {
        while ((chars = source.read(buffer)) != -1)
        {
            // Technically, some read(char[]) methods may return 0 and we cannot
            // accept that as an indication of EOF.
            if (chars == 0)
            {
                chars = source.read();
                if (chars < 0) {
                    break;
                }
                dest.write(chars);
                dest.flush();
                ++total;
                if (listener != null) {
                    listener.bytesTransferred(total, chars, streamSize);
                }
                continue;
            }

            dest.write(buffer, 0, chars);
            dest.flush();
            total += chars;
            if (listener != null) {
                listener.bytesTransferred(total, chars, streamSize);
            }
        }
    }
    catch (IOException e)
    {
        throw new CopyStreamException("IOException caught while copying.",
                                      total, e);
    }

    return total;
}
 
Example 19
Project: galop   File: HeaderWriterImpl.java   Source Code and License Vote up 4 votes
@Override
public void writeHeader(final Message message, final Writer writer) throws IOException {

    checkNotNull(message, "message");
    checkNotNull(writer, "writer");

    for (final Entry<String, List<String>> fields : message.getHeaderFields().entrySet()) {

        final String name = fields.getKey();
        final List<String> values = fields.getValue();

        for (final String value : values) {
            writer.write(name + ": " + value + NEW_LINE);
        }

    }

    writer.write(NEW_LINE);
    writer.flush();

}
 
Example 20
Project: manifold   File: StreamUtil.java   Source Code and License Vote up 2 votes
/**
 * Copies the content of an input stream to a writer.
 *
 * @param in     the input stream to read
 * @param writer the writer to write
 *
 * @throws IOException if an I/O error occurs
 */
public static void copy( InputStream in, Writer writer ) throws IOException
{
  copy( getInputStreamReader( in ), writer );
  writer.flush();
}