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:com.cloudera.sqoop.cli.ToolOptions.java

@Override
public String toString() {
    StringWriter sw = new StringWriter();
    printHelp(new HelpFormatter(), new PrintWriter(sw));
    sw.flush();
    return sw.getBuffer().toString();
}

From source file:org.nuxeo.ecm.platform.ui.web.component.seam.UICellExcel.java

/**
 * Helper method for rendering a component (usually on a facescontext with a caching reponsewriter)
 *
 * @param facesContext The faces context to render to
 * @param component The component to render
 * @return The textual representation of the component
 * @throws IOException If the JSF helper class can't render the component
 *//*from   w  ww.ja v a 2 s.c  om*/
public static String cmp2String(FacesContext facesContext, UIComponent component) throws IOException {
    ResponseWriter oldResponseWriter = facesContext.getResponseWriter();
    String contentType = oldResponseWriter != null ? oldResponseWriter.getContentType() : DEFAULT_CONTENT_TYPE;
    String characterEncoding = oldResponseWriter != null ? oldResponseWriter.getCharacterEncoding()
            : DEFAULT_CHARACTER_ENCODING;
    StringWriter cacheingWriter = new StringWriter();

    // XXX: create a response writer by hand, to control html escaping of
    // iso characters
    // take default values for these confs
    Boolean scriptHiding = Boolean.FALSE;
    Boolean scriptInAttributes = Boolean.TRUE;
    // force escaping to true
    WebConfiguration.DisableUnicodeEscaping escaping = WebConfiguration.DisableUnicodeEscaping.True;
    ResponseWriter newResponseWriter = new NXHtmlResponseWriter(cacheingWriter, contentType, characterEncoding,
            scriptHiding, scriptInAttributes, escaping);
    // ResponseWriter newResponseWriter = renderKit.createResponseWriter(
    // cacheingWriter, contentType, characterEncoding);

    facesContext.setResponseWriter(newResponseWriter);
    JSF.renderChild(facesContext, component);
    if (oldResponseWriter != null) {
        facesContext.setResponseWriter(oldResponseWriter);
    }
    cacheingWriter.flush();
    cacheingWriter.close();
    return cacheingWriter.toString();
}

From source file:org.apache.tapestry5.internal.webresources.CSSMinimizer.java

@Override
protected InputStream doMinimize(StreamableResource resource) throws IOException {
    StringWriter writer = new StringWriter(1000);
    Reader reader = new InputStreamReader(resource.openStream());

    try {/*from w  w w . j  a v a 2s  . c o  m*/
        new CssCompressor(reader).compress(writer, -1);

        writer.flush();

        return IOUtils.toInputStream(writer.getBuffer());
    } finally {
        InternalUtils.close(reader);
        InternalUtils.close(writer);
    }
}

From source file:com.vmware.photon.controller.deployer.dcp.ContainersConfigTest.java

@Test
public void buildsValidConfgiuration() throws Exception {
    String path = this.getClass().getResource("/configurations").getPath();
    List<File> leafDirectories = findAllLeafDirectories(new File(path));
    for (File dir : leafDirectories) {
        File configYml = findFile(dir, "yml");
        if (configYml != null) {
            File releaseJson = findFile(dir, "release.json");
            Map<String, Object> dynamicParamters = new HashMap<>(defaultDynamicParamters);
            @SuppressWarnings("unchecked")
            Map<String, Object> d = Utils.fromJson(FileUtils.readFileToString(releaseJson), Map.class);
            dynamicParamters.putAll(d);//from  www  .j  a va2  s.c om
            MustacheFactory mustacheFactory = new DefaultMustacheFactory();
            Mustache mustache = mustacheFactory.compile(new InputStreamReader(new FileInputStream(configYml)),
                    configYml.getName());
            StringWriter stringWriter = new StringWriter();
            mustache.execute(stringWriter, dynamicParamters).flush();
            stringWriter.flush();

            // validating that the created yml file can be read
            ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
            mapper.readValue(stringWriter.toString(), Object.class);
        }
    }
}

From source file:org.springframework.boot.actuate.web.BasicErrorController.java

@RequestMapping(value = "${error.path:/error}")
@ResponseBody//from   w w  w .  j  a va  2 s. c  o m
public Map<String, Object> error(HttpServletRequest request) {
    Map<String, Object> map = new LinkedHashMap<String, Object>();
    map.put("timestamp", new Date());
    try {
        Throwable error = (Throwable) request.getAttribute("javax.servlet.error.exception");
        Object obj = request.getAttribute("javax.servlet.error.status_code");
        int status = 999;
        if (obj != null) {
            status = (Integer) obj;
            map.put(ERROR_KEY, HttpStatus.valueOf(status).getReasonPhrase());
        } else {
            map.put(ERROR_KEY, "None");
        }
        map.put("status", status);
        if (error != null) {
            while (error instanceof ServletException && error.getCause() != null) {
                error = ((ServletException) error).getCause();
            }
            map.put("exception", error.getClass().getName());
            map.put("message", error.getMessage());
            String trace = request.getParameter("trace");
            if (trace != null && !"false".equals(trace.toLowerCase())) {
                StringWriter stackTrace = new StringWriter();
                error.printStackTrace(new PrintWriter(stackTrace));
                stackTrace.flush();
                map.put("trace", stackTrace.toString());
            }
            this.logger.error(error);
        } else {
            Object message = request.getAttribute("javax.servlet.error.message");
            map.put("message", message == null ? "No message available" : message);
        }
        return map;
    } catch (Exception ex) {
        map.put(ERROR_KEY, ex.getClass().getName());
        map.put("message", ex.getMessage());
        this.logger.error(ex);
        return map;
    }
}

From source file:org.springframework.boot.ops.web.BasicErrorController.java

@RequestMapping(value = "${error.path:/error}")
@ResponseBody/*w  ww . jav  a  2 s.c om*/
public Map<String, Object> error(HttpServletRequest request) {
    Map<String, Object> map = new LinkedHashMap<String, Object>();
    map.put("timestamp", new Date());
    try {
        Throwable error = (Throwable) request.getAttribute("javax.servlet.error.exception");
        Object obj = request.getAttribute("javax.servlet.error.status_code");
        int status = 999;
        if (obj != null) {
            status = (Integer) obj;
            map.put(ERROR_KEY, HttpStatus.valueOf(status).getReasonPhrase());
        } else {
            map.put(ERROR_KEY, "None");
        }
        map.put("status", status);
        if (error != null) {
            while (error instanceof ServletException) {
                error = ((ServletException) error).getCause();
            }
            map.put("exception", error.getClass().getName());
            map.put("message", error.getMessage());
            String trace = request.getParameter("trace");
            if (trace != null && !"false".equals(trace.toLowerCase())) {
                StringWriter stackTrace = new StringWriter();
                error.printStackTrace(new PrintWriter(stackTrace));
                stackTrace.flush();
                map.put("trace", stackTrace.toString());
            }
            this.logger.error(error);
        } else {
            Object message = request.getAttribute("javax.servlet.error.message");
            map.put("message", message == null ? "No message available" : message);
        }
        return map;
    } catch (Exception ex) {
        map.put(ERROR_KEY, ex.getClass().getName());
        map.put("message", ex.getMessage());
        this.logger.error(ex);
        return map;
    }
}

From source file:org.pivot4j.state.StateSavingIT.java

@Test
public void testSaveModelSettings() throws ConfigurationException, IOException {
    PivotModel model = getPivotModel();/*from w w w  .  j  a v a2 s . c om*/
    model.setMdx(getTestQuery());
    model.initialize();

    model.setSorting(true);
    model.setTopBottomCount(3);
    model.setSortCriteria(SortCriteria.BOTTOMCOUNT);

    CellSet cellSet = model.getCellSet();
    CellSetAxis axis = cellSet.getAxes().get(Axis.COLUMNS.axisOrdinal());

    model.sort(axis, axis.getPositions().get(0));

    String mdx = model.getCurrentMdx();

    XMLConfiguration configuration = new XMLConfiguration();
    configuration.setDelimiterParsingDisabled(true);

    model.saveSettings(configuration);

    Logger logger = LoggerFactory.getLogger(getClass());
    if (logger.isDebugEnabled()) {
        StringWriter writer = new StringWriter();
        configuration.save(writer);
        writer.flush();
        writer.close();

        logger.debug("Loading report content :" + System.getProperty("line.separator"));
        logger.debug(writer.getBuffer().toString());
    }

    PivotModel newModel = new PivotModelImpl(getDataSource());
    newModel.restoreSettings(configuration);

    newModel.getCellSet();

    String newMdx = newModel.getCurrentMdx();
    if (newMdx != null) {
        // Currently the parser treats every number as double value.
        // It's inevitable now and does not impact the result.
        newMdx = newMdx.replaceAll("3\\.0", "3");
    }

    assertThat("MDX has been changed after the state restoration", newMdx, is(equalTo(mdx)));
    assertThat("RenderProperty 'sorting' has been changed after the state restoration", newModel.isSorting(),
            is(true));
    assertThat("RenderProperty 'topBottomCount' has been changed after the state restoration",
            newModel.getTopBottomCount(), is(equalTo(3)));
    assertThat("RenderProperty 'sortMode' has been changed after the state restoration",
            newModel.getSortCriteria(), is(equalTo(SortCriteria.BOTTOMCOUNT)));
}

From source file:com.eyeq.pivot4j.state.StateSavingIT.java

@Test
public void testSaveModelSettings() throws ConfigurationException, IOException {
    PivotModel model = getPivotModel();//from   ww w .  ja  v a 2  s.c  o  m
    model.setMdx(getTestQuery());
    model.initialize();

    model.setSorting(true);
    model.setTopBottomCount(3);
    model.setSortCriteria(SortCriteria.BOTTOMCOUNT);

    CellSet cellSet = model.getCellSet();
    CellSetAxis axis = cellSet.getAxes().get(Axis.COLUMNS.axisOrdinal());

    model.sort(axis, axis.getPositions().get(0));

    String mdx = model.getCurrentMdx();

    XMLConfiguration configuration = new XMLConfiguration();
    configuration.setDelimiterParsingDisabled(true);

    model.saveSettings(configuration);

    Logger logger = LoggerFactory.getLogger(getClass());
    if (logger.isDebugEnabled()) {
        StringWriter writer = new StringWriter();
        configuration.save(writer);
        writer.flush();
        writer.close();

        logger.debug("Loading report content :" + System.getProperty("line.separator"));
        logger.debug(writer.getBuffer().toString());
    }

    PivotModel newModel = new PivotModelImpl(getDataSource());
    newModel.restoreSettings(configuration);

    newModel.getCellSet();

    String newMdx = newModel.getCurrentMdx();
    if (newMdx != null) {
        // Currently the parser treats every number as double value.
        // It's inevitable now and does not impact the result.
        newMdx = newMdx.replaceAll("3\\.0", "3");
    }

    assertThat("MDX has been changed after the state restoration", newMdx, is(equalTo(mdx)));
    assertThat("Property 'sorting' has been changed after the state restoration", newModel.isSorting(),
            is(true));
    assertThat("Property 'topBottomCount' has been changed after the state restoration",
            newModel.getTopBottomCount(), is(equalTo(3)));
    assertThat("Property 'sortMode' has been changed after the state restoration", newModel.getSortCriteria(),
            is(equalTo(SortCriteria.BOTTOMCOUNT)));
}

From source file:org.jbpm.integration.ecm.FileCustomType.java

public String renderField(String fieldName, String path, String namespace, boolean showInput) {

    String str = null;/*from   w w  w . j a  va 2s . c  o m*/
    try {

        Map<String, Object> context = new HashMap<String, Object>();

        // if there is a file in the specified path, the input will show a link to download it.
        context.put("inputId", namespace + "_file_" + fieldName);
        if (path != null) {
            // path is equipped with file name to avoid additional file retrieval from storage
            String[] idElements = path.split("@");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("content", Base64.encodeBase64String(path.getBytes()));

            String downloadLink = urlMarkupGenerator.getMarkup("ecmfdch", "download", params);

            context.put("showLink", Boolean.TRUE);
            context.put("downloadLink", downloadLink);
            context.put("fileName", idElements[0]);
        } else {
            context.put("showLink", Boolean.FALSE);
        }
        // If the field is readonly or we are just showing the field value we will hide the input file.
        context.put("showInput", showInput);

        InputStream src = this.getClass().getResourceAsStream("input.ftl");
        freemarker.template.Configuration cfg = new freemarker.template.Configuration();
        BeansWrapper defaultInstance = new BeansWrapper();
        defaultInstance.setSimpleMapWrapper(true);
        cfg.setObjectWrapper(defaultInstance);
        cfg.setTemplateUpdateDelay(0);
        Template temp = new Template(fieldName, new InputStreamReader(src), cfg);
        StringWriter out = new StringWriter();
        temp.process(context, out);
        out.flush();
        str = out.getBuffer().toString();
    } catch (Exception e) {
        log.warn("Failed to process template for field '{0}': {1}", fieldName, e);
    }
    return str;
}