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:com.fiorano.openesb.application.DmiObject.java

/**
 *  This method returns the XML String representation for this object of
 *  <code>DmiObject</code>. It has not been implemented in this version.
 *
 * @param versionNo version/*from  w w w .  j a v  a 2s .  co  m*/
 * @return XML String for this object
 * @exception FioranoException If the calls fails
 * @since Tifosi2.0
 */

public String toXMLString(int versionNo) throws FioranoException {
    try {
        StringWriter writer = new StringWriter();
        toXMLString(writer);
        writer.close();
        return writer.toString();
    } catch (IOException e) {
        throw new FioranoException(e);
    }
}

From source file:com.aurel.track.lucene.index.associatedFields.textExctractor.PdfExtractor.java

/**
 * Gets the text from file content /*from   w  w  w  .  jav  a 2s .  c  o  m*/
 * @param file
 * @param fileExtension
 * @return
 */
@Override
public String getText(File file, String fileExtension) {
    FileInputStream fis = null;
    PDDocument pdDoc = null;
    StringWriter stringWriter = null;
    try {
        fis = new FileInputStream(file);
        PDFParser parser = new PDFParser(fis);
        parser.parse();
        pdDoc = parser.getPDDocument();
        PDFTextStripper stripper = new PDFTextStripper();
        stripper.setLineSeparator("\n");
        stringWriter = new StringWriter();
        stripper.writeText(pdDoc, stringWriter);
        return stringWriter.toString();
    } catch (Exception e) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(
                    "Extracting text from the .pdf  file " + file.getName() + " failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    } finally {
        try {
            if (stringWriter != null) {
                stringWriter.close();
            }
        } catch (Exception e) {
        }
        try {
            if (pdDoc != null) {
                pdDoc.close();
            }
        } catch (Exception e) {
            LOGGER.info("Closing pdDoc for " + file + " failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
        try {
            if (fis != null) {
                fis.close();
            }
        } catch (Exception e) {
            LOGGER.info("Closing the FileInputStream for " + file + " failed with " + e.getMessage());
        }
    }
    return null;
}

From source file:org.eclipse.winery.repository.resources.servicetemplates.plans.PlansResource.java

@POST
@RestDoc(methodDescription = "<p>Linked plans are currently not supported. Existing plans with the same id are overwritten</p> <p>@return JSON with .tableData: Array with row data for dataTable</p>")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@Produces(MediaType.APPLICATION_JSON)/*from  w  ww.  j  a  v a2  s.c o m*/
// the supertype consumes JSON and XML at org.eclipse.winery.repository.resources._support.collections.EntityCollectionResource.addNewElement(EntityT)
// @formatter:off
public Response onPost(@FormDataParam("planName") String name, @FormDataParam("planType") String type,
        @FormDataParam("planLanguage") @RestDocParam(description = "the plan language (e..g, BPMN or BPEL). Full URL.") String language,
        @FormDataParam("file") @RestDocParam(description = "(optional in the case of BPMN4TOSCA) file containing the plan.") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail,
        @FormDataParam("file") FormDataBodyPart body) {
    // @formatter:on
    if (StringUtils.isEmpty(name)) {
        return Response.status(Status.BAD_REQUEST).entity("planName must be given").build();
    }
    if (StringUtils.isEmpty(type)) {
        return Response.status(Status.BAD_REQUEST).entity("planType must be given").build();
    }
    if (StringUtils.isEmpty(language)) {
        return Response.status(Status.BAD_REQUEST).entity("planLanguage must be given").build();
    }

    boolean bpmn4toscaMode = org.eclipse.winery.common.constants.Namespaces.URI_BPMN4TOSCA_20.equals(language);
    if (!bpmn4toscaMode) {
        if (uploadedInputStream == null) {
            return Response.status(Status.BAD_REQUEST).entity("file must be given").build();
        }
    }

    // A plan carries both a name and an ID
    // To be user-friendly, we create the ID based on the name
    // the drawback is, that we do not allow two plans with the same name
    // during creation, but allow renaming plans to the same name (as we do
    // not allow ID renaming)
    String xmlId = Utils.createXMLidAsString(name);

    // BEGIN: Store plan file

    // Determine Id
    PlansId plansId = new PlansId((ServiceTemplateId) ((ServiceTemplateResource) this.res).getId());
    PlanId planId = new PlanId(plansId, new XMLId(xmlId, false));
    // Ensure overwriting
    if (Repository.INSTANCE.exists(planId)) {
        try {
            Repository.INSTANCE.forceDelete(planId);
            // Quick hack to remove the deleted plan from the plans element
            ((ServiceTemplateResource) this.res).synchronizeReferences();
        } catch (IOException e) {
            return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
        }
    }

    String fileName;
    if (bpmn4toscaMode) {
        fileName = xmlId + Constants.SUFFIX_BPMN4TOSCA;
        RepositoryFileReference ref = new RepositoryFileReference(planId, fileName);
        try {
            Repository.INSTANCE.putContentToFile(ref, "{}", MediaType.APPLICATION_JSON_TYPE);
        } catch (IOException e1) {
            return Response.status(Status.INTERNAL_SERVER_ERROR)
                    .entity("Could not create empty plan. " + e1.getMessage()).build();
        }
    } else {
        // We use the filename also as local file name. Alternatively, we could use the xml id
        // With URL encoding, this should not be an issue
        fileName = Util.URLencode(fileDetail.getFileName());

        // Really store it
        RepositoryFileReference ref = new RepositoryFileReference(planId, fileName);
        try {
            Repository.INSTANCE.putContentToFile(ref, uploadedInputStream, body.getMediaType());
        } catch (IOException e1) {
            return Response.status(Status.INTERNAL_SERVER_ERROR)
                    .entity("Could not store plan. " + e1.getMessage()).build();
        }
    }
    // END: Store plan file

    TPlan plan = new TPlan();
    plan.setId(xmlId);
    plan.setName(name);
    plan.setPlanType(type);
    plan.setPlanLanguage(language);
    PlansResource.setPlanModelReference(plan, planId, fileName);
    this.list.add(plan);

    // prepare result
    JsonFactory jsonFactory = new JsonFactory();
    StringWriter sw = new StringWriter();
    try {
        JsonGenerator jGenerator = jsonFactory.createGenerator(sw);
        jGenerator.writeStartObject();
        jGenerator.writeFieldName("tableData");
        jGenerator.writeStartArray();
        jGenerator.writeString(xmlId);
        jGenerator.writeString(""); // precondition
        jGenerator.writeString(name);
        jGenerator.writeString(PlanTypesManager.INSTANCE.getShortName(type));
        jGenerator.writeString(PlanLanguagesManager.INSTANCE.getShortName(language));
        jGenerator.writeEndArray();
        jGenerator.writeEndObject();
        jGenerator.close();
        sw.close();
    } catch (JsonGenerationException e) {
        PlansResource.logger.error(e.getMessage(), e);
        return Response.serverError().build();
    } catch (IOException e) {
        PlansResource.logger.error(e.getMessage(), e);
        return Response.serverError().build();
    }

    Response res = BackendUtils.persist(this.res);
    if (res.getStatus() == 204) {
        // everything OK, return created
        return Response.created(Utils.createURI(Util.URLencode(xmlId))).entity(sw.toString()).build();
    } else {
        return res;
    }
}

From source file:io.github.gsteckman.rpi_rest.SsdpHandler.java

private String generateSearchResponse() throws IOException {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    pw.print("HTTP/1.1 200 OK\r\n");
    pw.printf("CACHE-CONTROL: max-age=%d\r\n", MAX_AGE);
    pw.print("EXT:\r\n");
    pw.printf("LOCATION: http://%s:8080\r\n", getServerAddress());
    pw.print("SERVER: " + System.getProperty("os.name") + "/" + System.getProperty("os.version")
            + ", UPnP/1.1, rpi-rest/0.1\r\n");
    pw.printf("ST: %s\r\n", ST);
    pw.printf("USN: uuid:%s\r\n", getUuid().toString());
    pw.printf("BOOTID.UPNP.ORG: %d\r\n", BOOTID);
    pw.printf("CONFIGID.UPNP.ORG: %d\r\n", CONFIGID);
    pw.printf("\r\n");
    pw.flush();// w ww.  j ava2s.  co m
    String resp = sw.toString();
    pw.close();
    sw.close();
    return resp;
}

From source file:com.google.acre.script.NHttpAsyncUrlfetch.java

private Scriptable callback_result(long start_time, URL url, HttpResponse res, boolean system,
        boolean log_to_user, String response_encoding) {
    BrowserCompatSpecFactory bcsf = new BrowserCompatSpecFactory();
    CookieSpec cspec = bcsf.newInstance(null);
    String protocol = url.getProtocol();
    boolean issecure = ("https".equals(protocol));
    int port = url.getPort();
    if (port == -1)
        port = 80;//from  www.j a va 2s  .  c  o m
    CookieOrigin origin = new CookieOrigin(url.getHost(), port, url.getPath(), issecure);

    Object body = "";
    int status = res.getStatusLine().getStatusCode();

    Context ctx = Context.getCurrentContext();
    Scriptable out = ctx.newObject(_scope);
    Scriptable headers = ctx.newObject(_scope);
    Scriptable cookies = ctx.newObject(_scope);

    out.put("status", out, status);
    out.put("headers", out, headers);
    out.put("cookies", out, cookies);

    Header content_type_header = null;

    StringBuilder response_header_log = new StringBuilder();
    for (Header h : res.getAllHeaders()) {
        if (h.getName().equalsIgnoreCase("set-cookie")) {
            String set_cookie = h.getValue();
            Matcher m = Pattern.compile("\\s*(([^,]|(,\\s*\\d))+)").matcher(set_cookie);
            while (m.find()) {
                Header ch = new BasicHeader("Set-Cookie", set_cookie.substring(m.start(), m.end()));
                try {
                    List<Cookie> pcookies = cspec.parse(ch, origin);
                    for (Cookie c : pcookies) {
                        cookies.put(c.getName(), cookies, new AcreCookie(c).toJsObject(_scope));
                    }
                } catch (MalformedCookieException e) {
                    throw new RuntimeException(e);
                }
            }
        } else if (h.getName().equalsIgnoreCase("content-type")) {
            content_type_header = h;
        }

        response_header_log.append(h.getName() + ": " + h.getValue() + "\r\n");
        headers.put(h.getName(), headers, h.getValue());
    }

    String charset = null;
    if (content_type_header != null) {
        HeaderElement values[] = content_type_header.getElements();
        if (values.length == 1) {
            NameValuePair param = values[0].getParameterByName("charset");
            if (param != null) {
                charset = param.getValue();
            }
        }
    }

    if (charset == null)
        charset = response_encoding;

    // read body
    HttpEntity ent = res.getEntity();
    try {
        if (ent != null) {
            InputStream res_stream = ent.getContent();
            Header cenc = ent.getContentEncoding();
            if (cenc != null && res_stream != null) {
                HeaderElement[] codecs = cenc.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        res_stream = new GZIPInputStream(res_stream);
                    }
                }
            }

            long first_byte_time = 0;
            long end_time = 0;
            if (content_type_header != null && (content_type_header.getValue().startsWith("image/")
                    || content_type_header.getValue().startsWith("application/octet-stream")
                    || content_type_header.getValue().startsWith("multipart/form-data"))) {
                // HttpClient's InputStream doesn't support mark/reset, so
                // wrap it with one that does.
                BufferedInputStream bufis = new BufferedInputStream(res_stream);
                bufis.mark(2);
                bufis.read();
                first_byte_time = System.currentTimeMillis();
                bufis.reset();
                byte[] data = IOUtils.toByteArray(bufis);

                end_time = System.currentTimeMillis();
                body = new JSBinary();
                ((JSBinary) body).set_data(data);

                try {
                    if (res_stream != null)
                        res_stream.close();
                } catch (IOException e) {
                    // ignore
                }
            } else if (res_stream == null || charset == null) {
                first_byte_time = end_time = System.currentTimeMillis();
                body = "";
            } else {
                StringWriter writer = new StringWriter();
                Reader reader = new InputStreamReader(res_stream, charset);
                int i = reader.read();
                first_byte_time = System.currentTimeMillis();
                writer.write(i);
                IOUtils.copy(reader, writer);
                end_time = System.currentTimeMillis();
                body = writer.toString();

                try {
                    reader.close();
                    writer.close();
                } catch (IOException e) {
                    // ignore
                }
            }

            long reading_time = end_time - first_byte_time;
            long waiting_time = first_byte_time - start_time;

            String httprephdr = response_header_log.toString();
            // XXX need to log start-time of request
            _logger.syslog4j("DEBUG", "urlfetch.response.async", "URL", url.toString(), "Status",
                    Integer.toString(status), "Headers", httprephdr, "Reading time", reading_time,
                    "Waiting time", waiting_time);

            if (system && log_to_user) {
                _response.userlog4j("DEBUG", "urlfetch.response.async", "URL", url.toString(), "Status",
                        Integer.toString(status), "Headers", httprephdr);

            }

            // XXX seems like AcreResponse should be able to use
            // the statistics object to generate x-metaweb-cost
            // given a bit of extra information

            Statistics.instance().collectUrlfetchTime(start_time, first_byte_time, end_time);

            _costCollector.collect((system) ? "asuc" : "auuc").collect((system) ? "asuw" : "auuw",
                    waiting_time);

        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    out.put("body", out, body);

    return out;
}

From source file:com.xmlcalabash.library.ApacheHttpRequest.java

private void doPutOrPost(EntityEnclosingMethod method, XdmNode body) {
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    for (Header header : headers) {
        method.addRequestHeader(header);
    }/*ww  w.j  a  va2 s  .  c  o  m*/

    contentType = body.getAttributeValue(_content_type);
    if (contentType == null) {
        throw new XProcException("Content-type on c:body is required.");
    }

    // FIXME: This sucks rocks. I want to write the data to be posted, not provide some way to read it
    String postContent = null;
    try {
        if (xmlContentType(contentType)) {
            Serializer serializer = makeSerializer();

            Vector<XdmNode> content = new Vector<XdmNode>();
            XdmSequenceIterator iter = body.axisIterator(Axis.CHILD);
            while (iter.hasNext()) {
                XdmNode node = (XdmNode) iter.next();
                content.add(node);
            }

            // FIXME: set serializer properties appropriately!
            StringWriter writer = new StringWriter();
            serializer.setOutputWriter(writer);
            S9apiUtils.serialize(runtime, content, serializer);
            writer.close();
            postContent = writer.toString();
        } else {
            StringWriter writer = new StringWriter();
            XdmSequenceIterator iter = body.axisIterator(Axis.CHILD);
            while (iter.hasNext()) {
                XdmNode node = (XdmNode) iter.next();
                writer.write(node.getStringValue());
            }
            writer.close();
            postContent = writer.toString();
        }

        StringRequestEntity requestEntity = new StringRequestEntity(postContent, contentType, "UTF-8");
        method.setRequestEntity(requestEntity);

    } catch (IOException ioe) {
        throw new XProcException(ioe);
    } catch (SaxonApiException sae) {
        throw new XProcException(sae);
    }
}

From source file:com.photon.phresco.service.admin.actions.ServiceBaseAction.java

protected String showErrorPopup(PhrescoException e, String action) {
    StringWriter sw = null;
    PrintWriter pw = null;//from  w  ww.j a  v  a  2  s. c  om
    try {
        sw = new StringWriter();
        pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        String stacktrace = sw.toString();
        User userInfo = (User) getHttpSession().getAttribute(SESSION_USER_INFO);
        LogInfo log = new LogInfo();
        log.setMessage(e.getLocalizedMessage());
        log.setTrace(stacktrace);
        log.setAction(action);
        log.setUserId(userInfo.getLoginId());
        setReqAttribute(REQ_LOG_REPORT, log);
    } finally {
        if (pw != null) {
            pw.close();
        }
        if (sw != null) {
            try {
                sw.close();
            } catch (IOException e1) {
                //Do nothing due to error popup
            }
        }
    }
    return LOG_ERROR;
}

From source file:edu.cornell.mannlib.vitro.webapp.servlet.setup.UpdateKnowledgeBase.java

private void addPageListDisplayModel(OntModel displayModel, Model addStatements, Model removeStatements,
        UpdateSettings settings) {/*www. j  a  v a  2s . c  o m*/
    OntModel newDisplayModel = settings.getNewDisplayModelFromFile();
    //Get all statements about pageListPage and pageListData
    Resource pageList = newDisplayModel.getResource(DisplayVocabulary.DISPLAY_NS + "pageListPage");
    Resource pageListData = newDisplayModel.getResource(DisplayVocabulary.DISPLAY_NS + "pageListData");

    addStatements.add(newDisplayModel.listStatements(pageList, null, (RDFNode) null));
    addStatements.add(newDisplayModel.listStatements(pageListData, null, (RDFNode) null));
    StringWriter sw = new StringWriter();
    try {
        if (pageList != null) {
            log.debug("Page list uri is " + pageList.getURI());
        } else {
            log.debug("Page list uri is null for some reason");
        }
        log.debug("New Display model from file is ");
        newDisplayModel.write(sw, "N3");
        log.debug(sw.toString());
        sw.close();
        sw = new StringWriter();
        log.debug("Added statements now include ");
        addStatements.write(sw, "N3");
        log.debug(sw.toString());
        sw.close();
    } catch (Exception ex) {
        log.error("Exception occurred in writing out new display model", ex);
    }

    log.debug("Checking: AFTER adding pageList resource, what do we have for pageList page");
    Resource testResource = ResourceFactory.createResource(DisplayVocabulary.DISPLAY_NS + "pageListPage");
    StmtIterator testIt = addStatements.listStatements(testResource, null, (RDFNode) null);
    if (!testIt.hasNext()) {
        log.debug("Add statements does not have the page list page resource " + testResource.getURI());
    }

    while (testIt.hasNext()) {
        log.debug("Statement for page list resource: " + testIt.nextStatement().toString());
    }
}

From source file:org.apache.olingo.fit.utils.AbstractUtilities.java

public InputStream writeEntitySet(final Accept accept, final ResWrap<EntityCollection> container)
        throws ODataSerializerException, IOException {

    final StringWriter writer = new StringWriter();
    if (accept == Accept.ATOM || accept == Accept.XML) {
        atomSerializer.write(writer, container);
    } else {//from   w w  w . j  ava2  s .c  om
        jsonSerializer.write(writer, container);
    }
    writer.flush();
    writer.close();

    return IOUtils.toInputStream(writer.toString(), Constants.ENCODING);
}