Example usage for java.io Writer flush

List of usage examples for java.io Writer flush

Introduction

In this page you can find the example usage for java.io Writer flush.

Prototype

public abstract void flush() throws IOException;

Source Link

Document

Flushes the stream.

Usage

From source file:com.moss.appsnap.keeper.Keeper.java

public Keeper(final Url location) {
    log.info("Starting keeper for " + location);

    final DesktopIntegrationStrategy desktop = new Bootstrapper().discover();
    final ProxyFactory proxyFactory = new ProxyFactory(new HessianProxyProvider());
    final AppsnapService snap = proxyFactory.create(AppsnapService.class, location.toString());

    AppsnapServiceInfo serviceInfo;/*from   w ww  .  java  2 s  .  c o  m*/
    while (true) {
        try {
            serviceInfo = snap.serviceInfo();
            break;
        } catch (Exception e) {
            log.error("Error talking to appsnap.  Will try again in 5 seconds.  The message was: "
                    + e.getMessage(), e);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }
    }

    final File dataLocation = desktop.keeperDataDir(serviceInfo.id());

    try {
        final File logOutput = new File(dataLocation, "log4j.log");
        Logger.getRootLogger().addAppender(new FileAppender(new SimpleLayout(), logOutput.getAbsolutePath()));
        log.info("Configured logging to " + logOutput.getAbsolutePath());
    } catch (IOException e) {
        e.printStackTrace();
    }

    log.info("Starting from " + dataLocation.getAbsolutePath());

    Data data;
    try {
        data = new Data(dataLocation);
    } catch (Exception e1) {
        throw new RuntimeException(e1);
    }

    if (data.config.get() == null) {
        if (System.getProperty("dev-bootstrap", "false").equals("true")) {
            KeeperConfig config = new KeeperConfig();
            data.config.put(config);
        } else {
            throw new NullPointerException("Keeper data has no config: have you run the installer?");
        }
    }
    if (location == null) {
        throw new NullPointerException();
    }

    guts = new Guts(serviceInfo, location, proxyFactory, snap, data, desktop);

    desktop.noLongerGutless(guts);

    final Poller poller = new Poller(guts, true);
    poller.start();

    desktop.thePollerWasStartedAndHereItIs(poller);

    desktop.startLocalApiServer(new ApiMessageHandler() {
        final SocketFunction[] commands = new SocketFunction[] { new PollFunction(guts, poller),
                new InstallFunction(guts, poller), new ControlPanelLaunchFunction(guts),
                new LaunchFunction(guts, poller), new PingFuction() };

        public void handle(ApiMessageConnection socket) {
            try {
                log.info("Opening connection");
                StringBuilder input = new StringBuilder();
                Reader r = new InputStreamReader(socket.in());
                log.info("Reading input");
                //               char[] b = new char[1024];
                //               for(int x=r.read(b);x!=-1;x=r.read(b)){
                //                  input.append(b, 0, x);
                //               }
                for (int x = r.read(); x != -1 && x != '\n'; x = r.read()) {
                    input.append((char) x);
                }
                //               r.close();

                log.info("Command: " + input);

                String commandName;
                String commandParams;

                int argsDelimiterPos = input.indexOf(" ");
                if (argsDelimiterPos != -1) {
                    commandName = input.substring(0, argsDelimiterPos);
                    commandParams = input.substring(argsDelimiterPos + 1);
                } else {
                    commandName = input.toString();
                    commandParams = "";
                }
                SocketFunction command = null;
                for (SocketFunction next : commands) {
                    if (next.name().equals(commandName)) {
                        command = next;
                    }
                }

                String response;
                if (command == null) {
                    response = ("Invalid command: " + commandName);
                } else {
                    try {
                        response = command.execute(commandParams);
                    } catch (Exception e) {
                        e.printStackTrace();
                        response = e.getClass().getSimpleName() + ":" + e.getMessage();
                    }
                }

                log.info("Sending response: " + response);

                Writer w = new OutputStreamWriter(socket.out());
                w.write(response);
                w.write('\n');
                w.flush();
                w.close();

            } catch (Throwable e) {
                e.printStackTrace();
            } finally {
                socket.close();
            }
        }
    });

}

From source file:de.hybris.platform.commons.renderer.impl.VelocityTemplateRenderer.java

private void writeToOutput(final Writer result, final InputStream inputStream, final Object context)
        throws IOException {
    final VelocityContext ctx = new VelocityContext();
    ctx.put(contextName, context);/*from w w w.  ja  v a2s . co m*/

    final Reader reader = new InputStreamReader(inputStream, "UTF-8");

    try {
        evaluate(result, ctx, reader);
        result.flush();
    } catch (final Exception e) {
        throw new RendererException("Problem with get velocity stream", e);
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:com.comcast.cns.util.Util.java

/**
  * Generate the confirmation Json string
  * @param arn The top arn for the topic the user is subscribing to.
  * @param token the token for confirming the subscription
  * @return the Json String // ww  w.  j  a  v  a 2 s .c  o  m
  */
public static String generateConfirmationJson(String topicArn, String token, String messageId) {

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Writer writer = new PrintWriter(out);
    JSONWriter jw = new JSONWriter(writer);
    String cnsServiceLocation = CMBProperties.getInstance().getCNSServiceUrl();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); // UTC, no offset
    Date now = new Date();

    try {
        jw = jw.object();
        jw.key("Type").value(CNSMessageType.SubscriptionConfirmation);
        jw.key("MessageId").value(messageId);
        jw.key("Token").value(token);
        jw.key("TopicArn").value(topicArn);
        jw.key("Message").value("You have chosen to subscribe to the topic " + topicArn
                + "\\nTo confirm the subscription, visit the SubscribeURL included in this message.");
        jw.key("SubscribeURL").value(
                cnsServiceLocation + "?Action=ConfirmSubscription&TopicArn=" + topicArn + "&Token=" + token);
        jw.key("Timestamp").value(df.format(now));
        jw.key("SignatureVersion").value("1");
        jw.key("Signature").value("");
        jw.key("SigningCertURL").value("");
        jw.endObject();
        writer.flush();

    } catch (Exception e) {
        return "";
    }

    return out.toString();
}

From source file:com.clican.pluto.orm.dynamic.impl.DynamicORMManagePojoHibernateImpl.java

private void generate(String file, Template template, VelocityContext velocityContext)
        throws ORMManageException {
    Writer w = null;
    try {/*from   w  w w .  j a v a  2s  .  c o  m*/
        w = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
        template.merge(velocityContext, w);
        w.flush();
    } catch (Exception e) {
        throw new ORMManageException(e);
    } finally {
        try {
            if (w != null) {
                w.close();
            }
        } catch (Exception e) {
            log.error("", e);
        }
    }
}

From source file:com.zyeeda.framework.template.internal.FreemarkerTemplateServiceProvider.java

@Override
public String render(String template, Map<String, Object> args) throws IOException {
    Reader reader = null;//from   w  w w  . java2s.com
    Writer writer = null;
    try {
        reader = new StringReader(template);
        Template tpl = new Template(null, reader, this.config);
        writer = new StringWriter();
        this.putBuildinVariables(args);
        tpl.process(args, writer);
        writer.flush();
        return writer.toString();
    } catch (TemplateException e) {
        throw new TemplateServiceException(e);
    } finally {
        if (reader != null) {
            reader.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.util.BeanToTextExporter.java

public static String beanListToText(final String type, final Writer out, final Map<String, String> columns,
        final List data, final DateFormat dateFormat) {
    CSVWriter writer = new CSVWriter(out);
    if ("tab".equals(type)) {
        writer = new CSVWriter(out, '\t', CSVWriter.NO_QUOTE_CHARACTER);
    }/*from  ww w .  j  a va 2s  . c o  m*/
    List<String> cols = new LinkedList<String>();
    try {
        //Writing the column headers
        for (Map.Entry<String, String> e : columns.entrySet()) {
            cols.add(e.getValue());
        }
        writer.writeNext((String[]) cols.toArray(new String[columns.size()]));
        cols.clear();
        //Writing the data
        if (data != null) {
            for (Object o : data) {
                for (Map.Entry<String, String> e : columns.entrySet()) {
                    final Object obj = getAndInvokeGetter(o, e.getKey());
                    String value = getExportString(obj, dateFormat);

                    if ("tab".equals(type)) {
                        value = value.replace("\t", "   ");
                    }
                    cols.add(value);
                }
                writer.writeNext((String[]) cols.toArray(new String[columns.size()]));
                cols.clear();
            }
        }
        writer.close();
        out.flush();
        out.close();
    } catch (Exception e) {
        logger.debug(FancyExceptionLogger.printException(e));
        return "An error occurred.";
    }
    return out.toString();
}

From source file:org.ala.util.CsvMerger.java

private void writeCsv(String[] f1, String[] f2, int k2, Writer writer) throws IOException {
    boolean isFirst = true;

    for (String f : f1) {
        if (!isFirst) {
            writer.write(",");
        }//from w  ww  . j  a v  a2  s  .  c  o m
        writer.write("\"");
        writer.write(f);
        writer.write("\"");
        isFirst = false;
        writer.flush();
    }

    for (int i = 0; i < f2.length; i++) {
        if (i == k2) {
            continue;
        } else {
            writer.write(",");
            writer.write("\"");
            writer.write(f2[i]);
            writer.write("\"");
            writer.flush();
        }
    }

    writer.write("\n");

    writer.flush();
}

From source file:com.comcast.cns.model.CNSRetryPolicy.java

@Override
public String toString() {

    try {//from w ww  .  j  ava  2s .co  m

        JSONObject json = this.toJSON();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Writer writer = new PrintWriter(out);
        json.write(writer);
        writer.flush();

        return out.toString();

    } catch (Exception e) {
        return null;
    }
}

From source file:com.intel.cosbench.exporter.ScriptsLogExporter.java

private void exportWorkloadLog(Writer writer) throws IOException {
    writer.write("=========================");
    writer.write("=========================");
    writer.write(" workload level ");
    writer.write("=========================");
    writer.write("=========================");
    writer.write('\n');
    String wsId = workload.getId();
    doExportLog(writer, wsId);//from w ww. j  a v  a2  s  .  c  om
    writer.flush();
}