Example usage for java.io StringWriter write

List of usage examples for java.io StringWriter write

Introduction

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

Prototype

public void write(String str) 

Source Link

Document

Write a string.

Usage

From source file:org.syncope.core.propagation.PropagationManager.java

/**
 * Execute a propagation task./*from   ww  w.j  a  va 2s.  co  m*/
 *
 * @param task to execute.
 * @param handler propagation handler.
 * @return TaskExecution.
 */
public TaskExec execute(final PropagationTask task, final PropagationHandler handler) {
    final Date startDate = new Date();

    TaskExec execution = new TaskExec();
    execution.setStatus(PropagationTaskExecStatus.CREATED.name());

    String taskExecutionMessage = null;

    // Flag to state wether any propagation has been attempted
    Set<String> propagationAttempted = new HashSet<String>();

    ConnectorObject before = null;
    ConnectorObject after = null;

    try {
        final ConnInstance connInstance = task.getResource().getConnector();

        final ConnectorFacadeProxy connector = connLoader.getConnector(task.getResource());

        if (connector == null) {
            final String msg = String.format(
                    "Connector instance bean for resource %s and " + "connInstance %s not found",
                    task.getResource(), connInstance);

            throw new NoSuchBeanDefinitionException(msg);
        }

        // Try to read user BEFORE any actual operation
        before = getRemoteObject(connector, task, false);

        try {
            switch (task.getPropagationOperation()) {
            case CREATE:
            case UPDATE:
                // set of attributes to be propagated
                final Set<Attribute> attributes = new HashSet<Attribute>(task.getAttributes());

                if (before != null) {

                    // 1. check if rename is really required
                    final Name newName = (Name) AttributeUtil.find(Name.NAME, attributes);

                    LOG.debug("Rename required with value {}", newName);

                    if (newName != null && newName.equals(before.getName())
                            && !before.getUid().getUidValue().equals(newName.getNameValue())) {

                        LOG.debug("Remote object name unchanged");
                        attributes.remove(newName);
                    }

                    LOG.debug("Attributes to be replaced {}", attributes);

                    // 2. update with a new "normalized" attribute set
                    connector.update(task.getPropagationMode(), ObjectClass.ACCOUNT, before.getUid(),
                            attributes, null, propagationAttempted);
                } else {
                    // 1. get accountId
                    final String accountId = task.getAccountId();

                    // 2. get name
                    final Name name = (Name) AttributeUtil.find(Name.NAME, attributes);

                    // 3. check if:
                    //      * accountId is not blank;
                    //      * accountId is not equal to Name.
                    if (StringUtils.hasText(accountId)
                            && (name == null || !accountId.equals(name.getNameValue()))) {

                        // 3.a retrieve uid
                        final Uid uid = (Uid) AttributeUtil.find(Uid.NAME, attributes);

                        // 3.b add Uid if not provided
                        if (uid == null) {
                            attributes.add(AttributeBuilder.build(Uid.NAME, Collections.singleton(accountId)));
                        }
                    }

                    // 4. provision entry
                    connector.create(task.getPropagationMode(), ObjectClass.ACCOUNT, attributes, null,
                            propagationAttempted);
                }
                break;

            case DELETE:
                if (before == null) {
                    LOG.debug("{} not found on external resource:" + " ignoring delete", task.getAccountId());
                } else {
                    connector.delete(task.getPropagationMode(), ObjectClass.ACCOUNT, before.getUid(), null,
                            propagationAttempted);
                }
                break;

            default:
            }

            execution.setStatus(task.getPropagationMode() == PropagationMode.ONE_PHASE
                    ? PropagationTaskExecStatus.SUCCESS.name()
                    : PropagationTaskExecStatus.SUBMITTED.name());

            LOG.debug("Successfully propagated to {}", task.getResource());

            // Try to read user AFTER any actual operation
            after = getRemoteObject(connector, task, true);

        } catch (Exception e) {
            after = getRemoteObject(connector, task, false);
            throw e;
        }

    } catch (Throwable t) {
        LOG.error("Exception during provision on resource " + task.getResource().getName(), t);

        if (t instanceof ConnectorException && t.getCause() != null) {
            taskExecutionMessage = t.getCause().getMessage();
        } else {
            StringWriter exceptionWriter = new StringWriter();
            exceptionWriter.write(t.getMessage() + "\n\n");
            t.printStackTrace(new PrintWriter(exceptionWriter));
            taskExecutionMessage = exceptionWriter.toString();
        }

        try {
            execution.setStatus(task.getPropagationMode() == PropagationMode.ONE_PHASE
                    ? PropagationTaskExecStatus.FAILURE.name()
                    : PropagationTaskExecStatus.UNSUBMITTED.name());
        } catch (Throwable wft) {
            LOG.error("While executing KO action on {}", execution, wft);
        }

        propagationAttempted.add(task.getPropagationOperation().name().toLowerCase());
    } finally {
        LOG.debug("Update execution for {}", task);

        if (hasToBeregistered(task, execution)) {
            PropagationTask savedTask = taskDAO.save(task);

            execution.setStartDate(startDate);
            execution.setMessage(taskExecutionMessage);
            execution.setEndDate(new Date());
            execution.setTask(savedTask);

            if (!propagationAttempted.isEmpty()) {
                execution = taskExecDAO.save(execution);

                LOG.debug("Execution finished: {}", execution);
            } else {
                LOG.debug("No propagation attemped for {}", execution);
            }
        }
    }

    if (handler != null) {
        handler.handle(task.getResource().getName(), PropagationTaskExecStatus.valueOf(execution.getStatus()),
                before, after);
    }

    return execution;
}

From source file:org.eclipse.jubula.app.testexec.batch.ExecutionController.java

/**
 * creates the job passend to command Line client
 * @param configFile File/* www .ja  v  a 2 s  . c om*/
 * @throws IOException Error
 * @return Jobconfiguration
 */
public JobConfiguration initJob(File configFile) throws IOException {
    if (configFile != null) {
        // Create JobConfiguration from xml
        BufferedReader in = null;
        StringWriter writer = new StringWriter();
        try {
            in = new BufferedReader(new FileReader(configFile));
            String line = null;
            while ((line = in.readLine()) != null) {
                writer.write(line);
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
        String xml = writer.toString();
        m_job = JobConfiguration.readFromXML(xml);
    } else {
        // or create an emty JobConfiguration
        m_job = new JobConfiguration();
    }
    return m_job;
}

From source file:org.botlibre.util.Utils.java

/**
 * Format the text that may be HTML, or may be text, or markup, or a mix.
 *//*from   ww  w  .  j  a va  2 s  .  c  om*/
public static String formatHTMLOutput(String text) {
    if (text == null) {
        return "";
    }
    int index = text.indexOf('<');
    int index2 = text.indexOf('>');
    boolean isHTML = (index != -1) && (index2 > index);
    boolean isMixed = isHTML && text.contains("[code]");
    if (isHTML && !isMixed) {
        return text;
    }
    if (!isMixed && ((index != -1) || (index2 != -1))) {
        text = text.replace("<", "&lt;");
        text = text.replace(">", "&gt;");
    }
    TextStream stream = new TextStream(text.trim());
    StringWriter writer = new StringWriter();
    boolean bullet = false;
    boolean nbullet = false;
    while (!stream.atEnd()) {
        String line = stream.nextLine();
        if (!isMixed && (line.contains("http://") || line.contains("https://"))) {
            line = Utils.linkHTML(line);
        }
        TextStream lineStream = new TextStream(line);
        boolean firstWord = true;
        boolean span = false;
        boolean cr = true;
        while (!lineStream.atEnd()) {
            while (!isMixed && firstWord && lineStream.peek() == ' ') {
                lineStream.next();
                writer.write("&nbsp;");
            }
            String whitespace = lineStream.nextWhitespace();
            writer.write(whitespace);
            if (lineStream.atEnd()) {
                break;
            }
            String word = lineStream.nextWord();
            if (!isMixed && nbullet && firstWord && !word.equals("#")) {
                writer.write("</ol>\n");
                nbullet = false;
            } else if (!isMixed && bullet && firstWord && !word.equals("*")) {
                writer.write("</ul>\n");
                bullet = false;
            }
            if (firstWord && word.equals("[")) {
                String peek = lineStream.peekWord();
                if ("code".equals(peek)) {
                    lineStream.nextWord();
                    String next = lineStream.nextWord();
                    String lang = "javascript";
                    int lines = 20;
                    if ("lang".equals(next)) {
                        lineStream.skip();
                        lang = lineStream.nextWord();
                        if ("\"".equals(lang)) {
                            lang = lineStream.nextWord();
                            lineStream.skip();
                        }
                        next = lineStream.nextWord();
                    }
                    if ("lines".equals(next)) {
                        lineStream.skip();
                        String value = lineStream.nextWord();
                        if ("\"".equals(value)) {
                            value = lineStream.nextWord();
                            lineStream.skip();
                        }
                        lineStream.skip();
                        try {
                            lines = Integer.valueOf(value);
                        } catch (NumberFormatException ignore) {
                        }
                    }
                    String id = "code" + stream.getPosition();
                    writer.write("<div style=\"width:100%;height:" + lines * 14 + "px;max-width:none\" id=\""
                            + id + "\">");
                    String code = lineStream.upToAll("[code]");
                    if (code.indexOf('<') != -1) {
                        code = code.replace("<", "&lt;");
                    }
                    if (code.indexOf('>') != -1) {
                        code = code.replace(">", "&gt;");
                    }
                    writer.write(code);
                    while (lineStream.atEnd() && !stream.atEnd()) {
                        line = stream.nextLine();
                        lineStream = new TextStream(line);
                        while (lineStream.peek() == ':') {
                            lineStream.next();
                            writer.write("&nbsp;&nbsp;&nbsp;&nbsp;");
                        }
                        code = lineStream.upToAll("[code]");
                        if (code.indexOf('<') != -1) {
                            code = code.replace("<", "&lt;");
                        }
                        if (code.indexOf('>') != -1) {
                            code = code.replace(">", "&gt;");
                        }
                        writer.write(code);
                    }
                    lineStream.skip("[code]".length());
                    writer.write("</div>\n");

                    writer.write("<script>\n");
                    writer.write("var " + id + " = ace.edit('" + id + "');\n");
                    writer.write(id + ".getSession().setMode('ace/mode/" + lang + "');\n");
                    writer.write(id + ".setReadOnly(true);\n");
                    writer.write("</script>\n");
                } else {
                    writer.write(word);
                }
            } else if (!isMixed && firstWord && word.equals("=")) {
                int count = 2;
                String token = word;
                while (!lineStream.atEnd() && lineStream.peek() == '=') {
                    lineStream.skip();
                    count++;
                    token = token + "=";
                }
                String header = lineStream.upToAll(token);
                if (lineStream.atEnd()) {
                    writer.write(token);
                    writer.write(header);
                } else {
                    lineStream.skip(token.length());
                    writer.write("<h");
                    writer.write(String.valueOf(count));
                    writer.write(">");
                    writer.write(header);
                    writer.write("</h");
                    writer.write(String.valueOf(count));
                    writer.write(">");
                    cr = false;
                }
            } else if (!isMixed && firstWord && word.equals(":")) {
                span = true;
                int indent = 1;
                while (!lineStream.atEnd() && lineStream.peek() == ':') {
                    lineStream.skip();
                    indent++;
                }
                writer.write("<span style=\"display:inline-block;text-indent:");
                writer.write(String.valueOf(indent * 20));
                writer.write("px;\">");
            } else if (!isMixed && firstWord && word.equals("*")) {
                if (!bullet) {
                    writer.write("<ul>");
                    bullet = true;
                }
                writer.write("<li>");
                cr = false;
            } else if (!isMixed && firstWord && word.equals("#")) {
                if (!nbullet) {
                    writer.write("<ol>");
                    nbullet = true;
                }
                writer.write("<li>");
                cr = false;
            } else {
                writer.write(word);
            }
            firstWord = false;
        }
        if (!isMixed && span) {
            writer.write("</span>");
        }
        if (!isMixed && cr) {
            writer.write("<br/>\n");
        }
    }
    if (!isMixed && bullet) {
        writer.write("</ul>");
    }
    if (!isMixed && nbullet) {
        writer.write("</ol>");
    }
    return writer.toString();
}

From source file:com.espertech.esper.dataflow.core.DataFlowServiceImpl.java

private String toPrettyPrint(int operatorNum, GraphOperatorSpec spec) {
    StringWriter writer = new StringWriter();
    writer.write(spec.getOperatorName());
    writer.write("#");
    writer.write(Integer.toString(operatorNum));

    writer.write("(");
    String delimiter = "";
    for (GraphOperatorInputNamesAlias inputItem : spec.getInput().getStreamNamesAndAliases()) {
        writer.write(delimiter);// w  w w  .j av  a2s.  c o  m
        toPrettyPrintInput(inputItem, writer);
        if (inputItem.getOptionalAsName() != null) {
            writer.write(" as ");
            writer.write(inputItem.getOptionalAsName());
        }
        delimiter = ", ";
    }
    writer.write(")");

    if (spec.getOutput().getItems().isEmpty()) {
        return writer.toString();
    }
    writer.write(" -> ");

    delimiter = "";
    for (GraphOperatorOutputItem outputItem : spec.getOutput().getItems()) {
        writer.write(delimiter);
        writer.write(outputItem.getStreamName());
        writeTypes(outputItem.getTypeInfo(), writer);
        delimiter = ",";
    }

    return writer.toString();
}

From source file:com.espertech.esper.dataflow.core.DataFlowServiceImpl.java

private void writeTypes(List<GraphOperatorOutputItemType> types, StringWriter writer) {
    if (types.isEmpty()) {
        return;/*from   ww  w . j a  v a 2  s .  com*/
    }

    writer.write("<");
    String typeDelimiter = "";
    for (GraphOperatorOutputItemType type : types) {
        writer.write(typeDelimiter);
        writeType(type, writer);
        typeDelimiter = ",";
    }
    writer.write(">");
}

From source file:com.espertech.esper.dataflow.core.DataFlowServiceImpl.java

private void toPrettyPrintInput(GraphOperatorInputNamesAlias inputItem, StringWriter writer) {
    if (inputItem.getInputStreamNames().length == 1) {
        writer.write(inputItem.getInputStreamNames()[0]);
    } else {/*from   www  . j  a  v  a 2 s .c  o  m*/
        writer.write("(");
        String delimiterNames = "";
        for (String name : inputItem.getInputStreamNames()) {
            writer.write(delimiterNames);
            writer.write(name);
            delimiterNames = ",";
        }
        writer.write(")");
    }
}

From source file:net.sourceforge.doddle_owl.ui.InputDocumentSelectionPanel.java

public String getTargetHtmlLines(String word) {
    StringWriter writer = new StringWriter();
    writer.write("<html><body>");
    ListModel listModel = inputDocList.getModel();
    for (int i = 0; i < listModel.getSize(); i++) {
        Document doc = (Document) listModel.getElementAt(i);
        String text = doc.getText();
        StringBuilder buf = new StringBuilder();
        if (text != null) {
            String[] lines = text.split("\n");
            for (int j = 0; j < lines.length; j++) {
                String line = lines[j];
                if (line.matches(".*" + word + ".*")) {
                    line = line.replaceAll(word, "<b><font size=3 color=red>" + word + "</font></b>");
                    buf.append("<b><font size=3 color=navy>");
                    if (DODDLEConstants.LANG.equals("en")) {
                        buf.append(Translator.getTerm("LineMessage"));
                        buf.append(" ");
                        buf.append((j + 1));
                    } else {
                        buf.append((j + 1));
                        buf.append(Translator.getTerm("LineMessage"));
                    }//  w  ww .ja v  a  2s .  c om
                    buf.append(": </font></b>");
                    buf.append("<font size=3>");
                    buf.append(line);
                    buf.append("</font>");
                    buf.append("<br>");
                }
            }
        }
        if (0 < buf.toString().length()) {
            writer.write("<font size=3><b>" + doc.getFile().getAbsolutePath() + "</b></font><br>");
            writer.write(buf.toString());
        }
    }
    writer.write("</body></html>");
    return writer.toString();
}

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

private void doPutOrPostSinglepart(EntityEnclosingMethod method, XdmNode body) {
    // ATTENTION: This doesn't handle multipart, that's done entirely separately

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    // Check for consistency of content-type
    contentType = body.getAttributeValue(_content_type);
    if (contentType == null) {
        throw new XProcException(step.getNode(), "Content-type on c:body is required.");
    }//from   ww  w . j a  v a  2  s  . c om

    if (headerContentType != null && !headerContentType.equals(contentType.toLowerCase())) {
        throw XProcException.stepError(20);
    }

    for (Header header : headers) {
        method.addRequestHeader(header);
    }

    // FIXME: This sucks rocks. I want to write the data to be posted, not provide some way to read it
    String postContent = null;
    String encoding = body.getAttributeValue(_encoding);
    try {
        if ("base64".equals(encoding)) {
            String charset = body.getAttributeValue(_charset);
            // FIXME: is utf-8 the right default?
            if (charset == null) {
                charset = "utf-8";
            }
            String escapedContent = decodeBase64(body, charset);
            StringWriter writer = new StringWriter();
            writer.write(escapedContent);
            writer.close();
            postContent = writer.toString();
        } else {
            if (jsonContentType(contentType)) {
                postContent = XMLtoJSON.convert(body);
            } else if (xmlContentType(contentType)) {
                Serializer serializer = makeSerializer();

                if (!S9apiUtils.isDocumentContent(body.axisIterator(Axis.CHILD))) {
                    throw XProcException.stepError(22);
                }

                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();
                    if (node.getNodeKind() != XdmNodeKind.TEXT) {
                        throw XProcException.stepError(28);
                    }
                    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:de.csw.expertfinder.mediawiki.api.MediaWikiAPI.java

/**
 * Returns all child categories of the given category.
 * Works only for MediaWiki installations with the CategoryTree
 * extension installed (most of the public MediaWikis should have it
 * installed).//ww  w  . j  a v  a  2  s . co  m
 * @param category
 * @return
 */
public List<String> getChildCategories(String categoryName) throws MediaWikiAPIException {
    if (XPATH_CATEGORIES == null) {
        // should never happen
        throw new MediaWikiAPIException("XPath expression for getting categories not initialized");
    }
    //http://wiki.eclipse.org/index.php?action=ajax

    StringBuilder buf = new StringBuilder(ajaxURL);
    buf.append("&rs=efCategoryTreeAjaxWrapper&rsargs[]=");
    try {
        buf.append(URLEncoder.encode(categoryName.replace(' ', '_'), "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new MediaWikiAPIException("The UTF-8 character encoding is not supported on this platform.", e);
    }
    buf.append("&rsargs[]=0"); // mode = 0 (no parent categories, no pages). 

    HttpGet httpGet = new HttpGet(buf.toString());
    HttpResponse response;
    try {
        response = http.execute(httpGet);
    } catch (ClientProtocolException e) {
        throw new MediaWikiAPIException("Could not execute HTTP call to MediaWiki API", e);
    } catch (IOException e) {
        throw new MediaWikiAPIException("Could not execute HTTP call to MediaWiki API", e);
    }

    InputStream content;
    try {
        content = response.getEntity().getContent();
    } catch (IllegalStateException e) {
        throw new MediaWikiAPIException("Could not process response from call to MediaWiki API", e);
    } catch (IOException e) {
        throw new MediaWikiAPIException("Could not process response from call to MediaWiki API", e);
    }

    StringWriter out;
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(content));
        out = new StringWriter();
        String line;
        while ((line = in.readLine()) != null) {
            out.write(line + "\n");
        }
    } catch (IOException e) {
        throw new MediaWikiAPIException("Could not read response", e);
    }

    String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<categories>\n" + out.toString()
            + "\n</categories>";

    Document doc;

    try {
        doc = documentBuilder.parse(new StringInputStream(xml));
    } catch (SAXException e) {
        throw new MediaWikiAPIException("Error parsing xml document", e);
    } catch (IOException e) {
        throw new MediaWikiAPIException("Errror reading xml document", e);
    }

    NodeList childCategoryNodes;
    try {
        childCategoryNodes = (NodeList) XPATH_CATEGORIES.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new MediaWikiAPIException("Could not evaluate XPath expression " + XPATH_CATEGORIES
                + " on result of category name query for category " + categoryName);
    }

    ArrayList<String> childCategories = new ArrayList<String>();

    int length = childCategoryNodes.getLength();
    for (int i = 0; i < length; i++) {
        Node childCategoryNode = childCategoryNodes.item(i);
        String childCategoryName = childCategoryNode.getTextContent().trim();
        childCategories.add(childCategoryName);
    }

    return childCategories;
}

From source file:com.netspective.sparx.theme.basic.StandardDialogSkin.java

public void appendGridControlBasics(DialogContext dc, DialogField field, StringBuffer html) throws IOException {
    StringWriter controlHtml = new StringWriter();
    field.renderControlHtml(controlHtml, dc);
    String popupHtml = getPopupHtml(dc, field);
    if (popupHtml != null)
        controlHtml.write(popupHtml);

    if (field.isHelpAvailable())
        controlHtml.write("&nbsp;" + field.getHelpPanel().getDialogFieldHelpHtml(dc, getTheme()));

    if (field.getFlags().flagIsSet(DialogFieldFlags.CREATE_ADJACENT_AREA)) {
        String adjValue = dc.getFieldStates().getState(field).getAdjacentAreaValue();
        controlHtml.write("&nbsp;<span id='" + field.getQualifiedName() + "_adjacent'>"
                + (adjValue != null ? adjValue : "") + "</span>");
    }/*from   w  ww .j  a v  a  2  s.c  o  m*/

    StringBuffer messagesHtml = new StringBuffer();
    String hint = field.getHint().getTextValue(dc);
    if (hint != null) {
        messagesHtml.append("<br><font " + hintFontAttrs + ">");
        messagesHtml.append(hint);
        messagesHtml.append("</font>");
    }

    html.append("<font ");
    html.append(controlAreaFontAttrs);
    html.append(">");
    html.append(controlHtml);
    if (messagesHtml.length() > 0)
        html.append(messagesHtml);
    html.append("</font>");
}