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.dia.kafka.isatools.producer.ISAToolsKafkaProducer.java

/**
 * Performs the parsing request to Tika/*  w  w  w.  j  a va2 s. c  o  m*/
 *
 * @param files
 * @return
 */
public static List<JSONObject> doTikaRequest(List<String> files) {
    List<JSONObject> jsonObjs = new ArrayList<JSONObject>();

    try {
        Parser parser = new ISArchiveParser();
        StringWriter strWriter = new StringWriter();

        for (String file : files) {
            JSONObject jsonObject = new JSONObject();

            // get metadata from tika
            InputStream stream = TikaInputStream.get(new File(file));
            ContentHandler handler = new ToHTMLContentHandler();
            Metadata metadata = new Metadata();
            ParseContext context = new ParseContext();
            parser.parse(stream, handler, metadata, context);

            // get json object
            jsonObject.put(SOURCE_TAG, ISATOOLS_SOURCE_VAL);
            JsonMetadata.toJson(metadata, strWriter);
            jsonObject = adjustUnifiedSchema((JSONObject) jsonParser.parse(new String(strWriter.toString())));
            //TODO Tika parsed content is not used needed for now
            //jsonObject.put(X_TIKA_CONTENT, handler.toString());
            System.out.format("[%s] Tika message: %s \n", ISAToolsKafkaProducer.class.getSimpleName(),
                    jsonObject.toJSONString());

            jsonObjs.add(jsonObject);

            strWriter.getBuffer().setLength(0);
        }
        strWriter.flush();
        strWriter.close();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (TikaException e) {
        e.printStackTrace();
    }
    return jsonObjs;
}

From source file:com.nebhale.cyclinglibrary.web.json.AbstractJsonSerializerTest.java

@Test
public final void test() throws IOException, ParseException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new SimpleModule().addSerializer(new LinkJsonSerializer()));

    T value = getValue();//from www.j  a v a 2 s  .  c  om
    StringWriter out = new StringWriter();
    JsonGenerator jsonGenerator = objectMapper.getFactory().createJsonGenerator(out);
    SerializerProvider serializerProvider = objectMapper.getSerializerProvider();

    try {
        getJsonSerializer().serialize(value, jsonGenerator, serializerProvider);
        jsonGenerator.flush();
        assertResult(out.toString());
    } finally {
        out.close();
        jsonGenerator.close();
    }
}

From source file:org.easyrec.service.domain.profile.impl.ProfileServiceImpl.java

public void insertOrUpdateSimpleDimension(Integer tenantId, Integer itemId, String itemTypeId,
        String dimensionXPath, String value) {

    XPathFactory xpf = XPathFactory.newInstance();
    try {/*from   ww w .j  a v a 2  s .com*/
        // load and parse the profile
        DocumentBuilder db = validationParsers.get(tenantId).get(itemTypeId);
        Document doc = db.parse(new InputSource(new StringReader(getProfile(tenantId, itemId, itemTypeId))));
        // check if the element exists
        XPath xp = xpf.newXPath();
        Node node = (Node) xp.evaluate(dimensionXPath, doc, XPathConstants.NODE);
        // if the element exists, just update the value
        if (node != null) {
            // if value doesn't change, there is no need to alter the profile and write it to database
            if (value.equals(node.getTextContent()))
                return;
            node.setTextContent(value);
        } else { // if the element cannot be found, insert it at the position given in the dimensionXPath
            // follow the XPath from bottom to top until you find the first existing path element
            String tmpPath = dimensionXPath;
            while (node == null) {
                tmpPath = dimensionXPath.substring(0, tmpPath.lastIndexOf("/"));
                node = (Node) xp.evaluate(tmpPath, doc, XPathConstants.NODE);
            }
            // found the correct node to insert or ended at Document root, hence insert
            insertElement(doc, node, dimensionXPath.substring(tmpPath.length()/*, dimensionXPath.length()*/),
                    value);
        }

        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, itemTypeId, xml, true);

    } catch (Exception e) {
        logger.error("Error inserting Simple Dimension: " + e.getMessage());
        e.printStackTrace();
    }

}

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

/**
 * Used//from w w w. java2  s.c om
 * @param tenantId
 * @param itemId
 * @param itemTypeId
 * @param dimensionXPath
 * @param value
 *
 */
@Override
public synchronized boolean storeProfileField(Integer tenantId, String itemId, String itemTypeId,
        String dimensionXPath, String value) throws Exception {

    int itemIntID = idMappingDAO.lookup(itemId);

    XPathFactory xpf = XPathFactory.newInstance();

    // load and parse the profile
    Document doc = getProfileXMLDocument(tenantId, itemIntID, itemTypeId);

    // follow the XPath from bottom to top until you find the first existing path element
    XPath xp = xpf.newXPath();
    String tmpPath = dimensionXPath;
    NodeList nodeList = (NodeList) xp.evaluate(tmpPath, doc, XPathConstants.NODESET);
    if (nodeList.getLength() > 1)
        throw new MultipleProfileFieldsFoundException(nodeList.getLength() + " nodes found.");

    Node node = null;
    if (nodeList.getLength() == 1)
        nodeList.item(0).setTextContent(value);
    else {
        while (node == null) {
            tmpPath = dimensionXPath.substring(0, tmpPath.lastIndexOf("/"));
            if ("".equals(tmpPath))
                tmpPath = "/";
            node = (Node) xp.evaluate(tmpPath, doc, XPathConstants.NODE);
        }
        insertElement(doc, node, dimensionXPath.substring(tmpPath.length()), value);
    }

    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, itemTypeId, xml);

    return true;
}

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

@Test
public void testAddVertxMavenPluginWithVertxVersion() throws Exception {

    System.setProperty("vertxVersion", "3.4.0");

    InputStream pomFile = getClass().getResourceAsStream("/unit/setup/vmp-setup-pom.xml");
    assertNotNull(pomFile);/*from  ww  w .  ja va 2  s .c o m*/
    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);

    String vertxVersion = System.getProperty("vertxVersion") == null
            ? MojoUtils.getVersion("vertx-core-version")
            : System.getProperty("vertxVersion");

    model.getProperties().putIfAbsent("vertx.version", vertxVersion);

    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));
    Properties projectProps = project.getProperties();
    assertNotNull(projectProps);
    assertFalse(projectProps.isEmpty());
    assertEquals(projectProps.getProperty("vertx.version"), vertxVersion);
}

From source file:org.eclipse.packagedrone.utils.deb.build.DebianPackageWriter.java

protected ContentProvider createConfFilesContent() throws IOException {
    if (this.confFiles.isEmpty()) {
        return ContentProvider.NULL_CONTENT;
    }//www.  j  a  v a  2 s . co m

    final StringWriter sw = new StringWriter();

    for (final String confFile : this.confFiles) {
        sw.append(confFile).append('\n');
    }

    sw.close();
    return new StaticContentProvider(sw.toString());
}

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

@Test
public void testAddVertxMavenPluginWithVertxVersion() throws Exception {

    System.setProperty("vertxVersion", "3.4.0");

    InputStream pomFile = getClass().getResourceAsStream("/unit/setup/vmp-setup-pom.xml");
    assertNotNull(pomFile);/*from w w w  .j a v a 2 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);

    String vertxVersion = System.getProperty("vertxVersion") == null
            ? MojoUtils.getVersion("vertx-core-version")
            : System.getProperty("vertxVersion");

    model.getProperties().putIfAbsent("vertx.version", vertxVersion);

    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));
    Properties projectProps = project.getProperties();
    assertNotNull(projectProps);
    assertFalse(projectProps.isEmpty());
    assertEquals(projectProps.getProperty("vertx.version"), vertxVersion);
}

From source file:org.apache.hadoop.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  .ja va  2 s.c  o m*/
        public String getValue() {
            return "foo";
        }
    };

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

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

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

@Test
public void sampler() throws Exception {
    final long value[] = new long[1];
    Instrumentation.Variable<Long> var = new Instrumentation.Variable<Long>() {
        @Override// ww  w .j a v a 2s  . com
        public Long getValue() {
            return value[0];
        }
    };

    InstrumentationService.Sampler sampler = new InstrumentationService.Sampler();
    sampler.init(4, var);
    Assert.assertEquals(sampler.getRate(), 0f, 0.0001);
    sampler.sample();
    Assert.assertEquals(sampler.getRate(), 0f, 0.0001);
    value[0] = 1;
    sampler.sample();
    Assert.assertEquals(sampler.getRate(), (0d + 1) / 2, 0.0001);
    value[0] = 2;
    sampler.sample();
    Assert.assertEquals(sampler.getRate(), (0d + 1 + 2) / 3, 0.0001);
    value[0] = 3;
    sampler.sample();
    Assert.assertEquals(sampler.getRate(), (0d + 1 + 2 + 3) / 4, 0.0001);
    value[0] = 4;
    sampler.sample();
    Assert.assertEquals(sampler.getRate(), (4d + 1 + 2 + 3) / 4, 0.0001);

    JSONObject json = (JSONObject) new JSONParser().parse(sampler.toJSONString());
    Assert.assertEquals(json.size(), 2);
    Assert.assertEquals(json.get("sampler"), sampler.getRate());
    Assert.assertEquals(json.get("size"), 4L);

    StringWriter writer = new StringWriter();
    sampler.writeJSONString(writer);
    writer.close();
    json = (JSONObject) new JSONParser().parse(writer.toString());
    Assert.assertEquals(json.size(), 2);
    Assert.assertEquals(json.get("sampler"), sampler.getRate());
    Assert.assertEquals(json.get("size"), 4L);
}

From source file:org.easyrec.service.domain.profile.impl.ProfileServiceImpl.java

public void insertOrUpdateMultiDimension(Integer tenantId, Integer itemId, String itemTypeId,
        String dimensionXPath, List<String> values) {

    XPathFactory xpf = XPathFactory.newInstance();

    try {//  w  ww.ja va2  s  . c om
        // load and parse the profile
        DocumentBuilder db = validationParsers.get(tenantId).get(itemTypeId);
        Document doc = db.parse(new InputSource(new StringReader(getProfile(tenantId, itemId, itemTypeId))));
        // check if the element exists
        Node node = null;
        Node parent = null;
        XPath xp = xpf.newXPath();
        for (Iterator<String> it = values.iterator(); it.hasNext();) {
            String value = it.next();
            // look if value already exists
            node = (Node) xp.evaluate(dimensionXPath + "[text()='" + value + "']", doc, XPathConstants.NODE);
            // if value exists, value can be discarded
            if (node != null) {
                // optimization: if a node was found, store the parent; later no new XPath evaluation is necessary
                parent = node.getParentNode();
                it.remove();
            }
        }
        if (values.isEmpty())
            return; // nothing left to do
        String parentPath = dimensionXPath.substring(0, dimensionXPath.lastIndexOf("/"));
        // find path to parent
        if (parent == null) {
            String tmpPath = parentPath;
            while (parent == null) {
                tmpPath = parentPath.substring(0, tmpPath.lastIndexOf("/"));
                parent = (Node) xp.evaluate(tmpPath, doc, XPathConstants.NODE);
            }
            parent = insertElement(doc, parent, parentPath.substring(tmpPath.length()), null);
        }
        String tag = dimensionXPath.substring(parentPath.length() + 1);
        for (String value : values) {
            Element el = doc.createElement(tag);
            el.setTextContent(value);
            parent.appendChild(el);
        }

        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, itemTypeId, xml, true);

    } catch (Exception e) {
        logger.error("Error inserting Multi Dimension: " + e.getMessage());
        e.printStackTrace();
    }
}