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:net.cit.tetrad.resource.MainResource.java

/**
 *  Master/Slave //w  w  w.  ja  v  a  2s  .c  o  m
 * @param dto
 * @return
 * @throws Exception
 */
@RequestMapping("/getMyState.do")
public void getMyState(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String deviceLst = request.getParameter("myStateLst");
    try {
        if (!StringUtil.isNull(deviceLst)) {
            String[] deviceCode = deviceLst.split(",");
            Map<String, Object> fromMongo = new HashMap<String, Object>();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < deviceCode.length; i++) {
                fromMongo = comandService.insertCommand(Integer.parseInt(deviceCode[i]), MYSTATE);
                sb.append(deviceCode[i] + ":" + fromMongo.get("myState"));
                if (i < deviceCode.length - 1)
                    sb.append(",");
            }

            Writer writer = setResponse(response).getWriter();
            writer.write(sb.toString());
            writer.flush();
        }
    } catch (Exception e) {
        log.error(e, e);
    }
}

From source file:com.norconex.collector.core.crawler.AbstractCrawlerConfig.java

@Override
public void saveToXML(Writer out) throws IOException {
    try {// w w  w  .  j  a va 2  s .com
        out.flush();
        EnhancedXMLStreamWriter writer = new EnhancedXMLStreamWriter(out);
        writer.writeStartElement("crawler");
        writer.writeAttributeClass("class", getClass());
        writer.writeAttribute("id", getId());

        writer.writeElementInteger("numThreads", getNumThreads());
        writer.writeElementString("workDir", getWorkDir().toString());
        writer.writeElementInteger("maxDocuments", getMaxDocuments());

        OrphansStrategy strategy = getOrphansStrategy();
        if (strategy != null) {
            writer.writeElementString("orphansStrategy", strategy.toString());
        }
        writer.flush();

        writeObject(out, "crawlDataStoreFactory", getCrawlDataStoreFactory());
        writeArray(out, "referenceFilters", "filter", getReferenceFilters());
        writeArray(out, "metadataFilters", "filter", getMetadataFilters());
        writeArray(out, "documentFilters", "filter", getDocumentFilters());
        writeArray(out, "crawlerListeners", "listener", getCrawlerListeners());
        writeObject(out, "importer", getImporterConfig());
        writeObject(out, "committer", getCommitter());
        writeObject(out, "documentChecksummer", getDocumentChecksummer());
        writeObject(out, "spoiledReferenceStrategizer", getSpoiledReferenceStrategizer());

        saveCrawlerConfigToXML(out);

        writer.writeEndElement();
        writer.flush();

    } catch (XMLStreamException e) {
        throw new IOException("Cannot save as XML.", e);
    }

}

From source file:com.igormaznitsa.jhexed.swing.editor.ui.exporters.JavaConstantExporter.java

@Override
  public void export(final File file) throws IOException {
      final StringBuilder buffer = new StringBuilder(16384);

      final Set<String> processedLayerNames = new HashSet<String>();
      final Set<String> processedConstantNames = new HashSet<String>();

      int layerIndex = -1;

      final String className = FilenameUtils.getBaseName(file.getName());

      buffer.append("/**");
      nextLine(buffer);// ww w . j a va2s .  c o m
      commentLine(buffer, this.docOptions.getCommentary().replace('\n', ' '));
      commentLine(buffer, "");
      commentLine(buffer, "Generated by the JHexedSwingEditor");
      commentLine(buffer, "The Project page : https://code.google.com/p/jhexed/");
      commentLine(buffer, SimpleDateFormat.getInstance().format(new Date()));
      buffer.append(" */");
      nextLine(buffer);

      buffer.append("public interface ").append(className).append(" {");
      nextLine(buffer);

      printTab(buffer);
      buffer.append("public static final int HEX_EMPTY = 0; // The Empty hex value");
      nextLine(buffer);
      nextLine(buffer);

      for (final LayerExportRecord r : exportData.getLayers()) {
          layerIndex++;

          if (r.isAllowed()) {
              final String layerName = r.getLayer().getLayerName().trim();
              final String layerComment = r.getLayer().getComments().trim();
              final String preparedLayerName;
              if (layerName.isEmpty()) {
                  preparedLayerName = "L" + Integer.toString(layerIndex);
              } else {
                  preparedLayerName = adaptTextForJava(layerName);
              }

              if (processedLayerNames.contains(preparedLayerName)) {
                  throw new ExportException("Can't make export because there is duplicated identifier for layer '"
                          + layerName + "' (" + preparedLayerName + ')');
              }
              processedLayerNames.add(preparedLayerName);

              printTab(buffer);
              endLineComment(buffer, "Layer " + layerIndex);
              if (!layerComment.isEmpty()) {
                  printTab(buffer);
                  endLineComment(buffer, layerComment);
              }

              printTab(buffer);
              buffer.append("public static final int LAYER_").append(preparedLayerName).append(" = ")
                      .append(layerIndex).append(';');
              nextLine(buffer);
              nextLine(buffer);

              for (int e = 1; e < r.getLayer().getHexValuesNumber(); e++) {
                  final HexFieldValue value = r.getLayer().getHexValueForIndex(e);
                  final String valueName = value.getName().trim();
                  final String valueComment = value.getComment();

                  final String preparedValueName;
                  if (valueName.isEmpty()) {
                      preparedValueName = "VALUE" + e;
                  } else {
                      preparedValueName = adaptTextForJava(valueName);
                  }

                  final String fullName = preparedLayerName + '_' + preparedValueName;
                  if (processedConstantNames.contains(fullName)) {
                      throw new ExportException(
                              "Can't make export because there is duplicated identifier for layer value '"
                                      + valueName + "\' (" + fullName + ')');
                  }
                  processedConstantNames.add(fullName);

                  printTab(buffer);
                  buffer.append("public static final int ").append(fullName).append(" = ").append(e).append("; ");
                  endLineComment(buffer, valueComment);
              }
              nextLine(buffer);
          }
      }
      buffer.append('}');
      nextLine(buffer);

      Writer writer = null;
      try {
          writer = new BufferedWriter(new FileWriterWithEncoding(file, "UTF-8", false));
          writer.write(buffer.toString());
          writer.flush();
      } finally {
          IOUtils.closeQuietly(writer);
      }
  }

From source file:org.openmrs.module.sdmxhddataexport.web.controller.report.ReportDataElementController.java

@RequestMapping(value = "/module/sdmxhddataexport/downloadExecutedReport.form", method = RequestMethod.GET)
public String downloadExecutedReport(@RequestParam(value = "reportId", required = false) Integer reportId,
        @RequestParam(value = "startDate", required = false) String startDate,
        @RequestParam(value = "endDate", required = false) String endDate,
        @RequestParam(value = "outputType", required = false) String outputType, HttpServletRequest request,
        HttpServletResponse response, Model model) throws ParseException, IOException {
    String u = request.getParameter("url");
    System.out.print("i think it is a url - " + u);
    //String s=(u.split("/")[2]).split(":")[0];
    String urlToRead = "http://" + u + request.getContextPath()
            + "/module/sdmxhddataexport/resultExecuteReport.form?reportId=" + reportId + "&startDate="
            + startDate + "&endDate=" + endDate;
    //       String urlToRead = "http://" + "127.0.0.1" + ":"
    //        + request.getLocalPort() + request.getContextPath()
    //        + "/module/sdmxhddataexport/resultExecuteReport.form?reportId="
    //        + reportId + "&startDate=" + startDate + "&endDate=" + endDate;
    URL url;//from w w  w. j  ava2  s.c om

    System.out.println("http servlet request" + u + request.getLocalAddr() + "," + request.getLocalName());
    HttpURLConnection conn;
    InputStream rd = null;
    String contents = "";
    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        rd = conn.getInputStream();
        byte[] bytes = new byte[1024];
        int bytesRead;
        boolean firstRead = true;

        while ((bytesRead = rd.read(bytes)) != -1) {
            String str = new String(bytes);
            str = str.substring(0, bytesRead);
            //if(firstRead){
            firstRead = false;
            str = str.replaceAll("^\\s+", "");
            System.out.print(str);
            //}
            contents = contents.concat(str);

        }
        //rd.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (outputType.contentEquals("download")) {
        //           File fil1=new File("/sdmx-temp-sdmx.xml");
        //           FileOutputStream fos = new FileOutputStream("sdmx-temp-sdmx.xml");
        File file = File.createTempFile("sdmx", "report");
        Writer output = new BufferedWriter(new FileWriter(file));
        output.write(contents);
        output.flush();
        //           output = new BufferedWriter(new FileWriter(fil1));
        //           output.write(contents);
        //           output.flush();

        output.close();
        System.out.println("these are contents ------------------------");
        System.out.println(contents);
        System.out.println("these wre contents ------------------------");
        response.setContentType("application/download");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + "sdmxhd-" + formatter.format(new Date()) + ".xml" + "\"");
        FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
        file.delete();

    }

    if (outputType.equals("view")) {
        try {
            contents = transform(contents);
        } catch (Exception e) {
            System.out.println("some error" + contents);
            e.printStackTrace();
        }
        model.addAttribute("contents", contents);
        System.out.println("Now contents---------------------------" + contents + ":");
        return "/module/sdmxhddataexport/report/resultView";
    } else if (outputType.equals("send")) {
        HttpSession httpSession = request.getSession();

        String urlStr = Context.getAdministrationService().getGlobalProperty("sdmxhddataexport.reportUrl");
        String[] paramName = { "report1" };
        String[] paramVal = new String[10];
        paramVal[0] = contents;
        try {
            String Response = HttpRestUtil.httpRestPost(urlStr, paramName, paramVal);
            System.out.println("Response:" + Response);
            String temp = "Report Sent Successfully";
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    StringUtils.isBlank(temp) ? "sdmxhddataexport.dataElement.deleted" : temp);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return "/module/sdmxhddataexport/report/list";
}

From source file:com.norconex.collector.core.crawler.AbstractCrawlerConfig.java

protected void writeObject(Writer out, String tagName, Object object, boolean ignore) throws IOException {
    out.flush();
    if (object == null) {
        if (ignore) {
            out.write("<" + tagName + " ignore=\"" + ignore + "\" />");
        }// w  w w . j  av  a2s .  c  o m
        return;
    }
    StringWriter w = new StringWriter();
    if (object instanceof IXMLConfigurable) {
        ((IXMLConfigurable) object).saveToXML(w);
    } else {
        w.write("<" + tagName + " class=\"" + object.getClass().getCanonicalName() + "\" />");
    }
    String xml = w.toString();
    if (ignore) {
        xml = xml.replace("<" + tagName + " class=\"", "<" + tagName + " ignore=\"true\" class=\"");
    }
    out.write(xml);
    out.flush();
}

From source file:org.usrz.libs.webtools.utils.JsonMessageBodyWriter.java

@Override
protected void writeTo(Object instance, Annotation[] annotations, Writer writer)
        throws IOException, WebApplicationException {
    mapper.writeValue(new Writer() {

        @Override/*from www  .j  a va  2 s. c  om*/
        public void write(int c) throws IOException {
            writer.write(c);
        }

        @Override
        public void write(char[] buf, int off, int len) throws IOException {
            writer.write(buf, off, len);
        }

        @Override
        public void flush() throws IOException {
            writer.flush();
        }

        @Override
        public void close() {
            /* Avoid bug in Jackson always closing */
        }

    }, instance);
}

From source file:com.joliciel.csvLearner.EventCombinationGenerator.java

public void writeCombination(Writer writer) {
    try {//from   www.  jav a2 s .com
        try {
            writer.write("ID,outcome,\n");
            for (Entry<String, String> entry : this.combination.entrySet()) {
                writer.write(CSVFormatter.format(entry.getKey()) + "," + CSVFormatter.format(entry.getValue())
                        + ",\n");
            }
        } finally {
            writer.flush();
            writer.close();
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:hu.petabyte.redflags.engine.gear.export.FlagExporter.java

private void writeFile() throws IOException {
    File csvFile = new File(filename);
    Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "UTF-8"));
    for (ArrayList<String> row : grid) {
        for (String col : row) {
            if (null != col) {
                out.write(col);//from w  w  w  .java  2  s.com
            }
            out.write("\t");
        }
        out.write("\n");
    }
    out.flush();
    out.close();
}

From source file:io.github.jeddict.jcode.parser.ejs.EJSParser.java

public Consumer<FileTypeStream> getParserManager(List<String> skipFile) {
    return (fileType) -> {
        try {/*ww  w . j a v  a 2  s.  c  o  m*/
            if (SKIP_FILE_TYPE.contains(fileType.getFileType())
                    || (skipFile != null && skipFile.contains(fileType.getFileName()))
                    || fileType.isSkipParsing()) {
                IOUtils.copy(fileType.getInputStream(), fileType.getOutputStream());
                if (!(fileType.getInputStream() instanceof ZipInputStream)) {
                    fileType.getInputStream().close();
                }
                fileType.getOutputStream().close();
            } else {
                Charset charset = Charset.forName("UTF-8");
                Reader reader = new BufferedReader(new InputStreamReader(fileType.getInputStream(), charset));
                Writer writer = new BufferedWriter(new OutputStreamWriter(fileType.getOutputStream(), charset));
                IOUtils.write(parse(reader), writer);
                if (!(fileType.getInputStream() instanceof ZipInputStream)) {
                    reader.close();
                }
                writer.flush();
                writer.close();
            }

        } catch (ScriptException | IOException ex) {
            Exceptions.printStackTrace(ex);
            System.out.println("Error in template : " + fileType.getFileName());
        }
    };
}