Example usage for java.io StringWriter flush

List of usage examples for java.io StringWriter flush

Introduction

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

Prototype

public void flush() 

Source Link

Document

Flush the stream.

Usage

From source file:gtu._work.ui.SqlCreaterUI.java

private void executeBtnPreformed() {
    try {//  w  w w .  j a v a  2  s .  c  om
        logArea.setText("");
        File srcFile = JCommonUtil.filePathCheck(excelFilePathText.getText(), "?", false);
        if (srcFile == null) {
            return;
        }
        if (!srcFile.getName().endsWith(".xlsx")) {
            JCommonUtil._jOptionPane_showMessageDialog_error("excel");
            return;
        }
        if (StringUtils.isBlank(sqlArea.getText())) {
            return;
        }
        File saveFile = JCommonUtil._jFileChooser_selectFileOnly_saveFile();
        if (saveFile == null) {
            JCommonUtil._jOptionPane_showMessageDialog_error("?");
            return;
        }

        String sqlText = sqlArea.getText();

        StringBuffer sb = new StringBuffer();
        Map<Integer, String> refMap = new HashMap<Integer, String>();
        Pattern sqlPattern = Pattern.compile("\\$\\{(\\w+)\\}", Pattern.MULTILINE);
        Matcher matcher = sqlPattern.matcher(sqlText);
        while (matcher.find()) {
            String val = StringUtils.trim(matcher.group(1)).toUpperCase();
            refMap.put(ExcelUtil.cellEnglishToPos(val), val);
            matcher.appendReplacement(sb, "\\$\\{" + val + "\\}");
        }
        matcher.appendTail(sb);
        appendLog(refMap.toString());

        sqlText = sb.toString();
        sqlArea.setText(sqlText);

        Configuration cfg = new Configuration();
        StringTemplateLoader stringTemplatge = new StringTemplateLoader();
        stringTemplatge.putTemplate("aaa", sqlText);
        cfg.setTemplateLoader(stringTemplatge);
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        Template temp = cfg.getTemplate("aaa");

        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(saveFile), "utf8"));

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(bis);
        Sheet sheet = xssfWorkbook.getSheetAt(0);
        for (int j = 0; j < sheet.getPhysicalNumberOfRows(); j++) {
            Row row = sheet.getRow(j);
            if (row == null) {
                continue;
            }
            Map<String, Object> root = new HashMap<String, Object>();
            for (int index : refMap.keySet()) {
                root.put(refMap.get(index), formatCellType(row.getCell(index)));
            }
            appendLog(root.toString());

            StringWriter out = new StringWriter();
            temp.process(root, out);
            out.flush();
            String writeStr = out.getBuffer().toString();
            appendLog(writeStr);

            writer.write(writeStr);
            writer.newLine();
        }
        bis.close();

        writer.flush();
        writer.close();

        JCommonUtil._jOptionPane_showMessageDialog_info("? : \n" + saveFile);
    } catch (Exception ex) {
        JCommonUtil.handleException(ex);
    }
}

From source file:net.lightbody.bmp.proxy.jetty.html.Element.java

/** Convert Element to String.
 * Uses write() to convert the HTML Element to a string.
 * @return String of the HTML element//from  w  ww  .  j av a  2  s  .  c  om
 */
public String toString() {
    try {
        StringWriter out = new StringWriter();
        write(out);
        out.flush();
        return out.toString();
    } catch (IOException e) {
        LogSupport.ignore(log, e);
    }
    return null;
}

From source file:de.thischwa.pmcms.view.renderer.VelocityRenderer.java

/**
 * Renders an {@link IRenderable} with respect of the {@link ViewMode} and possible context objects into <code>writer</code>.
 * //from   w w  w . j  a  v  a2  s.  c om
 * @param writer
 *            Contains the rendered string. It has to be flushed and closed by the caller!
 * @param renderable
 *            The {@link IRenderable} to render.
 * @param viewMode
 *            The {@link ViewMode} to respect.
 * @param additionalContextObjects
 *            Contains the context objects. It could be null or empty.
 * @throws RenderingException 
 */
public void render(Writer writer, final IRenderable renderable, final ViewMode viewMode,
        final Map<String, Object> additionalContextObjects) throws RenderingException {
    logger.debug("Try to render: " + renderable);
    PojoHelper pojoHelper = new PojoHelper();
    pojoHelper.putpo((APoormansObject<?>) renderable);
    Site site = pojoHelper.getSite();
    Map<String, Object> contextObjects = ContextObjectManager.get(pojoHelper, viewMode);
    if (logger.isDebugEnabled()) {
        logger.debug("context objects:");
        for (String objName : contextObjects.keySet()) {
            logger.debug(" - Object class: " + objName + " - " + contextObjects.get(objName).getClass());
        }
    }
    if (additionalContextObjects != null && !additionalContextObjects.isEmpty())
        contextObjects.putAll(additionalContextObjects);
    try {
        String templateContent = PoInfo.getTemplateContent(renderable);
        StringWriter contentWriter = new StringWriter();
        renderString(contentWriter, templateContent, contextObjects);

        String layoutContent = site.getLayoutTemplate().getText();
        if (layoutContent != null) {
            contentWriter.flush();
            contextObjects.put("content", contentWriter.toString());
            renderString(writer, layoutContent, contextObjects);
        } else
            writer.write(contentWriter.toString());
    } catch (IOException e) {
        throw new RenderingException(e);
    }
}

From source file:org.apache.ode.utils.DOMUtils.java

/**
 * Convert a DOM node to a stringified XML representation.
 *//*from w w w. jav a2  s .co m*/
static public String domToString(Node node) {
    if (node == null) {
        throw new IllegalArgumentException("Cannot stringify null Node!");
    }

    String value = null;
    short nodeType = node.getNodeType();
    if (nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE
            || nodeType == Node.DOCUMENT_FRAGMENT_NODE) {
        // serializer doesn't handle Node type well, only Element
        DOMSerializerImpl ser = new DOMSerializerImpl();
        ser.setParameter(Constants.DOM_NAMESPACES, Boolean.TRUE);
        ser.setParameter(Constants.DOM_WELLFORMED, Boolean.FALSE);
        ser.setParameter(Constants.DOM_VALIDATE, Boolean.FALSE);

        // create a proper XML encoding header based on the input document;
        // default to UTF-8 if the parent document's encoding is not accessible
        String usedEncoding = "UTF-8";
        Document parent = node.getOwnerDocument();
        if (parent != null) {
            String parentEncoding = parent.getXmlEncoding();
            if (parentEncoding != null) {
                usedEncoding = parentEncoding;
            }
        }

        // the receiver of the DOM
        DOMOutputImpl out = new DOMOutputImpl();
        out.setEncoding(usedEncoding);

        // we write into a String
        StringWriter writer = new StringWriter(4096);
        out.setCharacterStream(writer);

        // out, ye characters!
        ser.write(node, out);
        writer.flush();

        // finally get the String
        value = writer.toString();
    } else {
        value = node.getNodeValue();
    }
    return value;
}

From source file:com.joliciel.jochre.search.highlight.Snippet.java

public String toJson() {
    try {//from   www.  ja  v  a 2  s  .  com
        DecimalFormatSymbols enSymbols = new DecimalFormatSymbols(Locale.US);
        DecimalFormat df = new DecimalFormat("0.00", enSymbols);
        StringWriter writer = new StringWriter();
        JsonFactory jsonFactory = new JsonFactory();
        JsonGenerator jsonGen = jsonFactory.createGenerator(writer);
        this.toJson(jsonGen, df);
        writer.flush();
        String json = writer.toString();
        return json;
    } catch (IOException ioe) {
        LogUtils.logError(LOG, ioe);
        throw new RuntimeException(ioe);
    }
}

From source file:ubc.pavlab.aspiredb.server.util.JSONUtil.java

/**
 * Converts a collection of objects to a json string
 * /*w  w w .j  av  a 2s . co m*/
 * @param collection
 * @return
 * @throws JSONException
 */
public String collectionToJson(Collection<?> collection) throws JSONException {
    StringWriter jsonText = new StringWriter();
    jsonText.write("[");

    try {
        Iterator<?> it = collection.iterator();
        while (it.hasNext()) {
            Object obj = it.next();
            String delim = it.hasNext() ? "," : "";
            jsonText.append(new JSONObject(obj).toString() + delim);
        }
        jsonText.append("]");
        jsonText.flush();
    } catch (Exception e) {
        log.error(e.getLocalizedMessage(), e);
        JSONObject json = new JSONObject();
        json.put("success", false);
        json.put("message", e.getLocalizedMessage());
        jsonText.write(json.toString());
        log.info(jsonText);
    }

    try {
        jsonText.close();
    } catch (Exception e) {
        log.error(e.getLocalizedMessage(), e);
        JSONObject json = new JSONObject();
        json.put("success", false);
        json.put("message", e.getLocalizedMessage());
        jsonText.write(json.toString());
        log.info(jsonText);
    }

    return jsonText.toString();
}

From source file:org.gbif.occurrence.download.service.DownloadRequestServiceImpl.java

@Override
public String create(DownloadRequest request) {
    LOG.debug("Trying to create download from request [{}]", request);
    Preconditions.checkNotNull(request);

    HiveQueryVisitor hiveVisitor = new HiveQueryVisitor();
    SolrQueryVisitor solrVisitor = new SolrQueryVisitor();
    String hiveQuery;/* w  w  w  .  jav a2s .c  o m*/
    String solrQuery;
    try {
        hiveQuery = StringEscapeUtils.escapeXml(hiveVisitor.getHiveQuery(request.getPredicate()));
        solrQuery = solrVisitor.getQuery(request.getPredicate());
    } catch (QueryBuildingException e) {
        throw new ServiceUnavailableException("Error building the hive query, attempting to continue", e);
    }
    LOG.debug("Attempting to download with hive query [{}]", hiveQuery);

    final String uniqueId = REPL_INVALID_HIVE_CHARS
            .removeFrom(request.getCreator() + '_' + UUID.randomUUID().toString());
    final String tmpTable = "download_tmp_" + uniqueId;
    final String citationTable = "download_tmp_citation_" + uniqueId;

    Properties jobProps = new Properties();
    jobProps.putAll(defaultProperties);
    jobProps.setProperty("select_interpreted", HIVE_SELECT_INTERPRETED);
    jobProps.setProperty("select_verbatim", HIVE_SELECT_VERBATIM);
    jobProps.setProperty("query", hiveQuery);
    jobProps.setProperty("solr_query", solrQuery);
    jobProps.setProperty("query_result_table", tmpTable);
    jobProps.setProperty("citation_table", citationTable);
    // we dont have a downloadId yet, submit a placeholder
    jobProps.setProperty("download_link", downloadLink(wsUrl, DownloadUtils.DOWNLOAD_ID_PLACEHOLDER));
    jobProps.setProperty(Constants.USER_PROPERTY, request.getCreator());
    if (request.getNotificationAddresses() != null && !request.getNotificationAddresses().isEmpty()) {
        jobProps.setProperty(Constants.NOTIFICATION_PROPERTY,
                EMAIL_JOINER.join(request.getNotificationAddresses()));
    }
    // serialize the predicate filter into json
    StringWriter writer = new StringWriter();
    try {
        mapper.writeValue(writer, request.getPredicate());
        writer.flush();
        jobProps.setProperty(Constants.FILTER_PROPERTY, writer.toString());
    } catch (IOException e) {
        throw new ServiceUnavailableException("Failed to serialize download filter " + request.getPredicate(),
                e);
    }

    LOG.debug("job properties: {}", jobProps);

    try {
        final String jobId = client.run(jobProps);
        LOG.debug("oozie job id is: [{}], with tmpTable [{}]", jobId, tmpTable);
        String downloadId = DownloadUtils.workflowToDownloadId(jobId);
        persistDownload(request, downloadId);
        return downloadId;
    } catch (OozieClientException e) {
        throw new ServiceUnavailableException("Failed to create download job", e);
    }
}

From source file:org.bibsonomy.scraper.url.kde.blackwell.BlackwellSynergyScraper.java

/** FIXME: refactor
 * Extract the content of a scitation.aip.org page.
 * (changed code from ScrapingContext.getContentAsString)
 * @param urlConn Connection to api page (from url.openConnection())
 * @param cookie Cookie for auth./*  ww  w. ja v a  2  s .com*/
 * @return Content of aip page.
 * @throws IOException
 */
private String getPageContent(HttpURLConnection urlConn, String cookie) throws IOException {

    urlConn.setAllowUserInteraction(true);
    urlConn.setDoInput(true);
    urlConn.setDoOutput(false);
    urlConn.setUseCaches(false);
    urlConn.setFollowRedirects(true);
    urlConn.setInstanceFollowRedirects(false);
    urlConn.setRequestProperty("Cookie", cookie);

    urlConn.setRequestProperty("User-Agent",
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)");
    urlConn.connect();

    // build content
    StringWriter out = new StringWriter();
    InputStream in = new BufferedInputStream(urlConn.getInputStream());
    int b;
    while ((b = in.read()) >= 0) {
        out.write(b);
    }

    urlConn.disconnect();
    in.close();
    out.flush();
    out.close();

    return out.toString();
}

From source file:org.nuxeo.elasticsearch.commands.IndexingCommand.java

public String toJSON() throws IOException {
    StringWriter out = new StringWriter();
    JsonFactory factory = new JsonFactory();
    JsonGenerator jsonGen = factory.createJsonGenerator(out);
    toJSON(jsonGen);/*from  w  w  w.ja v  a  2s.c o m*/
    out.flush();
    jsonGen.close();
    return out.toString();
}

From source file:org.apache.olingo.client.core.op.AbstractODataBinder.java

@Override
public ODataEntitySet getODataEntitySet(final Feed resource, final URI defaultBaseURI) {
    if (LOG.isDebugEnabled()) {
        final StringWriter writer = new StringWriter();
        client.getSerializer().feed(resource, writer);
        writer.flush();
        LOG.debug("Feed -> ODataEntitySet:\n{}", writer.toString());
    }//from  ww w. jav  a  2s .  c  o  m

    final URI base = defaultBaseURI == null ? resource.getBaseURI() : defaultBaseURI;

    final URI next = resource.getNext();

    final ODataEntitySet entitySet = next == null ? client.getObjectFactory().newEntitySet()
            : client.getObjectFactory().newEntitySet(URIUtils.getURI(base, next.toASCIIString()));

    if (resource.getCount() != null) {
        entitySet.setCount(resource.getCount());
    }

    for (Entry entryResource : resource.getEntries()) {
        entitySet.addEntity(getODataEntity(entryResource));
    }

    return entitySet;
}