Example usage for java.io StringWriter close

List of usage examples for java.io StringWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closing a StringWriter has no effect.

Usage

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

private synchronized void init() {
    sLastRefresh = System.currentTimeMillis();
    try {// w  w w.  j  a va  2s .c o  m
        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: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);
    }/*w  w w  .  java  2 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:org.eurekastreams.server.service.restlets.ActionResource.java

/**
 * GET the activites.//from  w  ww . j  a  v  a2  s  .c  o m
 *
 * @param variant
 *            the variant.
 * @return the JSON.
 * @throws ResourceException
 *             the exception.
 */
@SuppressWarnings("unchecked")
@Override
public Representation represent(final Variant variant) throws ResourceException {
    String jsString = "";

    try {
        // get the action
        Object springBean = applicationContextHolder.getContext().getBean(actionKey);

        // get parameter
        Serializable actionParameter = getRequestObject();

        // create ServiceActionContext.
        PrincipalActionContext actionContext = new ClientPrincipalActionContextImpl(actionParameter, principal,
                clientUniqueId);
        actionContext.setActionId(actionKey);

        log.debug("executing action: " + actionKey + " for user: " + principal.getAccountId());

        Serializable result = "empty result";
        if (springBean instanceof ServiceAction) {
            ServiceAction action = (ServiceAction) springBean;
            if (readOnly && !action.isReadOnly()) {
                throw new IllegalStateException("Action requested is not read-only.");
            }
            result = serviceActionController.execute(actionContext, action);
        } else if (springBean instanceof TaskHandlerServiceAction) {
            TaskHandlerServiceAction action = (TaskHandlerServiceAction) springBean;
            if (readOnly && !action.isReadOnly()) {
                throw new IllegalStateException("Action requested is not read-only.");
            }
            result = serviceActionController.execute(actionContext, action);
        }

        StringWriter writer = new StringWriter();
        JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(writer);
        jsonGenerator.writeObject(result);
        writer.close();

        jsString = writer.toString();
    } catch (Exception ex) {
        log.error("Error excecuting action " + actionKey + " from restlet.", ex);
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Error executing action.");
    }

    Representation rep = new StringRepresentation(jsString, MediaType.TEXT_PLAIN);
    rep.setExpirationDate(new Date(0L));
    return rep;
}

From source file:org.easyrec.service.core.impl.ProfileServiceImpl.java

/**
 * Used//  w  w  w .ja v  a 2 s . c  o  m
 * @param tenantId
 * @param itemId
 * @param itemType
 * @param deleteXPath
 * @throws Exception
 *
 */
@Override
public boolean deleteProfileField(Integer tenantId, String itemId, String itemType, String deleteXPath)
        throws Exception {

    XPathFactory xpf = XPathFactory.newInstance();

    // load and parse the profile
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new InputSource(new StringReader(getProfile(tenantId, itemId, itemType))));

    // check if the element exists
    XPath xp = xpf.newXPath();
    NodeList nodeList = (NodeList) xp.evaluate(deleteXPath, doc, XPathConstants.NODESET);

    if (nodeList.getLength() == 0)
        throw new FieldNotFoundException("Field does not exist in this profile!");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        node.getParentNode().removeChild(node);
    }

    StringWriter writer = new StringWriter();
    Result result = new StreamResult(writer);
    trans.transform(new DOMSource(doc), result);
    writer.close();
    String xml = writer.toString();
    logger.debug(xml);
    storeProfile(tenantId, itemId, itemType, xml);

    return true;
}

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);//from   w w w  .  j  a  va  2 s  .  com
    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));
}

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

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

    MavenProject project = new MavenProject(model);

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

    Plugin vertxMavenPlugin = plugin("io.reactiverse", "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.reactiverse:vertx-maven-plugin");
    assertTrue(vmPlugin.isPresent());
    Plugin vmp = project.getPlugin("io.reactiverse:vertx-maven-plugin");
    assertNotNull(vmp);
    Xpp3Dom pluginConfig = (Xpp3Dom) vmp.getConfiguration();
    assertNotNull(pluginConfig);
    String redeploy = pluginConfig.getChild("redeploy").getValue();
    assertNotNull(redeploy);
    assertTrue(Boolean.valueOf(redeploy));
}

From source file:com.cloudera.lib.service.instrumentation.TestInstrumentationService.java

@Test
public void variableHolder() throws Exception {
    InstrumentationService.VariableHolder<String> variableHolder = new InstrumentationService.VariableHolder<String>();

    variableHolder.var = new Instrumentation.Variable<String>() {
        @Override//from  w  w  w . j a v a 2 s . com
        public String getValue() {
            return "foo";
        }
    };

    JSONObject json = (JSONObject) new JSONParser().parse(variableHolder.toJSONString());
    Assert.assertEquals(json.size(), 1);
    Assert.assertEquals(json.get("value"), "foo");

    StringWriter writer = new StringWriter();
    variableHolder.writeJSONString(writer);
    writer.close();
    json = (JSONObject) new JSONParser().parse(writer.toString());
    Assert.assertEquals(json.size(), 1);
    Assert.assertEquals(json.get("value"), "foo");
}

From source file:com.jf.javafx.plugins.impl.PluginRepositoryImpl.java

private String getConfigInString(XMLConfiguration cfg) {
    StringWriter sw = new StringWriter();
    String result = "";
    try {/*ww w .  j  a v  a 2  s  . com*/
        cfg.save(sw);
        result = sw.toString();
    } catch (ConfigurationException ex) {
        // do nothing
    }
    try {
        sw.close();
    } catch (IOException ex) {
        Logger.getLogger(PluginRepositoryImpl.class.getName()).log(Level.INFO, null, ex);
    }

    return result;
}

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

@Test
public void testAddVertxMavenPluginWithNoBuildPom() throws Exception {
    InputStream pomFile = getClass().getResourceAsStream("/unit/setup/vmp-setup-nobuild-pom.xml");
    assertNotNull(pomFile);//from  www.  ja v a2  s  . 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")));

    Build build = new Build();
    model.setBuild(build);
    build.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));
}

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

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

    MavenProject project = new MavenProject(model);

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

    Plugin vertxMavenPlugin = plugin("io.reactiverse", "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")));

    Build build = new Build();
    model.setBuild(build);
    build.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.reactiverse:vertx-maven-plugin");
    assertTrue(vmPlugin.isPresent());
    Plugin vmp = project.getPlugin("io.reactiverse:vertx-maven-plugin");
    assertNotNull(vmp);
    Xpp3Dom pluginConfig = (Xpp3Dom) vmp.getConfiguration();
    assertNotNull(pluginConfig);
    String redeploy = pluginConfig.getChild("redeploy").getValue();
    assertNotNull(redeploy);
    assertTrue(Boolean.valueOf(redeploy));
}