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.newrelic.agent.transport.DataSenderImpl.java

private byte[] writeData(String encoding, JSONStreamAware params)/* 945:    */ throws IOException
/* 946:    */ {/*from   w  ww  .  ja  v a  2s.  c  o  m*/
    /* 947:760 */ ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    /* 948:761 */ Writer out = null;
    /* 949:    */ try
    /* 950:    */ {
        /* 951:763 */ OutputStream os = getOutputStream(outStream, encoding);
        /* 952:764 */ out = new OutputStreamWriter(os, "UTF-8");
        /* 953:765 */ JSONValue.writeJSONString(params, out);
        /* 954:766 */ out.flush();
        /* 955:    */ }
    /* 956:    */ finally
    /* 957:    */ {
        /* 958:768 */ if (out != null) {
            /* 959:769 */ out.close();
            /* 960:    */ }
        /* 961:    */ }
    /* 962:772 */ return outStream.toByteArray();
    /* 963:    */ }

From source file:net.jcreate.e3.templateEngine.jxp.JxpTemplateEngine.java

protected void mergeStringTemplate(Template pTemplate, Context pContext, Writer pWriter)
        throws MergeTemplateException {
    String encoding = pTemplate.getInputEncoding();
    ByteArrayPageSource byteArrayPageSource = new ByteArrayPageSource();
    JxpContext context = new JxpContext(byteArrayPageSource);
    JxpProcessor processor = new JxpProcessor(context);

    String templateStr = this.getStrTemplate(pTemplate);
    try {/*  w ww .j a  v  a 2s  .  c o m*/
        byteArrayPageSource.putPageBuffer(STR_PATH_ID, templateStr.getBytes(encoding));
    } catch (UnsupportedEncodingException e) {
        final String MSG = "?? \"" + templateStr + "\"  !" + e.getMessage();
        if (log.isErrorEnabled()) {
            log.error(MSG, e);
        }
        throw new MergeTemplateException(MSG, e);
    }
    if (pContext == null) {
        pContext = new DefaultContext();
    }
    Map params = pContext.getParameters();
    try {
        processor.process(STR_PATH_ID, pWriter, params);
    } catch (Exception e) {
        final String MSG = "?? \"" + templateStr + "\"  !" + e.getMessage();
        if (log.isErrorEnabled()) {
            log.error(MSG, e);
        }
        throw new MergeTemplateException(MSG, e);
    }

    try {
        pWriter.flush();
    } catch (IOException e) {
        final String MSG = "?? \"" + templateStr + "\"  !" + e.getMessage();
        if (log.isErrorEnabled()) {
            log.error(MSG, e);
        }
        throw new MergeTemplateException(MSG, e);
    }

}

From source file:com.fluidops.iwb.deepzoom.CXMLServlet.java

private void writeImageListToFile(String dirString, int cacheHash, Vector<String> imageList)
        throws IOException {

    File dir = IWBFileUtil.getFileInDataFolder("pivotCache");
    if (!dir.exists() || !dir.isDirectory()) {
        GenUtil.mkdir(dir);/*  w  ww.j  av  a  2s  . com*/
    }

    dir = IWBFileUtil.getFileInDataFolder("pivotCache/" + dirString);
    if (!dir.exists() || !dir.isDirectory()) {
        GenUtil.mkdir(dir);
    }

    Writer fw = null;
    try {
        File file = new File(dir, String.valueOf(cacheHash));
        fw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        for (String s : imageList) {
            fw.write(s + "\n");
        }
        fw.flush();
    } finally {
        IOUtils.closeQuietly(fw);
    }
}

From source file:com.amalto.core.storage.record.SystemDataRecordXmlWriter.java

@Override
public void write(DataRecord record, Writer writer) throws IOException {
    FieldPrinter fieldPrinter = new FieldPrinter(record, writer);
    Set<FieldMetadata> fields = type == null ? new HashSet<FieldMetadata>(record.getType().getFields())
            : new HashSet<FieldMetadata>(type.getFields());
    // Print isMany=false as attributes
    fieldPrinter.printAttributes(true);//from   ww w .  java2  s  . c  o  m
    writer.write("<" + getRootElementName(record)); //$NON-NLS-1$ 
    Iterator<FieldMetadata> iterator = fields.iterator();
    while (iterator.hasNext()) {
        FieldMetadata field = iterator.next();
        if (field instanceof SimpleTypeFieldMetadata && !field.isMany()
                && isValidAttributeType(field.getType())) {
            writer.append(' ');
            field.accept(fieldPrinter);
            iterator.remove();
        }
    }
    writer.write('>');
    // Print isMany=true as elements
    fieldPrinter.printAttributes(false);
    for (FieldMetadata field : fields) {
        field.accept(fieldPrinter);
    }
    writer.write("</" + getRootElementName(record) + ">"); //$NON-NLS-1$ //$NON-NLS-2$
    writer.flush();
}

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

private void doCommandAnalyse() throws IOException {
    if (featureDir == null)
        throw new RuntimeException("Missing argument: featureDir");
    if (maxentModelFilePath == null)
        throw new RuntimeException("Missing argument: maxentModel");
    if (outfilePath == null)
        throw new RuntimeException("Missing argument: outfile");

    CSVEventListReader reader = this.getReader(TrainingSetType.ALL_TEST, false);

    GenericEvents events = reader.getEvents();

    try {/*from www .  ja  v a 2 s.c  o m*/
        LOG.info("Evaluating test events...");
        ZipInputStream zis = new ZipInputStream(new FileInputStream(maxentModelFilePath));
        ZipEntry ze;
        while ((ze = zis.getNextEntry()) != null) {
            if (ze.getName().endsWith(".bin"))
                break;
        }
        MaxentModel model = new MaxentModelReader(zis).getModel();
        zis.close();

        MaxentAnalyser analyser = new MaxentAnalyser();
        analyser.setMaxentModel(model);
        if (preferredOutcome != null) {
            analyser.setPreferredOutcome(preferredOutcome);
            analyser.setBias(bias);
        }

        if (outfilePath.lastIndexOf('/') >= 0) {
            String outDirPath = outfilePath.substring(0, outfilePath.lastIndexOf('/'));

            File outDir = new File(outDirPath);
            outDir.mkdirs();
        }

        File outcomeFile = new File(outfilePath);

        if (outfilePath.endsWith(".xml")) {
            MaxentOutcomeXmlWriter xmlWriter = new MaxentOutcomeXmlWriter(outcomeFile);
            xmlWriter.setMinProbToConsider(minProbToConsider);
            xmlWriter.setUnknownOutcomeName(unknownOutcomeName);
            analyser.addObserver(xmlWriter);
        } else {
            MaxentOutcomeCsvWriter csvWriter = new MaxentOutcomeCsvWriter(model, outcomeFile);
            csvWriter.setMinProbToConsider(minProbToConsider);
            csvWriter.setUnknownOutcomeName(unknownOutcomeName);
            analyser.addObserver(csvWriter);
        }

        MaxentBestFeatureObserver bestFeatureObserver = null;
        if (!crossValidation && featureCount > 0 && resultFilePath != null) {
            bestFeatureObserver = new MaxentBestFeatureObserver(model, featureCount,
                    reader.getFeatureToFileMap());
            analyser.addObserver(bestFeatureObserver);
        }

        MaxentFScoreCalculator maxentFScoreCalculator = null;
        if (resultFilePath != null) {
            maxentFScoreCalculator = new MaxentFScoreCalculator();
            maxentFScoreCalculator.setMinProbToConsider(minProbToConsider);
            maxentFScoreCalculator.setUnknownOutcomeName(unknownOutcomeName);
            analyser.addObserver(maxentFScoreCalculator);
        }

        analyser.analyse(events);

        if (maxentFScoreCalculator != null) {
            FScoreCalculator<String> fscoreCalculator = maxentFScoreCalculator.getFscoreCalculator();

            LOG.info("F-score: " + fscoreCalculator.getTotalFScore());

            File fscoreFile = new File(outfilePath + ".fscores.csv");
            fscoreCalculator.writeScoresToCSVFile(fscoreFile);
        }

        if (bestFeatureObserver != null) {
            File weightPerFileFile = new File(outfilePath + ".weightPerFile.csv");
            weightPerFileFile.delete();
            weightPerFileFile.createNewFile();
            Writer weightPerFileWriter = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(weightPerFileFile, false), "UTF8"));
            try {
                bestFeatureObserver.writeFileTotalsToFile(weightPerFileWriter);
            } finally {
                weightPerFileWriter.flush();
                weightPerFileWriter.close();
            }

            LOG.debug("Total feature count: " + reader.getFeatures().size());
        }
    } catch (IOException ioe) {
        LogUtils.logError(LOG, ioe);
        throw new RuntimeException(ioe);
    }

    if (generateEventFile) {
        File eventFile = new File(outfilePath + ".events.txt");
        this.generateEventFile(eventFile, events);
    }
    LOG.info("#### Complete ####");
}

From source file:fr.cls.atoll.motu.api.rest.MotuRequest.java

/**
 * Excute de la requte et retourne du rsultat dans un flux. Le flux contient le fichier netcdf en
 * mode console, l'url du fichier extrait en mode url ou l'url du fichier de status en mode status (ce
 * fichier contiendra l'tat de la requte en cours : INPRGRESS ou ERROR msg_erreur ou DONE.
 * //w  w  w.j ava2s. c  o m
 * @return le flux rsultat de la requte
 * 
 * @throws MotuRequestException the motu request exception
 * @deprecated use {@link #executeV2()}
 * 
 */
@Deprecated
public InputStream execute() throws MotuRequestException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("execute() - entering");
    }

    String requestParams = null;

    try {
        requestParams = getRequestParams();
    } catch (UnsupportedEncodingException ex) {
        LOG.error("execute()", ex);

        throw new MotuRequestException("Request parameters encoding error", ex);
    }

    URL url = null;

    Map<String, String> requestExtraInfo = MotuRequest.searchUrlUserPwd(servletUrl);
    String targetUrl = servletUrl;

    if (requestExtraInfo != null) {
        targetUrl = requestExtraInfo.get(MotuRequestParametersConstant.PARAM_MODE_URL);
    }

    try {
        url = new URL(targetUrl);
    } catch (MalformedURLException ex) {
        LOG.error("execute()", ex);

        throw new MotuRequestException("Invalid url", ex);
    }

    LOG.info("URL=" + getRequestUrl());

    HttpURLConnection urlConnection;

    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(connectTimeout);
    } catch (IOException ex) {
        LOG.error("execute()", ex);

        throw new MotuRequestException("Request connection failed", ex);
    }
    try {

        // Effectue un POST Http plutt qu'un GET car le nombre de
        // paramtres peu tre important et on ne veut pas voir passer
        // le login et password dans l'url

        if (requestExtraInfo != null) {
            String user = requestExtraInfo.get(MotuRequestParametersConstant.PARAM_LOGIN);
            String pwd = requestExtraInfo.get(MotuRequestParametersConstant.PARAM_PWD);
            if ((user != null) && (pwd != null)) {
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append(user);
                stringBuffer.append(":");
                stringBuffer.append(pwd);
                byte[] encoding = new org.apache.commons.codec.binary.Base64()
                        .encode(stringBuffer.toString().getBytes());
                urlConnection.setRequestProperty("Authorization", "Basic " + new String(encoding));
            }

        }

        urlConnection.setDoOutput(true);
        Writer writer = new OutputStreamWriter(urlConnection.getOutputStream());
        try {
            writer.write(requestParams);
            writer.flush();
        } finally {
            IOUtils.closeQuietly(writer);
        }

        InputStream returnInputStream = urlConnection.getInputStream();
        if (LOG.isDebugEnabled()) {
            LOG.debug("execute() - exiting");
        }
        return returnInputStream;

    } catch (IOException ex) {
        LOG.error("execute()", ex);

        MotuRequestException motuRequestException;
        try {
            motuRequestException = new MotuRequestException("Request failed - errorCode: "
                    + urlConnection.getResponseCode() + ", errorMsg: " + urlConnection.getResponseMessage(),
                    ex);
        } catch (IOException e) {
            LOG.error("execute()", e);

            motuRequestException = new MotuRequestException("Request connection failed", ex);
        }
        throw motuRequestException;
    }

}

From source file:axiom.servlet.AbstractServletClient.java

void sendError(HttpServletResponse response, int code, String message) throws IOException {
    response.reset();//from w ww. j av  a 2  s  .  c  om
    response.setStatus(code);
    response.setContentType("text/html");

    Writer writer = response.getWriter();

    writer.write("<html><body><h3>");
    writer.write("Error in application ");
    try {
        writer.write(getApplication().getName());
    } catch (Exception besafe) {
        besafe.printStackTrace();
    }
    writer.write("</h3>");
    writer.write(message);
    writer.write("</body></html>");
    writer.flush();
}

From source file:com.ikon.util.impexp.JcrRepositoryChecker.java

/**
 * Performs a recursive repository document check
 *//*from   w w  w  . ja v a  2s . c  o  m*/
private static ImpExpStats checkDocumentsHelper(String token, Node baseNode, boolean versions, Writer out,
        InfoDecorator deco)
        throws FileNotFoundException, PathNotFoundException, AccessDeniedException, RepositoryException,
        IOException, DatabaseException, javax.jcr.PathNotFoundException, javax.jcr.RepositoryException {
    log.debug("checkDocumentsHelper({}, {}, {}, {}, {})",
            new Object[] { token, baseNode, versions, out, deco });
    ImpExpStats stats = new ImpExpStats();

    for (NodeIterator ni = baseNode.getNodes(); ni.hasNext();) {
        Node child = ni.nextNode();

        if (child.isNodeType(Document.TYPE)) {
            ImpExpStats tmp = readDocument(token, child.getPath(), versions, out, deco);
            stats.setDocuments(stats.getDocuments() + tmp.getDocuments());
            stats.setFolders(stats.getFolders() + tmp.getFolders());
            stats.setSize(stats.getSize() + tmp.getSize());
            stats.setOk(stats.isOk() && tmp.isOk());
        } else if (child.isNodeType(Folder.TYPE)) {
            ImpExpStats tmp = readFolder(token, child, versions, out, deco);
            stats.setDocuments(stats.getDocuments() + tmp.getDocuments());
            stats.setFolders(stats.getFolders() + tmp.getFolders());
            stats.setSize(stats.getSize() + tmp.getSize());
            stats.setOk(stats.isOk() && tmp.isOk());
        } else if (child.isNodeType(Mail.TYPE)) {
            ImpExpStats tmp = readFolder(token, child, versions, out, deco);
            stats.setDocuments(stats.getDocuments() + tmp.getDocuments());
            stats.setFolders(stats.getFolders() + tmp.getFolders());
            stats.setSize(stats.getSize() + tmp.getSize());
            stats.setOk(stats.isOk() && tmp.isOk());
        } else if (child.isNodeType(Note.LIST_TYPE)) {
            // Note nodes has no check procedure
        } else {
            log.error("Unknown node type: {} ({})", child.getPrimaryNodeType().getName(), child.getPath());
            stats.setOk(false);
            out.write(deco.print(child.getPath(), 0,
                    "Unknown node type: " + child.getPrimaryNodeType().getName()));
            out.flush();
        }
    }

    log.debug("checkDocumentsHelper: {}", stats);
    return stats;
}