Example usage for java.io Writer toString

List of usage examples for java.io Writer toString

Introduction

In this page you can find the example usage for java.io Writer toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.syncope.core.workflow.ActivitiUserWorkflowAdapter.java

@Override
public WorkflowDefinitionTO getDefinition() throws WorkflowException {

    ProcessDefinition procDef;/*from w  w  w . j  a  va 2 s  . c  om*/
    try {
        procDef = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey(ActivitiUserWorkflowAdapter.WF_PROCESS_ID).latestVersion().singleResult();
    } catch (ActivitiException e) {
        throw new WorkflowException(e);
    }

    InputStream procDefIS = repositoryService.getResourceAsStream(procDef.getDeploymentId(),
            WF_PROCESS_RESOURCE);
    Reader reader = null;
    Writer writer = new StringWriter();
    try {
        reader = new BufferedReader(new InputStreamReader(procDefIS));

        int n;
        char[] buffer = new char[1024];
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } catch (IOException e) {
        LOG.error("While reading workflow definition {}", procDef.getKey(), e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            if (procDefIS != null) {
                procDefIS.close();
            }
        } catch (IOException ioe) {
            LOG.error("While closing input stream for {}", procDef.getKey(), ioe);
        }
    }

    WorkflowDefinitionTO definitionTO = new WorkflowDefinitionTO();
    definitionTO.setId(ActivitiUserWorkflowAdapter.WF_PROCESS_ID);
    definitionTO.setXmlDefinition(writer.toString());

    return definitionTO;
}

From source file:hoot.services.command.CommandRunner.java

public CommandResult exec(String[] pCmd, Map<String, String> pEnv, boolean useSysEnv, File dir, Writer pOut,
        Writer pErr) throws IOException, InterruptedException {

    int out = 0;/*  w  ww  .  ja v a  2 s.co  m*/
    String pCmdString = ArrayUtils.toString(pCmd);
    ProcessBuilder builder = new ProcessBuilder();
    builder.command(pCmd);
    Map<String, String> env = builder.environment();
    if (!useSysEnv)
        env.clear();
    for (String name : pEnv.keySet()) {
        env.put(name, pEnv.get(name));
    }
    builder.directory(dir);

    logExec(pCmdString, env);

    StopWatch clock = new StopWatch();
    clock.start();
    try {
        process = builder.start();
        out = handleProcess(process, pCmdString, pOut, pErr, _outputList, sig_interrupt);
    } finally {
        this.cleanUpProcess();
        clock.stop();
        if (_log.isInfoEnabled())
            _log.info("'" + pCmdString + "' completed in " + clock.getTime() + " ms");
    }
    if (sig_interrupt.getValue() == true) {
        out = -9999;
    }
    CommandResult result = new CommandResult(pCmdString, out, pOut.toString(), pErr.toString());
    return result;
}

From source file:com.cisco.dvbu.ps.common.util.CommonUtils.java

public static String getStackTraceAsString(Throwable throwable) {
    Writer stackTraceWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stackTraceWriter);
    throwable.printStackTrace(printWriter);
    return stackTraceWriter.toString();
}

From source file:org.artifactory.repo.webdav.WebdavServiceImpl.java

@Override
@SuppressWarnings({ "OverlyComplexMethod" })
public void handlePropfind(ArtifactoryRequest request, ArtifactoryResponse response) throws IOException {
    // Retrieve the resources
    int depth = INFINITY;
    String depthStr = request.getHeader("Depth");
    if (depthStr != null) {
        if ("0".equals(depthStr)) {
            depth = 0;/*  w  w  w .j  a v  a2 s .c o  m*/
        } else if ("1".equals(depthStr)) {
            depth = 1;
        } else if ("infinity".equals(depthStr)) {
            depth = INFINITY;
        }
    }
    List<String> properties = null;
    int propertyFindType = FIND_ALL_PROP;
    Node propNode = null;
    //get propertyNode and type
    if (request.getContentLength() > 0) {
        DocumentBuilder documentBuilder = getDocumentBuilder();
        try {
            Document document = documentBuilder.parse(new InputSource(request.getInputStream()));
            logWebdavRequest(document);
            // Get the root element of the document
            Element rootElement = document.getDocumentElement();
            NodeList childList = rootElement.getChildNodes();

            for (int i = 0; i < childList.getLength(); i++) {
                Node currentNode = childList.item(i);
                switch (currentNode.getNodeType()) {
                case Node.TEXT_NODE:
                    break;
                case Node.ELEMENT_NODE:
                    if (currentNode.getNodeName().endsWith("prop")) {
                        propertyFindType = FIND_BY_PROPERTY;
                        propNode = currentNode;
                    }
                    if (currentNode.getNodeName().endsWith("propname")) {
                        propertyFindType = FIND_PROPERTY_NAMES;
                    }
                    if (currentNode.getNodeName().endsWith("allprop")) {
                        propertyFindType = FIND_ALL_PROP;
                    }
                    break;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Webdav propfind failed.", e);
        }
    }

    if (propertyFindType == FIND_BY_PROPERTY) {
        properties = getPropertiesFromXml(propNode);
    }

    response.setStatus(WebdavStatus.SC_MULTI_STATUS);
    response.setContentType("text/xml; charset=UTF-8");

    // Create multistatus object
    Writer writer = response.getWriter();
    if (log.isDebugEnabled()) {
        writer = new StringWriter(); // write to memory so we'll be able to log the result as string
    }
    XmlWriter generatedXml = new XmlWriter(writer);
    generatedXml.writeXMLHeader();
    generatedXml.writeElement(null, "multistatus xmlns=\"" + DEFAULT_NAMESPACE + "\"", XmlWriter.OPENING);

    RepoPath repoPath = request.getRepoPath();
    BrowsableItem rootItem = null;
    if (repoService.exists(repoPath)) {
        rootItem = repoBrowsing.getLocalRepoBrowsableItem(repoPath);
    }
    if (rootItem != null) {
        recursiveParseProperties(request, response, generatedXml, rootItem, propertyFindType, properties,
                depth);
    } else {
        log.warn("Item '" + request.getRepoPath() + "' not found.");
    }
    generatedXml.writeElement(null, "multistatus", XmlWriter.CLOSING);
    generatedXml.sendData();
    if (log.isDebugEnabled()) {
        log.debug("Webdav response:\n" + writer.toString());
        //response.setContentLength(writer.toString().getBytes().length);
        response.getWriter().append(writer.toString());
    }
    response.flush();
}

From source file:com.powers.wsexplorer.gui.WSExplorer.java

public String getStrackTraceAsString(Throwable t) {
    if (t == null) {
        return null;
    }// w ww  .j ava2s  .  c  o m

    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    t.printStackTrace(printWriter);
    return result.toString();
}

From source file:com.cyberway.issue.crawler.frontier.AdaptiveRevisitFrontier.java

/**
 * Loads the seeds//from w  w w .j  a v  a 2 s  .co m
 * <p>
 * This method is called by initialize() and kickUpdate()
 */
public void loadSeeds() {
    Writer ignoredWriter = new StringWriter();
    // Get the seeds to refresh.
    Iterator iter = this.controller.getScope().seedsIterator(ignoredWriter);
    while (iter.hasNext()) {
        CandidateURI caUri = CandidateURI.createSeedCandidateURI((UURI) iter.next());
        caUri.setSchedulingDirective(CandidateURI.MEDIUM);
        schedule(caUri);
    }
    batchFlush();
    // save ignored items (if any) where they can be consulted later
    AbstractFrontier.saveIgnoredItems(ignoredWriter.toString(), controller.getDisk());
}

From source file:com.kloudtek.buildmagic.tools.createinstaller.deb.CreateDebTask.java

private void writeTemplate(final TarArchive tarArchive, final ArrayList<TemplateEntry> templateEntries)
        throws IOException {
    final Writer w = new StringWriter();
    for (Iterator<TemplateEntry> iterator = templateEntries.iterator(); iterator.hasNext();) {
        final TemplateEntry entry = iterator.next();
        if (entry.getFullId() == null) {
            throw new BuildException("template id missing");
        }/*  w w  w  .  j a  v a2s  .  co m*/
        if (entry.getShortDesc() == null) {
            throw new BuildException("template " + entry.getId() + " has no shortDesc defined");
        }
        w.write("Template: ");
        w.write(entry.getFullId());
        if (entry.getDefaultValue() != null) {
            w.write("\nDefault: ");
            w.write(entry.getDefaultValue());
        }
        w.write("\nType: ");
        w.write(entry.getType().name().toLowerCase());
        w.write("\nDescription: ");
        w.write(entry.getShortDesc());
        w.write("\n");
        String longDesc = entry.getLongDesc();
        if (longDesc == null) {
            longDesc = entry.getShortDesc();
        }
        w.write(generateExtendedControlField(longDesc));
        w.write("\n");
        if (iterator.hasNext()) {
            w.write("\n");
        }
    }
    w.close();
    tarArchive.write(w.toString(), "templates");
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.source.TestCswSourceBase.java

protected String getGetRecordsTypeAsXml(GetRecordsType getRecordsType, String cswVersion) {
    Writer writer = new StringWriter();
    try {/*from   www .j  a  v  a 2 s .c  om*/
        JAXBContext jaxbContext = JAXBContext.newInstance(
                "net.opengis.cat.csw.v_2_0_2:net.opengis.filter.v_1_1_0:net.opengis.gml.v_3_1_1:net.opengis.ows.v_1_0_0");
        Marshaller marshaller = jaxbContext.createMarshaller();

        JAXBElement<GetRecordsType> jaxbElement = null;
        if (CswConstants.VERSION_2_0_2.equals(cswVersion)) {
            // QName("http://www.opengis.net/cat/csw/2.0.2", ""GetRecords")
            jaxbElement = new JAXBElement<GetRecordsType>(
                    new QName(CswConstants.CSW_OUTPUT_SCHEMA, CswConstants.GET_RECORDS), GetRecordsType.class,
                    getRecordsType);
        } else {
            // CSW 2.0.1
            // QName("http://www.opengis.net/cat/csw", ""GetRecords")
            LOGGER.debug("Called 2.0.1");
            jaxbElement = new JAXBElement<GetRecordsType>(
                    new QName("http://www.opengis.net/cat/csw", CswConstants.GET_RECORDS), GetRecordsType.class,
                    getRecordsType);
        }
        marshaller.marshal(jaxbElement, writer);
    } catch (JAXBException e) {
        String message = "Unable to marshall " + GetRecordsResponseType.class + " to XML.";
        LOGGER.debug(message, e);
    }
    return writer.toString();
}

From source file:org.cryptsecure.Utility.java

/**
 * Get the content as string./*from  w ww  .  ja  v  a 2 s  .  c  om*/
 * 
 * @param response
 *            the response
 * @return the content as string
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static String getContentAsString(HttpResponse response) throws IOException {
    String returnString = "";
    HttpEntity httpEntity = response.getEntity();

    InputStream inputStream = httpEntity.getContent();
    InputStreamReader is = new InputStreamReader(inputStream);

    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(is);
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }

        returnString = writer.toString();

    }

    return returnString;
}

From source file:com.w20e.socrates.formatting.VelocityHTMLFormatter.java

/**
 * Format list of items. This formatter uses velocity and thus needs a
 * template to work. The template to use is determined as follows: 1. if the
 * RunnerContext contains a value for the property "template", this one is
 * used; 2. else if the configuration given to init contains a key for
 * "formatter.template", this one is used; 3. the template name defaults to
 * "main.vm".//from ww  w.  j  a v  a2  s  .c o  m
 * 
 * @param items
 *            List of items to use.
 * @param out
 *            OutputStream to use
 * @param pContext
 *            Processing context
 * @throws Exception
 *             in case of Velocity errors, or output stream errors.
 */
public void format(final Collection<Renderable> items, final OutputStream out, final RunnerContext pContext)
        throws FormatException {

    VelocityContext context = new VelocityContext();
    try {
        Writer writer;
        writer = new OutputStreamWriter(out, this.cfg.getString("formatter.encoding", "UTF-8"));

        Locale locale = pContext.getLocale();

        LOGGER.fine("Using locale " + locale + " with prefix " + this.cfg.getString("formatter.locale.prefix"));

        UTF8ResourceBundle bundle = UTF8ResourceBundleImpl
                .getBundle(this.cfg.getString("formatter.locale.prefix"), locale);

        LOGGER.fine("Found resource locale: " + bundle.getLocale());

        LOGGER.finer("Formatting " + items.size() + " items");

        fillContext(items, context, pContext, bundle);

        this.engine.mergeTemplate(
                (String) pContext.getProperty("template", this.cfg.getString("formatter.template", "main.vm")),
                this.cfg.getString("formatter.encoding", "UTF-8"), context, writer);
        writer.flush();
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Error in formatting items", e);
        // Print full stack to logging;
        PrintWriter writer = new PrintWriter(new StringWriter());
        e.printStackTrace(writer);
        LOGGER.log(Level.SEVERE, writer.toString());
        throw new FormatException(e.getMessage());
    }
}