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:org.metamorfosis.template.directive.freemarker.AppendFileSection.java

@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) {
    log.debug("Ejecutando <@" + getDirectiveName() + " .../>");

    // Validar parametros
    if (params.isEmpty()) {
        throw new DirectiveException(msgErr);
    }/*from ww w  .j  av a2  s .  c  om*/

    if (loopVars.length != 0) {
        throw new DirectiveException("<@" + getDirectiveName() + " .../> no acepta loop variables.");
    }

    // If there is non-empty nested content:
    if (body != null) {
        try {
            // Executes the nested body. Same as <#nested> in FTL, except
            // that we use our own writer instead of the current output writer.
            String filePath = null;
            String position = null;
            String ocurrenceCount = null;
            String ocurrence = null;

            Set<Entry<String, SimpleScalar>> entrySet = params.entrySet();
            for (Entry<String, SimpleScalar> entry : entrySet) {
                String key = entry.getKey();
                SimpleScalar value = entry.getValue();
                if (key.equals(FILE_PATH)) {
                    filePath = value.getAsString();
                } else if (key.equals(POSITION)) {
                    position = value.getAsString();
                } else if (key.equals(OCURRENCE_COUNT)) {
                    ocurrenceCount = value.getAsString();
                } else if (key.equals(OCURRENCE)) {
                    ocurrence = value.getAsString();
                } else {
                    throw new DirectiveException(
                            "<@" + getDirectiveName() + " .../> no acepta el parmetro '" + key + "'");
                }
            }

            // Escribir resultado del procesamiento en un buffer
            StringWriter sw = new StringWriter();
            BufferedWriter bw = new BufferedWriter(sw);
            body.render(bw);
            env.getOut().flush();
            bw.flush();
            sw.flush();
            bw.close();
            sw.close();

            // =============================================================
            // 1. El filePath debe existir dentro del proyecto
            ExternalProject project = SpringUtils.getProject();
            File absProjectPath = project.getInProjectPath(filePath);
            if (!project.existsInProject(filePath)) {
                throw new DirectiveException("<@AppendFileSection .../> " + "No se encuentra el archivo '"
                        + absProjectPath + "', " + "se requiere que exista el filePath '" + filePath + "' "
                        + "dentro del proyecto original");
            }

            File fFilePath = project.getInProjectPath(filePath);
            String originalFileStr = FileUtils.readFileToString(fFilePath);
            AppendFileSectionLogic logic = new AppendFileSectionLogic(originalFileStr, sw.toString());
            String result = logic.process(position, ocurrenceCount, ocurrence);

            String outputFolder = FilenameUtils.getFullPath(filePath);
            String outputFileName = FilenameUtils.getName(filePath);

            TemplateProcessed tp = new TemplateProcessed(originalFileStr, outputFolder, outputFileName, result);

            // notificar a los observadores
            super.setChanged();
            super.notifyObservers(tp);

        } catch (TemplateException ex) {
            throw new DirectiveException("Error al ejecutar la directiva '" + getDirectiveName() + "'", ex);
        } catch (IOException ex) {
            throw new DirectiveException("Error al ejecutar la directiva '" + getDirectiveName() + "'", ex);
        }

    } else {
        throw new DirectiveException("<@" + getDirectiveName() + "missing body");
    }
}

From source file:de.quist.samy.remocon.RemoteSession.java

private String getTextPayload(String text) throws IOException {
    StringWriter writer = new StringWriter();
    writer.append((char) 0x01);
    writer.append((char) 0x00);
    writeBase64Text(writer, text);
    writer.flush();
    return writer.toString();
}

From source file:org.jspringbot.keyword.csv.CSVState.java

private String toCSV(List<String[]> lines) {
    StringWriter str = new StringWriter();
    CSVWriter writer = new CSVWriter(str);

    writer.writeAll(lines);/*from  ww  w  .  ja  v  a2s .  co m*/
    str.flush();

    return str.toString();
}

From source file:org.apache.sling.repoinit.parser.test.ParserTest.java

@Test
public void checkResult() throws ParseException, IOException {
    final String expected = IOUtils.toString(tc.expected, DEFAULT_ENCODING).trim();
    try {/*  w  w w . ja v  a2s. c o  m*/
        final StringWriter sw = new StringWriter();
        final OperationVisitor v = new OperationToStringVisitor(new PrintWriter(sw));
        final List<Operation> result = new RepoInitParserImpl(tc.input).parse();
        for (Operation o : result) {
            o.accept(v);
        }
        sw.flush();
        String actual = sw.toString().trim();

        // normalize line endings to ensure tests run on windows as well
        actual = actual.replaceAll("\r\n", "\n");

        assertEquals(expected, actual);
    } finally {
        tc.close();
    }
}

From source file:org.objectstyle.cayenne.query.Ordering.java

public String toString() {
    StringWriter buffer = new StringWriter();
    PrintWriter pw = new PrintWriter(buffer);
    XMLEncoder encoder = new XMLEncoder(pw);
    encodeAsXML(encoder);//from w  ww  . jav  a2  s .  c  o  m
    pw.close();
    buffer.flush();
    return buffer.toString();
}

From source file:de.fischer.thotti.core.distbuilder.DistributionBuilder.java

protected void generateRunSkript(ArchiveOutputStream os)
        throws IOException, TemplateException, AWSRessourceNotFoundException, AWSIllegalConfigurationException {
    // @todo Improve Exception handling

    AWSAccessCredentials remoteCredentials = getRemoteUsersCredentials();

    Configuration cfg = new Configuration();
    cfg.setClassForTemplateLoading(this.getClass(), "/freemarker/distribution");
    cfg.setLocalizedLookup(false);//from ww  w .ja  v  a2  s.  co m
    cfg.setObjectWrapper(new DefaultObjectWrapper());

    Map varMap = new HashMap();
    varMap.put("var_classpath", cpBuilder.toString());
    varMap.put("var_ak", remoteCredentials.getAccessKeyId());
    varMap.put("var_sk", remoteCredentials.getSecretKey());
    varMap.put("var_resultfile", NDRunner.THOTTI_RESULT_FILE);

    Template temp = null;
    temp = cfg.getTemplate("run.sh.ftl");
    StringWriter out = new StringWriter();
    temp.process(varMap, out);
    out.flush();

    String content = out.getBuffer().toString().replace("\r\n", "\n");

    String target = BASE_DIRECTORY + "/" + BIN_DIRECTORY + "/ndrunner";
    os.putArchiveEntry(new ZipArchiveEntry(target));
    IOUtils.copy(new ByteArrayInputStream(content.getBytes()), os);
    os.closeArchiveEntry();
}

From source file:com.agiletec.aps.system.common.renderer.BaseEntityRenderer.java

@Override
public String render(IApsEntity entity, String velocityTemplate, String langCode,
        boolean convertSpecialCharacters) {
    String renderedEntity = null;
    List<TextAttributeCharReplaceInfo> conversions = null;
    try {/*ww w.j av a  2s  .c  om*/
        if (convertSpecialCharacters) {
            conversions = this.convertSpecialCharacters(entity, langCode);
        }
        Context velocityContext = new VelocityContext();
        EntityWrapper entityWrapper = this.getEntityWrapper(entity);
        entityWrapper.setRenderingLang(langCode);
        velocityContext.put(this.getEntityWrapperContextName(), entityWrapper);

        I18nManagerWrapper i18nWrapper = new I18nManagerWrapper(langCode, this.getI18nManager());
        velocityContext.put("i18n", i18nWrapper);
        StringWriter stringWriter = new StringWriter();
        boolean isEvaluated = Velocity.evaluate(velocityContext, stringWriter, "render", velocityTemplate);
        if (!isEvaluated) {
            throw new ApsSystemException("Rendering error");
        }
        stringWriter.flush();
        renderedEntity = stringWriter.toString();
    } catch (Throwable t) {
        _logger.error("Rendering error. entity {}", entity.getTypeCode(), t);
        //ApsSystemUtils.logThrowable(t, this, "render", "Rendering error");
        renderedEntity = "";
    } finally {
        if (convertSpecialCharacters && null != conversions) {
            this.replaceSpecialCharacters(conversions);
        }
    }
    return renderedEntity;
}

From source file:de.dennishoersch.web.css.parser.ParserTest.java

@Test
public void testCompressRulesSimple() throws Exception {

    StringWriter merged = new StringWriter();

    String css = getFileContent("simpleTest.css");

    Stylesheet stylesheet = Parser.parse(css);

    for (Rule rule : stylesheet.getRules()) {
        IOUtils.write(rule.toString() + "\n", merged);
    }/*from  www. j ava  2  s .c  om*/

    merged.flush();
    merged.close();

    //        System.out.println();
    //        System.out.println(merged);
    //        System.out.println();

    // The overriding removes the 'yellow' definition
    assertThat(merged.toString(), not(containsString("yellow")));

    // Vendor prefixes in values do not override
    assertThat(merged.toString(), containsString("-moz"));
    assertThat(merged.toString(), containsString("-webkit"));

    // was ist besser oder effizienter?

    // .paddingAll, .paddingWithMarginTop {padding: 20px;}
    // .paddingWithMarginTop {margin-top: 10px;}

    // vs:
    // .paddingAll{padding:20px;}
    // .paddingWithMarginTop{padding:20px;margin-top:10px;}
}

From source file:org.unitime.timetable.tags.Registration.java

private synchronized void init() {
    sLastRefresh = System.currentTimeMillis();
    try {//w  w w .  j  a v a 2s  . com
        File regFile = new File(ApplicationProperties.getDataFolder(), "unitime.reg");
        if (sKey == null && regFile.exists()) {
            Properties reg = new Properties();
            FileInputStream in = new FileInputStream(regFile);
            try {
                reg.load(in);
            } finally {
                in.close();
            }
            sKey = reg.getProperty("key");
        }

        HashMap<String, String> registration = new HashMap<String, String>();
        if (sKey != null)
            registration.put("key", sKey);
        else
            sLog.debug("No registration key found...");
        registration.put("version", Constants.getVersion());
        registration.put("sessions", String.valueOf(QueryLog.getNrSessions(31)));
        registration.put("users", String.valueOf(QueryLog.getNrActiveUsers(31)));
        registration.put("url",
                pageContext.getRequest().getScheme() + "://" + pageContext.getRequest().getServerName() + ":"
                        + pageContext.getRequest().getServerPort()
                        + ((HttpServletRequest) pageContext.getRequest()).getContextPath());
        sLog.debug("Sending the following registration info: " + registration);

        Document input = DocumentHelper.createDocument();
        Element regEl = input.addElement("registration");
        for (Map.Entry<String, String> entry : registration.entrySet()) {
            regEl.addElement(entry.getKey()).setText(entry.getValue());
        }

        sLog.debug("Contacting registration service...");
        ClientResource cr = new ClientResource("http://register.unitime.org/xml");

        StringWriter w = new StringWriter();
        new XMLWriter(w, OutputFormat.createPrettyPrint()).write(input);
        w.flush();
        w.close();

        String result = cr.post(w.toString(), String.class);
        sLog.info("Registration information received.");

        try {
            cr.release();
        } catch (Exception e) {
        }

        StringReader r = new StringReader(result);
        Document output = (new SAXReader()).read(r);
        r.close();

        HashMap<String, String> ret = new HashMap<String, String>();
        for (Element e : (List<Element>) output.getRootElement().elements()) {
            ret.put(e.getName(), e.getText());
        }

        String newKey = ret.get("key");
        if (!newKey.equals(sKey)) {
            sKey = newKey;
            sLog.debug("New registration key received...");
            Properties reg = new Properties();
            reg.setProperty("key", sKey);
            FileOutputStream out = new FileOutputStream(regFile);
            try {
                reg.store(out,
                        "UniTime " + Constants.VERSION + " registration file, please do not delete or modify.");
                out.flush();
            } finally {
                out.close();
            }
        }

        sMessage = ret.get("message");
        sNote = ret.get("note");
        sRegistered = "1".equals(ret.get("registered"));
    } catch (Exception e) {
        sLog.error("Validation failed: " + e.getMessage(), e);
    }
}

From source file:io.fabric8.vertx.maven.plugin.SetupMojoTest.java

@Test
public void testAddVertxMavenPlugin() throws Exception {
    InputStream pomFile = getClass().getResourceAsStream("/unit/setup/vmp-setup-pom.xml");
    assertNotNull(pomFile);// w  w w  .  j a  v a 2s .c om
    MavenXpp3Reader xpp3Reader = new MavenXpp3Reader();
    Model model = xpp3Reader.read(pomFile);

    MavenProject project = new MavenProject(model);

    Optional<Plugin> vmPlugin = MojoUtils.hasPlugin(project, "io.fabric8:vertx-maven-plugin");
    assertFalse(vmPlugin.isPresent());

    Plugin vertxMavenPlugin = plugin("io.fabric8", "vertx-maven-plugin",
            MojoUtils.getVersion("vertx-maven-plugin-version"));

    PluginExecution pluginExec = new PluginExecution();
    pluginExec.addGoal("initialize");
    pluginExec.addGoal("package");
    pluginExec.setId("vmp-init-package");
    vertxMavenPlugin.addExecution(pluginExec);

    vertxMavenPlugin.setConfiguration(configuration(element("redeploy", "true")));

    model.getBuild().getPlugins().add(vertxMavenPlugin);

    model.getProperties().putIfAbsent("vertx.version", MojoUtils.getVersion("vertx-core-version"));

    Dependency vertxBom = dependency("io.vertx", "vertx-dependencies", "${vertx.version}");
    vertxBom.setType("pom");
    vertxBom.setScope("import");

    addDependencies(model, vertxBom);

    MavenXpp3Writer xpp3Writer = new MavenXpp3Writer();
    StringWriter updatedPom = new StringWriter();

    xpp3Writer.write(updatedPom, model);
    updatedPom.flush();
    updatedPom.close();

    //System.out.println(updatedPom);

    //Check if it has been added

    model = xpp3Reader.read(new StringReader(updatedPom.toString()));
    project = new MavenProject(model);
    vmPlugin = MojoUtils.hasPlugin(project, "io.fabric8:vertx-maven-plugin");
    assertTrue(vmPlugin.isPresent());
    Plugin vmp = project.getPlugin("io.fabric8:vertx-maven-plugin");
    assertNotNull(vmp);
    Xpp3Dom pluginConfig = (Xpp3Dom) vmp.getConfiguration();
    assertNotNull(pluginConfig);
    String redeploy = pluginConfig.getChild("redeploy").getValue();
    assertNotNull(redeploy);
    assertTrue(Boolean.valueOf(redeploy));
}