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:eu.planets_project.tb.utils.ExperimentUtils.java

public static void outputAnalysis(OutputStream os, String expId, DATA_FORMAT format) throws IOException {
    log.info("Writing out experiment " + expId + " as " + format);

    Writer out = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    CSVWriter writer = new CSVWriter(out);

    long id = Long.parseLong(expId);

    ExperimentPersistencyRemote edao = ExperimentPersistencyImpl.getInstance();
    Experiment exp = edao.findExperiment(id);

    // The string array 
    String sa[] = new String[8];
    sa[0] = "Name";
    sa[1] = "Digital Object #";
    sa[2] = "Digital Object Source";
    sa[3] = "Agent Type";
    sa[4] = "Agent Name";
    sa[5] = "User Environment Description";
    sa[6] = "Property Identifier";
    sa[7] = "Property Value";
    // write the headers out:
    writer.writeNext(sa);// w w  w.  j a  v a  2 s . c  o  m

    // Loop through:
    int bi = 1;
    for (BatchExecutionRecordImpl batch : exp.getExperimentExecutable().getBatchExecutionRecords()) {
        // log.info("Found batch... "+batch);
        int doi = 1;
        for (ExecutionRecordImpl exr : batch.getRuns()) {
            // log.info("Found Record... "+exr+" stages: "+exr.getStages());
            if (exr != null) {
                for (MeasurementEventImpl me : exr.getMeasurementEvents()) {
                    for (MeasurementImpl m : me.getMeasurements()) {
                        sa[0] = exp.getExperimentSetup().getBasicProperties().getExperimentName();
                        sa[1] = "" + doi;
                        sa[2] = exr.getDigitalObjectReferenceCopy();
                        sa[3] = me.getAgent().getType().toString();
                        sa[4] = me.getAgent().getName();
                        sa[5] = me.getAgent().getUserEnvironmentDescription();
                        sa[6] = m.getIdentifier();
                        sa[7] = m.getValue();
                        // Write out CSV:
                        writer.writeNext(sa);
                    }
                }
            }
            // Increment, for the next DO.
            doi++;
            out.flush();
        }
        // Increment to the next batch:
        bi++;
    }
}

From source file:net.cit.tetrad.resource.GraphResource.java

@RequestMapping("/lockSumGraph.do")
public void lockSumGraph(HttpServletRequest request, HttpServletResponse response, CommonDto dto) {
    log.debug("start - lockSumGraph");
    try {/*from  w ww  .  j a  va 2s.c  om*/
        PersonJson result = new PersonJson();

        List<String> fileName = new ArrayList<String>();
        String[] dsNameArr = { "totalDbLocksTimeLockedMicros_w_sum", "totalDbLocksTimeLockedMicros_r_sum" };
        for (String dsName : dsNameArr) {
            String[] filters = { dsName };
            GraphDefInfo graphInfo = subDao.getLockGraphDefInfoForSubGraph(dto);
            graphInfo.setFileName(dsName);
            graphInfo.setFilters(filters);
            graphInfo.setGraphLegend(filters);
            fileName.add(rrdService.totalMultiGraphPerRrd(graphInfo));
        }

        result.setsEcho(Integer.parseInt(Utility.isNullNumber(request.getParameter("sEcho"))));
        result.setAaData(fileName);

        JSONObject jsonObject = JSONObject.fromObject(result);

        Writer writer = setResponse(response).getWriter();
        writer.write(jsonObject.toString());

        log.debug(jsonObject.toString());
        writer.flush();

    } catch (Exception e) {
        log.error(e, e);
    }
    log.debug("end - lockSumGraph");
}

From source file:com.tinspx.util.json.JSONParserTest.java

public void printRandom() throws IOException {
    RandomJSONGenerator g = RandomJSONGenerator.builder().maxFieldLength(64).maxStringLength(256)
            .maxObjectLength(16).maxArrayLength(32).bigNumbers(false).build();

    Object value = g.buildRandomJSON(2, 4);

    Writer w = writer_utf(RAW);
    ConfigurableWriter.INSTANCE.writeTo(w, value);
    w.flush();
    w.close();/*from  w ww  .  ja  va2  s. c om*/

    w = writer_utf(FORMATTED);
    IndentingWriter.indentingBuilder().build().writeTo(w, value);
    w.flush();
    w.close();

    assertTrue(true);
}

From source file:net.cit.tetrad.resource.GraphResource.java

@RequestMapping("/lockGraph.do")
public void lockGraph(HttpServletRequest request, HttpServletResponse response, CommonDto dto) {
    log.debug("start - lockGraph.do");
    try {//from   w w w. j  a v a 2 s  .  c  o  m
        PersonJson result = new PersonJson();

        String type_gubun = dto.getType_gubun();
        if (type_gubun.equals("deviceLock") || type_gubun.equals("device") || type_gubun.equals("event")) {
            setMulti(dto);
        } else if (type_gubun.equals("typeLock")) {
            setType(dto);
        } else if (type_gubun.equals("groupLock")) {
            setGroupCode(dto);
        } else if (type_gubun.equals("dbLock")) {
            dto.setSortItem("big");
            String[] strs = { dto.getDbname() };
            dto.setDbNameLst(strs);
        }

        List<String> fileName = new ArrayList<String>();
        boolean isExistDeviceLst = dto.getDeviceLst().length != 0;
        boolean isExistDsNameLst = dto.getDbNameLst().length != 0;
        if (isExistDeviceLst && isExistDsNameLst)
            fileName = setLockGraphInfo(dto);

        result.setsEcho(Integer.parseInt(Utility.isNullNumber(request.getParameter("sEcho"))));
        result.setAaData(fileName);

        JSONObject jsonObject = JSONObject.fromObject(result);

        Writer writer = setResponse(response).getWriter();
        writer.write(jsonObject.toString());

        log.debug(jsonObject.toString());
        writer.flush();

    } catch (Exception e) {
        log.error(e, e);
    }
    log.debug("end - lockGraph");
}

From source file:net.cit.tetrad.resource.GraphResource.java

/**
 * DB  /*from w  w  w  .  ja  va 2 s.  c o  m*/
 * 
 * @param mav
 * @return
 */
@RequestMapping("/selectDbLst.do")
public void dbLst(HttpServletRequest request, HttpServletResponse response) {
    String typeGubun = Utility.isNull(request.getParameter("type_gubun"));
    try {
        PersonJson result = new PersonJson();
        Query query = new Query();
        if (typeGubun.equals("deviceLock") || typeGubun.equals("event")) {
            int deviceCode = (Integer.parseInt(Utility.isNullNumber(request.getParameter("deviceCode"))));
            if (deviceCode != 0)
                query.addCriteria(Criteria.where(DEVICECODE).is(deviceCode));
        } else if (typeGubun.equals("typeLock")) {
            String type = Utility.isNull(request.getParameter("type"));
            if (!type.equals(""))
                query.addCriteria(Criteria.where(DEVICE_TYPE).is(type));
        } else if (typeGubun.equals("groupLock")) {
            String[] groups = request.getParameter("groupCode").split(",");
            List<Integer> list = new ArrayList<Integer>();
            for (String group : groups) {
                list.add(new Integer(group));
            }
            if (groups.length != 0)
                query.addCriteria(Criteria.where(DEVICE_GROUPCODE).in(list));

        }

        List<String> dbLst = mkDbLst(query);

        result.setsEcho(Integer.parseInt(Utility.isNullNumber(request.getParameter("sEcho"))));
        result.setAaData(dbLst);

        JSONObject jsonObject = JSONObject.fromObject(result);

        Writer writer = setResponse(response).getWriter();
        writer.write(jsonObject.toString());

        log.debug(jsonObject.toString());
        writer.flush();

    } catch (Exception e) {
        log.error(e, e);
    }
}

From source file:gov.nih.nci.cacis.common.util.ExtractSchematron.java

/**
 * Read the ISO datatypes schema and build up a mapping of datatype to schematron abstract rule ids. At the same
 * time, extract the abstract rules and write them to the abstract schematron file.
 * // w w  w . j  a  v  a2 s. c  o m
 * @param datatypeSchemaLocation
 * @param abstractSchematronLocation
 * @throws IOException
 */
private void processDatatypes(String datatypesAndFlavorsSchemaLocations, String abstractSchematronLocation)
        throws IOException {
    final String[] schemaLocations = StringUtils.split(datatypesAndFlavorsSchemaLocations, ",");
    final XSModel schema = this.schemaLoader
            .loadURIList(new StringListImpl(schemaLocations, schemaLocations.length));
    if (schema == null) {
        throw new IOException("Schema not loaded for URI(s): " + datatypesAndFlavorsSchemaLocations);
    }
    final Writer out = new FileWriter(abstractSchematronLocation);
    try {
        out.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
        out.write("<sch:pattern name=\"abstract rules\" xmlns:sch=\"" + SCH_NS + "\">\n");

        final XSNamedMap typeDecls = schema.getComponents(XSTypeDefinition.COMPLEX_TYPE);
        for (int i = 0; i < typeDecls.getLength(); i++) {
            final XSComplexTypeDefinition typeDecl = (XSComplexTypeDefinition) typeDecls.item(i);
            processDatatype(typeDecl, out);
        }
        out.write("</sch:pattern>\n");
        out.flush();
    } finally {
        try {
            out.close();
            // CHECKSTYLE:OFF We want the original exception to be thrown.
        } catch (final Exception ex) {
            // CHECKSTYLE:ON
            LOG.error("Error closing output stream: " + ex.getMessage(), ex);
        }
    }

}

From source file:net.cit.tetrad.resource.GraphResource.java

@RequestMapping("/subGraph.do")
public void subGraph(HttpServletRequest request, HttpServletResponse response, CommonDto dto) {
    log.debug("start - subGraph.do");
    String gubun = Utility.isNull(request.getParameter("gubun"));

    if (!gubun.equals("")) {
        String typeGubunStr = Utility.isNull(request.getParameter("type_gubun"));
        String dsName = Utility.isNull(request.getParameter("dsNameLst"));
        dto.setType_gubun(typeGubunStr);
        String[] dsNameLst = { dsName };
        dto.setDsNameLst(dsNameLst);/*from   w  ww .  j av  a2 s .c  om*/
    }
    try {
        PersonJson result = new PersonJson();

        String type_gubun = dto.getType_gubun();
        if (type_gubun.equals("dsName")) {
            setDsName(dto);
        } else if (type_gubun.equals("group")) {
            setGroupCode(dto);
        } else if (type_gubun.equals("type")) {
            setType(dto);
        } else if (type_gubun.equals("device") || type_gubun.equals("event")) {
            setDevice(dto);
        } else if (type_gubun.equals("multi") || type_gubun.equals("deviceDb")) {
            setMulti(dto);
        }

        List<String> fileName = new ArrayList<String>();
        boolean isExistDeviceLst = dto.getDeviceLst().length != 0;
        boolean isExistDsNameLst = dto.getDsNameLst().length != 0;
        if (isExistDeviceLst && isExistDsNameLst)
            fileName = setGraphInfo(dto);

        result.setsEcho(Integer.parseInt(Utility.isNullNumber(request.getParameter("sEcho"))));
        result.setAaData(fileName);

        JSONObject jsonObject = JSONObject.fromObject(result);

        Writer writer = setResponse(response).getWriter();
        writer.write(jsonObject.toString());

        log.debug(jsonObject.toString());
        writer.flush();

    } catch (Exception e) {
        log.error(e, e);
    }
    log.debug("end - subGraph.do");
}

From source file:com.tinspx.util.json.JSONParserTest.java

public void logParse() throws IOException {
    Object value = gen.buildRandomJSON(16, 12);
    writeFormatted(LOG_JSON, value);/*from w  w  w  .  j a  va  2  s.co m*/

    CAWriter w = new CAWriter(1024 * 64);
    ConfigurableWriter.INSTANCE.writeTo(w, value);

    Writer out = writer(LOG_HANDLER);
    JSONParser.create(stream(w), new LoggingHandler(out), STRICT).parseFully();
    out.flush();
    out.close();
    assertTrue(true);
}

From source file:com.google.gerrit.server.mail.SmtpEmailSender.java

@Override
public void send(final Address from, Collection<Address> rcpt, final Map<String, EmailHeader> callerHeaders,
        final String body) throws EmailException {
    if (!isEnabled()) {
        throw new EmailException("Sending email is disabled");
    }//from   w  w  w  . j a  v  a 2  s.  c  o m

    final Map<String, EmailHeader> hdrs = new LinkedHashMap<String, EmailHeader>(callerHeaders);
    setMissingHeader(hdrs, "MIME-Version", "1.0");
    setMissingHeader(hdrs, "Content-Type", "text/plain; charset=UTF-8");
    setMissingHeader(hdrs, "Content-Transfer-Encoding", "8bit");
    setMissingHeader(hdrs, "Content-Disposition", "inline");
    setMissingHeader(hdrs, "User-Agent", "Gerrit/" + Version.getVersion());
    if (importance != null) {
        setMissingHeader(hdrs, "Importance", importance);
    }
    if (expiryDays > 0) {
        Date expiry = new Date(System.currentTimeMillis() + expiryDays * 24 * 60 * 60 * 1000);
        setMissingHeader(hdrs, "Expiry-Date",
                new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z").format(expiry));
    }

    StringBuffer rejected = new StringBuffer();
    try {
        final SMTPClient client = open();
        try {
            if (!client.setSender(from.email)) {
                throw new EmailException("Server " + smtpHost + " rejected from address " + from.email);
            }

            /* Do not prevent the email from being sent to "good" users simply
             * because some users get rejected.  If not, a single rejected
             * project watcher could prevent email for most actions on a project
             * from being sent to any user!  Instead, queue up the errors, and
             * throw an exception after sending the email to get the rejected
             * error(s) logged.
             */
            for (Address addr : rcpt) {
                if (!client.addRecipient(addr.email)) {
                    String error = client.getReplyString();
                    rejected.append("Server " + smtpHost + " rejected recipient " + addr + ": " + error);
                }
            }

            Writer w = client.sendMessageData();
            if (w == null) {
                /* Include rejected recipient error messages here to not lose that
                 * information. That piece of the puzzle is vital if zero recipients
                 * are accepted and the server consequently rejects the DATA command.
                 */
                throw new EmailException(
                        rejected + "Server " + smtpHost + " rejected DATA command: " + client.getReplyString());
            }
            w = new BufferedWriter(w);

            for (Map.Entry<String, EmailHeader> h : hdrs.entrySet()) {
                if (!h.getValue().isEmpty()) {
                    w.write(h.getKey());
                    w.write(": ");
                    h.getValue().write(w);
                    w.write("\r\n");
                }
            }

            w.write("\r\n");
            w.write(body);
            w.flush();
            w.close();

            if (!client.completePendingCommand()) {
                throw new EmailException(
                        "Server " + smtpHost + " rejected message body: " + client.getReplyString());
            }

            client.logout();
            if (rejected.length() > 0) {
                throw new EmailException(rejected.toString());
            }
        } finally {
            client.disconnect();
        }
    } catch (IOException e) {
        throw new EmailException("Cannot send outgoing email", e);
    }
}

From source file:com.tinspx.util.json.JSONParserTest.java

public void printEvents() throws IOException {
    //        String json = "], 'string']".replace('\'', '"');
    //        String json = ",\"89\":null}], 'string']".replace('\'', '"');
    String json = "'key': 'value' ,\n'89':null}], 'string'], 'another string', 124.56, [{}]], [], 'test', {},"
            .replace('\'', '"');

    Writer w = new OutputStreamWriter(System.out);
    JSONParser.create(stream(json), new LoggingHandler(w)).parseFragment();
    w.flush();
    System.out.println();//from  www .  j a v a  2  s  .c om

    FragmentBuilder frag = new FragmentBuilder();
    JSONParser.create(stream(json), frag).parseFragment();
    System.out.println(frag.get());

    writeIndentingOut(frag.get());

    assertTrue(true);
}