Example usage for java.io StringWriter getBuffer

List of usage examples for java.io StringWriter getBuffer

Introduction

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

Prototype

public StringBuffer getBuffer() 

Source Link

Document

Return the string buffer itself.

Usage

From source file:com.redhat.rhn.frontend.taglibs.list.ListTag.java

private int doAfterBodyRenderFooterAddons() throws JspException {
    ListTagUtil.write(pageContext, "</table>");
    ListTagUtil.setCurrentCommand(pageContext, getUniqueName(), ListCommand.TBL_FOOTER);

    // as the footer addons are populated with decorators, we don't
    // know if there will be content or not, but we want to avoid
    // writing the tfoot tag at all if there is none, so we push a
    // buffer into the stack, and empty it later.
    StringWriter footAddonsContent = new StringWriter();
    StringWriter footLinksContent = new StringWriter();
    StringWriter footExtraContent = new StringWriter();

    pageContext.pushBody(footAddonsContent);
    if (!manip.isListEmpty()) {
        for (ListDecorator dec : getDecorators()) {
            dec.onFooterExtraAddons();//www .j a v a2  s  .  c o  m
        }
    }
    pageContext.popBody();

    pageContext.pushBody(footExtraContent);
    if (!manip.isListEmpty()) {
        for (ListDecorator dec : getDecorators()) {
            dec.onFooterExtraContent();
        }
    }
    pageContext.popBody();

    pageContext.pushBody(footLinksContent);
    // if there is reference links, put them as a panel footer
    if ((refLink != null) && (!isEmpty())) {

        ListTagUtil.write(pageContext, "<a href=\"" + refLink + "\" >");
        /* Here we render the reflink and its key. If the key hasn't been set
         * we just display the link address itself.
         */
        if (refLinkKey != null) {
            Object[] args = new Object[2];
            args[0] = new Integer(getPageRowCount());
            args[1] = refLinkKeyArg0;
            String message = LocalizationService.getInstance().getMessage(refLinkKey, args);

            ListTagUtil.write(pageContext, message);
        } else {
            ListTagUtil.write(pageContext, refLink);
        }

        ListTagUtil.write(pageContext, "</a>");
    }
    pageContext.popBody();

    int footerContentLength = footLinksContent.getBuffer().length() + footAddonsContent.getBuffer().length()
            + footExtraContent.getBuffer().length();

    if (footerContentLength > 0) {
        ListTagUtil.write(pageContext, "<div class=\"panel-footer\">");
        ListTagUtil.write(pageContext, "<div class=\"spacewalk-list-footer-addons\">");
        ListTagUtil.write(pageContext, "<div class=\"spacewalk-list-reflinks\">");
        ListTagUtil.write(pageContext, footLinksContent.toString());
        ListTagUtil.write(pageContext, "</div>");
        ListTagUtil.write(pageContext, "<div class=\"spacewalk-list-footer-addons-extra\">");
        ListTagUtil.write(pageContext, footAddonsContent.toString());
        ListTagUtil.write(pageContext, "</div>");
        ListTagUtil.write(pageContext, "</div>");
        ListTagUtil.write(pageContext, "<div class=\"spacewalk-list-footer-extra\">");
        ListTagUtil.write(pageContext, footExtraContent.toString());
        ListTagUtil.write(pageContext, "</div>");
        // closes the panel footer
        ListTagUtil.write(pageContext, "</div>");
    }

    // close the panel
    ListTagUtil.write(pageContext, "</div>");

    ListTagUtil.write(pageContext, "<div class=\"spacewalk-list-bottom-addons\">");
    renderFooterPaginationControls();
    ListTagUtil.write(pageContext, "<div class=\"spacewalk-list-bottom-addons-extra\">");
    if (!isEmpty()) {
        for (ListDecorator dec : getDecorators()) {
            dec.onBottomExtraAddons();
        }
    }
    ListTagUtil.write(pageContext, "</div>");
    ListTagUtil.write(pageContext, "</div>");
    ListTagUtil.write(pageContext, "<div class=\"spacewalk-list-bottom-addons-extra\">");
    if (!isEmpty()) {
        for (ListDecorator dec : getDecorators()) {
            dec.onBottomExtraContent();
        }
    }
    ListTagUtil.write(pageContext, "</div>");
    // we render the hidden fields outside of the table
    if (isSortable()) {
        renderSortableHiddenFields();
    }
    // close list
    ListTagUtil.write(pageContext, "</div>");
    return BodyTagSupport.SKIP_BODY;
}

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

public void appendFieldHtml(DialogContext dc, DialogField field, StringBuffer fieldsHtml,
        StringBuffer fieldsJSDefn, List fieldErrorMsgs) throws IOException {
    if (field.isInputHidden(dc)) {
        StringWriter writer = new StringWriter();
        field.renderControlHtml(writer, dc);
        fieldsHtml.append(writer);/*  ww w.  j  av  a2s  .  c  om*/
        // even if the field is hidden, you still need to register it in JS
        if (field.getName() != null)
            fieldsJSDefn.append(field.getJavaScriptDefn(dc));
        return;
    }

    String caption = field.getCaption().getTextValue(dc);
    DialogFields fieldChildren = field.getChildren();
    if (caption != null && fieldChildren != null && caption.equals(DialogField.GENERATE_CAPTION)) {
        StringBuffer generated = new StringBuffer();
        for (int i = 0; i < fieldChildren.size(); i++) {
            DialogField childField = fieldChildren.get(i);
            String childCaption = childField.getCaption().getTextValue(dc);
            if (childCaption != null && childCaption != DialogField.CUSTOM_CAPTION) {
                if (generated.length() > 0)
                    generated.append(" / ");
                generated.append(childField.isRequired(dc) ? "<b>" + childCaption + "</b>" : childCaption);
            }
        }
        caption = generated.toString();
    } else {
        if (caption != null && field.isRequired(dc))
            caption = "<b>" + caption + "</b>";
    }

    if (captionSuffix != null && caption != null && caption.length() > 0)
        caption += captionSuffix;

    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()));

    DialogField.State state = dc.getFieldStates().getState(field);
    DialogFieldFlags stateFlags = state.getStateFlags();

    if (stateFlags.flagIsSet(DialogFieldFlags.CREATE_ADJACENT_AREA)) {
        String adjValue = state.getAdjacentAreaValue();
        controlHtml.write("&nbsp;<span id='" + field.getQualifiedName() + "_adjacent'>"
                + (adjValue != null ? adjValue : "") + "</span>");
    }

    boolean haveErrors = false;
    StringBuffer messagesHtml = null;
    List errorMessages = dc.getValidationContext()
            .getValidationErrorsForScope(state.getValidationContextScope());
    if (errorMessages.size() > 0) {
        messagesHtml = new StringBuffer();
        messagesHtml.append("<font " + errorMsgFontAttrs + ">");
        for (int i = 0; i < errorMessages.size(); i++) {
            String msgStr = (String) errorMessages.get(i);
            fieldErrorMsgs.add(msgStr);
            if (i > 0)
                messagesHtml.append("<br>");
            messagesHtml.append("<a name='dc_error_msg_" + i + "'>" + msgStr + "</a>");
        }
        messagesHtml.append("</font>");
        haveErrors = true;
    }

    String hintHtml = "";
    if (controlHtml.getBuffer().length() > 0) {
        // only show the hint when there is an input field!
        String hint = field.getHint().getTextValue(dc);
        if (hint != null) {
            DialogFlags dialogFlags = dc.getDialog().getDialogFlags();
            if ((field.isReadOnly(dc) && dialogFlags.flagIsSet(DialogFlags.HIDE_READONLY_HINTS))) {
                hintHtml = "";
            } else if (dialogFlags.flagIsSet(DialogFlags.HIDE_HINTS_UNTIL_FOCUS)) {
                // hide the hints until the field is being edited
                hintHtml = "<br><span id=\"" + field.getQualifiedName()
                        + "_hint\" class=\"dialog-fields-hint-hidden\">&nbsp;&nbsp;&nbsp;" + hint + "</span>";
            } else {
                hintHtml = "<br><span id=\"" + field.getQualifiedName()
                        + "_hint\" class=\"dialog-fields-hint\">&nbsp;&nbsp;&nbsp;" + hint + "</span>";
            }
        }
    }

    /*
    * each field row gets its own ID so DHTML can hide/show the row
    */

    String rowAttr = fieldRowAttrs + " id='" + FIELDROW_PREFIX + field.getQualifiedName() + "' ";
    if (haveErrors)
        rowAttr = rowAttr + fieldRowErrorAttrs;

    if (caption == null) {
        if (field instanceof SeparatorField)
            fieldsHtml.append("<tr" + rowAttr + "><td class=\"dialog-fields-separator\" colspan='2'>"
                    + controlHtml + "</td></tr>\n");
        else
            fieldsHtml.append("<tr" + rowAttr + "><td colspan='2'>" + controlHtml + hintHtml + "</td></tr>\n");

        if (haveErrors)
            fieldsHtml.append("<tr><td><span class=\"dialog-fields-errors\">&nbsp;&nbsp;&nbsp;" + messagesHtml
                    + "</span></td></tr>\n");
    } else {
        String accessKey = field.getAccessKey();
        if (accessKey != null && accessKey.length() > 0) {
            int accessKeyPos = caption.toLowerCase().indexOf(accessKey.toLowerCase());
            if (accessKeyPos > 0 && accessKeyPos < caption.length() - 1) {
                fieldsHtml.append("<tr " + rowAttr + "><td " + getCaptionClass() + "><label for=\""
                        + field.getHtmlFormControlId() + "\" accesskey=\"" + field.getAccessKey() + "\">"
                        + caption.substring(0, accessKeyPos) + "<span class=\"accesskey\">"
                        + caption.substring(accessKeyPos, accessKeyPos + 1) + "</span>"
                        + caption.substring(accessKeyPos + 1) + "</label></td>" + "<td " + getControlAreaClass()
                        + ">" + controlHtml + hintHtml + "</td></tr>\n");
            } else if (accessKeyPos == caption.length() - 1) {
                fieldsHtml.append("<tr " + rowAttr + "><td " + getCaptionClass() + "><label for=\""
                        + field.getHtmlFormControlId() + "\" accesskey=\"" + field.getAccessKey() + "\">"
                        + caption.substring(0, accessKeyPos) + "<span class=\"accesskey\">"
                        + caption.substring(accessKeyPos) + "</span></label></td>" + "<td "
                        + getControlAreaClass() + ">" + controlHtml + hintHtml + "</td></tr>\n");
            } else if (accessKeyPos == 0) {
                fieldsHtml.append("<tr " + rowAttr + "><td " + getCaptionClass() + "><label for=\""
                        + field.getHtmlFormControlId() + "\" accesskey=\"" + field.getAccessKey() + "\">"
                        + "<span class=\"accesskey\">" + caption.substring(0, 1) + "</span>"
                        + caption.substring(1) + "</label></td>" + "<td " + getControlAreaClass() + ">"
                        + controlHtml + hintHtml + "</td></tr>\n");
            } else {
                fieldsHtml.append("<tr " + rowAttr + "><td " + getCaptionClass() + ">" + caption + "</td>"
                        + "<td " + getControlAreaClass() + ">" + controlHtml + hintHtml + "</td></tr>\n");
            }
        } else if (caption.length() > 0) {
            fieldsHtml.append("<tr" + rowAttr + "><td " + getCaptionClass() + ">" + "<label for=\""
                    + field.getHtmlFormControlId() + "\">" + caption + "</label></td>" + "<td "
                    + getControlAreaClass() + ">" + controlHtml + hintHtml + "</td></tr>\n");
        } else {
            fieldsHtml.append("<tr" + rowAttr + "><td>&nbsp;</td>" + "<td " + getControlAreaClass() + ">"
                    + controlHtml + hintHtml + "</td></tr>\n");
        }

        if (haveErrors)
            fieldsHtml.append(
                    "<tr><td>&nbsp;</td><td>" + "<span class=\"dialog-fields-errors\">&nbsp;&nbsp;&nbsp;"
                            + messagesHtml + "</span></td></tr>\n");
    }

    if (field.getName() != null)
        fieldsJSDefn.append(field.getJavaScriptDefn(dc));
}

From source file:com.flexive.core.storage.genericSQL.GenericHierarchicalStorage.java

/**
 * Run tidy on the given content/*from  w ww  . j  a va  2s .co  m*/
 *
 * @param XPath   XPath with full indices for error messages
 * @param content the string to tidy
 * @return tidied string
 * @throws FxUpdateException if tidy failed
 */
protected static String doTidy(String XPath, String content) throws FxUpdateException {
    Tidy tidy = new Tidy();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    tidy.setDropEmptyParas(true);
    tidy.setMakeClean(true);
    tidy.setHideEndTags(true);
    tidy.setTidyMark(false);
    tidy.setMakeBare(true);
    tidy.setXHTML(true);
    //        tidy.setOnlyErrors(true);
    tidy.setShowWarnings(false);
    tidy.setQuiet(true);
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    tidy.setErrout(pw);
    tidy.parse(new StringReader(content), out);

    if (tidy.getParseErrors() > 0) {
        String error = sw.getBuffer().toString();
        throw new FxUpdateException("ex.content.value.tidy.failed", XPath, error);
    }
    content = out.toString();
    return content;
}

From source file:edu.jhu.pha.vospace.node.Node.java

public String getXmlMetadata(Detail detail) {

    StringWriter jobWriter = new StringWriter();
    try {// www  .  j a va  2  s.c  o m
        XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(jobWriter);
        xsw.writeStartDocument();

        xsw.setDefaultNamespace(VOS_NAMESPACE);

        xsw.writeStartElement("node");
        xsw.writeNamespace("xsi", XSI_NAMESPACE);
        xsw.writeNamespace(null, VOS_NAMESPACE);
        xsw.writeAttribute("xsi:type", this.getType().getTypeName());
        xsw.writeAttribute("uri", this.getUri().toString());

        if (detail == Detail.max) {
            xsw.writeStartElement("properties");
            Map<String, String> properties = this.getMetastore().getProperties(this.getUri());
            properties.put(LENGTH_PROPERTY, Long.toString(getNodeInfo().getSize()));
            properties.put(DATE_PROPERTY, dropboxDateFormat.format(getNodeInfo().getMtime()));
            if (this.getType() == NodeType.DATA_NODE || this.getType() == NodeType.STRUCTURED_DATA_NODE
                    || this.getType() == NodeType.UNSTRUCTURED_DATA_NODE) {
                properties.put(CONTENTTYPE_PROPERTY, getNodeInfo().getContentType());
            }

            for (String propUri : properties.keySet()) {
                xsw.writeStartElement("property");
                xsw.writeAttribute("uri", propUri);
                xsw.writeCharacters(properties.get(propUri));
                xsw.writeEndElement();
            }

            xsw.writeEndElement();

            xsw.writeStartElement("accepts");
            xsw.writeEndElement();

            xsw.writeStartElement("provides");
            xsw.writeEndElement();

            xsw.writeStartElement("capabilities");
            xsw.writeEndElement();

            if (this.getType() == NodeType.CONTAINER_NODE) {
                NodesList childrenList = ((ContainerNode) this).getDirectChildren(false, 0, -1);
                List<Node> children = childrenList.getNodesList();

                xsw.writeStartElement("nodes");
                for (Node childNode : children) {
                    xsw.writeStartElement("node");
                    xsw.writeAttribute("uri", childNode.getUri().getId().toString());
                    xsw.writeEndElement();
                }
                xsw.writeEndElement();

            }

        }

        xsw.writeEndElement();

        xsw.writeEndDocument();
        xsw.close();
    } catch (XMLStreamException e) {
        e.printStackTrace();
        throw new InternalServerErrorException(e);
    }
    return jobWriter.getBuffer().toString();
}

From source file:net.sf.reportengine.core.steps.TestDataRowsOutputStep.java

@Test
public void testExecuteScenario1() {
    DataRowsOutputStep classUnderTest = new DataRowsOutputStep();

    AlgoContext reportContext = new DefaultAlgorithmContext();
    Map<AlgoIOKeys, Object> mockAlgoInput = new EnumMap<AlgoIOKeys, Object>(AlgoIOKeys.class);

    StringWriter testWriter = new StringWriter();
    MockReportOutput mockOutput = new MockReportOutput(testWriter);

    reportContext.set(StepIOKeys.LOCAL_REPORT_INPUT, Scenario1.INPUT);
    //reportContext.set(ContextKeys.NEW_LOCAL_REPORT_OUTPUT, mockOutput); 

    mockAlgoInput.put(AlgoIOKeys.DATA_COLS, Scenario1.DATA_COLUMNS);
    mockAlgoInput.put(AlgoIOKeys.GROUP_COLS, Scenario1.GROUPING_COLUMNS);
    mockAlgoInput.put(AlgoIOKeys.NEW_REPORT_OUTPUT, mockOutput);

    reportContext.set(StepIOKeys.DATA_ROW_COUNT, 0);
    classUnderTest.init(new StepInput(mockAlgoInput, reportContext));

    NewRowEvent dataRowEvent = new NewRowEvent(Scenario1.ROW_OF_DATA_1);
    StepResult<Integer> stepResult = classUnderTest.execute(dataRowEvent,
            new StepInput(mockAlgoInput, reportContext));

    Assert.assertNotNull(stepResult);// w w w. j  a va 2  s. co m
    Assert.assertEquals(NumberUtils.INTEGER_ONE, stepResult.getValue()); //(ContextKeys.DATA_ROW_COUNT));
    reportContext.set(StepIOKeys.DATA_ROW_COUNT, stepResult.getValue());

    dataRowEvent = new NewRowEvent(Scenario1.ROW_OF_DATA_2);
    stepResult = classUnderTest.execute(dataRowEvent, new StepInput(mockAlgoInput, reportContext));

    Assert.assertNotNull(stepResult);
    Assert.assertEquals(Integer.valueOf(2), stepResult.getValue());
    reportContext.set(StepIOKeys.DATA_ROW_COUNT, stepResult.getValue());

    dataRowEvent = new NewRowEvent(Scenario1.ROW_OF_DATA_3);
    stepResult = classUnderTest.execute(dataRowEvent, new StepInput(mockAlgoInput, reportContext));

    Assert.assertNotNull(stepResult);
    Assert.assertEquals(Integer.valueOf(3), stepResult.getValue());
    reportContext.set(StepIOKeys.DATA_ROW_COUNT, stepResult.getValue());

    dataRowEvent = new NewRowEvent(Scenario1.ROW_OF_DATA_4);
    stepResult = classUnderTest.execute(dataRowEvent, new StepInput(mockAlgoInput, reportContext));

    Assert.assertNotNull(stepResult);
    Assert.assertEquals(Integer.valueOf(4), stepResult.getValue());
    reportContext.set(StepIOKeys.DATA_ROW_COUNT, stepResult.getValue());

    dataRowEvent = new NewRowEvent(Scenario1.ROW_OF_DATA_5);
    stepResult = classUnderTest.execute(dataRowEvent, new StepInput(mockAlgoInput, reportContext));

    Assert.assertNotNull(stepResult);
    Assert.assertEquals(Integer.valueOf(5), stepResult.getValue());
    reportContext.set(StepIOKeys.DATA_ROW_COUNT, stepResult.getValue());

    dataRowEvent = new NewRowEvent(Scenario1.ROW_OF_DATA_6);
    stepResult = classUnderTest.execute(dataRowEvent, new StepInput(mockAlgoInput, reportContext));

    Assert.assertNotNull(stepResult);
    Assert.assertEquals(Integer.valueOf(6), stepResult.getValue());
    reportContext.set(StepIOKeys.DATA_ROW_COUNT, stepResult.getValue());

    //CellProps[][] resultCellMatrix = Scenario1.OUTPUT.getDataCellMatrix();
    //Assert.assertTrue(MatrixUtils.compareMatrices(Scenario1.EXPECTED_OUTPUT_DATA, resultCellMatrix));
    System.out.println(testWriter.getBuffer());
}

From source file:org.apache.axis.client.Call.java

/**
 * Invoke this Call with its established MessageContext
 * (perhaps because you called this.setRequestMessage())
 *
 * Note: Not part of JAX-RPC specification.
 *
 * @exception AxisFault//from w  w w  .ja  v  a2  s  . c  o m
 */
public void invoke() throws AxisFault {
    if (log.isDebugEnabled()) {
        log.debug("Enter: Call::invoke()");
    }

    isNeverInvoked = false;

    Message reqMsg = null;
    SOAPEnvelope reqEnv = null;

    msgContext.reset();
    msgContext.setResponseMessage(null);
    msgContext.setProperty(MessageContext.CALL, this);
    msgContext.setProperty(WSDL_SERVICE, service);
    msgContext.setProperty(WSDL_PORT_NAME, getPortName());
    if (isMsg) {
        msgContext.setProperty(MessageContext.IS_MSG, "true");
    }

    if (username != null) {
        msgContext.setUsername(username);
    }
    if (password != null) {
        msgContext.setPassword(password);
    }
    msgContext.setMaintainSession(maintainSession);

    if (operation != null) {
        msgContext.setOperation(operation);
        operation.setStyle(getOperationStyle());
        operation.setUse(getOperationUse());
    }

    if (useSOAPAction) {
        msgContext.setUseSOAPAction(true);
    }
    if (SOAPActionURI != null) {
        msgContext.setSOAPActionURI(SOAPActionURI);
    } else {
        msgContext.setSOAPActionURI(null);
    }
    if (timeout != null) {
        msgContext.setTimeout(timeout.intValue());
    }
    msgContext.setHighFidelity(!useStreaming);

    // Determine client target service
    if (myService != null) {
        // If we have a SOAPService kicking around, use that directly
        msgContext.setService(myService);
    } else {
        if (portName != null) {
            // No explicit service.  If we have a target service name,
            // try that.
            msgContext.setTargetService(portName.getLocalPart());
        } else {
            // No direct config, so try the namespace of the first body.
            reqMsg = msgContext.getRequestMessage();

            boolean isStream = ((SOAPPart) reqMsg.getSOAPPart()).isBodyStream();

            if (reqMsg != null && !isStream) {
                reqEnv = reqMsg.getSOAPEnvelope();

                SOAPBodyElement body = reqEnv.getFirstBody();

                if (body != null) {
                    if (body.getNamespaceURI() == null) {
                        throw new AxisFault("Call.invoke", Messages.getMessage("cantInvoke00", body.getName()),
                                null, null);
                    } else {
                        msgContext.setTargetService(body.getNamespaceURI());
                    }
                }
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("targetService", msgContext.getTargetService()));
    }

    Message requestMessage = msgContext.getRequestMessage();
    if (requestMessage != null) {
        try {
            msgContext.setProperty(SOAPMessage.CHARACTER_SET_ENCODING,
                    requestMessage.getProperty(SOAPMessage.CHARACTER_SET_ENCODING));
        } catch (SOAPException e) {
        }

        if (myHeaders != null) {
            reqEnv = requestMessage.getSOAPEnvelope();

            // If we have headers to insert, do so now.
            for (int i = 0; myHeaders != null && i < myHeaders.size(); i++) {
                reqEnv.addHeader((SOAPHeaderElement) myHeaders.get(i));
            }
        }
    }

    // set up transport if there is one
    if (transport != null) {
        transport.setupMessageContext(msgContext, this, service.getEngine());
    } else {
        msgContext.setTransportName(transportName);
    }

    SOAPService svc = msgContext.getService();
    if (svc != null) {
        svc.setPropertyParent(myProperties);
    } else {
        msgContext.setPropertyParent(myProperties);
    }

    // For debugging - print request message
    if (log.isDebugEnabled()) {
        StringWriter writer = new StringWriter();
        try {
            SerializationContext ctx = new SerializationContext(writer, msgContext);
            requestMessage.getSOAPEnvelope().output(ctx);
            writer.close();
        } catch (Exception e) {
            throw AxisFault.makeFault(e);
        } finally {
            log.debug(writer.getBuffer().toString());
        }
    }

    if (!invokeOneWay) {
        invokeEngine(msgContext);
    } else {
        invokeEngineOneWay(msgContext);
    }

    if (log.isDebugEnabled()) {
        log.debug("Exit: Call::invoke()");
    }
}

From source file:org.apache.maven.plugin.javadoc.AbstractFixJavadocMojo.java

/**
 * @param stringWriter    not null//from  w  w  w  .ja v  a2s. c om
 * @param originalContent not null
 * @param entity          not null
 * @param indent          not null
 * @throws MojoExecutionException if any
 * @throws IOException            if any
 */
private void updateEntityComment(final StringWriter stringWriter, final String originalContent,
        final AbstractInheritableJavaEntity entity, final String indent)
        throws MojoExecutionException, IOException {
    String s = stringWriter.toString();
    int i = s.lastIndexOf(START_JAVADOC);
    if (i != -1) {
        String tmp = s.substring(0, i);
        if (tmp.lastIndexOf(EOL) != -1) {
            tmp = tmp.substring(0, tmp.lastIndexOf(EOL));
        }
        stringWriter.getBuffer().delete(0, stringWriter.getBuffer().length());
        stringWriter.write(tmp);
        stringWriter.write(EOL);
    }

    updateJavadocComment(stringWriter, originalContent, entity, indent);
}

From source file:edu.umn.msi.tropix.webgui.server.UploadController.java

@ServiceMethod(secure = true)
public ModelAndView handleRequest(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {
    LOG.debug("In UploadController.handleRequest");
    //final String userId = securityProvider.getUserIdForSessionId(request.getParameter("sessionId"));
    //Preconditions.checkState(userId != null);
    final String userId = userSession.getGridId();
    LOG.debug("Upload by user with id " + userId);
    String clientId = request.getParameter("clientId");
    if (!StringUtils.hasText(clientId)) {
        clientId = UUID.randomUUID().toString();
    }//from w ww  .  ja  va  2s  . c o m
    final String endStr = request.getParameter("end");
    final String startStr = request.getParameter("start");
    final String zipStr = request.getParameter("zip");

    final String lastUploadStr = request.getParameter("lastUpload");
    final boolean isZip = StringUtils.hasText("zip") ? Boolean.parseBoolean(zipStr) : false;
    final boolean lastUploads = StringUtils.hasText(lastUploadStr) ? Boolean.parseBoolean(lastUploadStr) : true;

    LOG.trace("Upload request with startStr " + startStr);
    final StringWriter rawJsonWriter = new StringWriter();
    final JSONWriter jsonWriter = new JSONWriter(rawJsonWriter);
    final FileItemFactory factory = new DiskFileItemFactory();

    final long requestLength = StringUtils.hasText(endStr) ? Long.parseLong(endStr)
            : request.getContentLength();
    long bytesWritten = StringUtils.hasText(startStr) ? Long.parseLong(startStr) : 0L;

    final ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8"); // Deal with international file names
    final FileItemIterator iter = upload.getItemIterator(request);

    // Setup message conditionalSampleComponent to track upload progress...
    final ProgressMessageSupplier supplier = new ProgressMessageSupplier();
    supplier.setId(userId + "/" + clientId);
    supplier.setName("Upload File(s) to Web Application");

    final ProgressTrackerImpl progressTracker = new ProgressTrackerImpl();
    progressTracker.setUserGridId(userId);
    progressTracker.setCometPusher(cometPusher);
    progressTracker.setProgressMessageSupplier(supplier);

    jsonWriter.object();
    jsonWriter.key("result");
    jsonWriter.array();

    while (iter.hasNext()) {
        final FileItemStream item = iter.next();
        if (item.isFormField()) {
            continue;
        }
        File destination;
        InputStream inputStream = null;
        OutputStream outputStream = null;

        if (!isZip) {
            final String fileName = FilenameUtils.getName(item.getName()); // new File(item.getName()).getName();
            LOG.debug("Handling upload of file with name " + fileName);

            final TempFileInfo info = tempFileStore.getTempFileInfo(fileName);
            recordJsonInfo(jsonWriter, info);
            destination = info.getTempLocation();
        } else {
            destination = FILE_UTILS.createTempFile();
        }

        try {
            inputStream = item.openStream();
            outputStream = FILE_UTILS.getFileOutputStream(destination);
            bytesWritten += progressTrackingIoUtils.copy(inputStream, outputStream, bytesWritten, requestLength,
                    progressTracker);

            if (isZip) {
                ZipUtilsFactory.getInstance().unzip(destination, new Function<String, File>() {
                    public File apply(final String fileName) {
                        final String cleanedUpFileName = FilenameUtils.getName(fileName);
                        final TempFileInfo info = tempFileStore.getTempFileInfo(cleanedUpFileName);
                        recordJsonInfo(jsonWriter, info);
                        return info.getTempLocation();
                    }
                });
            }
        } finally {
            IO_UTILS.closeQuietly(inputStream);
            IO_UTILS.closeQuietly(outputStream);
            if (isZip) {
                FILE_UTILS.deleteQuietly(destination);
            }
        }
    }
    if (lastUploads) {
        progressTracker.complete();
    }
    jsonWriter.endArray();
    jsonWriter.endObject();
    // response.setStatus(200);
    final String json = rawJsonWriter.getBuffer().toString();
    LOG.debug("Upload json response " + json);
    response.setContentType("text/html"); // GWT was attaching <pre> tag to result without this
    response.getOutputStream().println(json);
    return null;
}

From source file:edu.cornell.med.icb.goby.stats.TestAnnotationAveragingWriter.java

@Test
public void testCase9() {
    // test multiple samples, 4 groups, 3 comparisons
    // Test multiple samples, multiple groups, one comparison
    String[] groups = new String[] { "group1", "group2", "group3", "group4" };
    String[] samples = new String[] { "sample1", "sample2", "sample3", "sample4" };
    int[] positions = new int[] { 6, 8, 14, 16 };
    int[][] C = { { 5, 3, 9, 8 }, { 4, 6, 3, 2 }, { 8, 3, 8, 9 }, { 7, 4, 9, 7 } };
    int[][] Cm = { { 9, 7, 1, 5 }, { 9, 7, 9, 3 }, { 2, 3, 2, 8 }, { 4, 1, 3, 6 } };
    testSupport = new MethylCountProviderTestSupport(groups, samples, positions, "Case4", C, Cm);
    final StringWriter stringWriter = new StringWriter();
    AnnotationAveragingWriter testWriter = new AnnotationAveragingWriter(stringWriter, genome, testSupport);
    testWriter.setWriteNumSites(false);//from   w  ww. j a v a  2s. c  om
    testWriter.setContexts(DEFAULT_TEST_CONTEXTS);
    testWriter.setAnnotationFilename("test-data/vcf-averaging/annotations-1.tsv");
    int[] a = { 0, 1, 2, 3 };
    testWriter.setSampleIndexToGroupIndex(a);
    ArrayList<GroupComparison> groupComparisons = new ArrayList<GroupComparison>();
    GroupComparison comparisonToMake = new GroupComparison("group1", "group2", 0, 1, 0);
    groupComparisons.add(comparisonToMake);
    comparisonToMake = new GroupComparison("group1", "group3", 0, 2, 1);
    groupComparisons.add(comparisonToMake);
    comparisonToMake = new GroupComparison("group1", "group4", 0, 3, 2);
    groupComparisons.add(comparisonToMake);
    testWriter.setGroupComparisons(groupComparisons);
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.writeRecord();
    testWriter.close();
    assertEquals("Test Case 9 result: ",
            "Chromosome\tStart\tEnd\tFeature\tMR[sample1][CpG]\tMR[sample2][CpG]\tMR[sample3][CpG]\tMR[sample4][CpG]\tMR[sample1][CpA]\tMR[sample2][CpA]\tMR[sample3][CpA]\tMR[sample4][CpA]\tMR[sample1][CpC]\tMR[sample2][CpC]\tMR[sample3][CpC]\tMR[sample4][CpC]\tMR[sample1][CpT]\tMR[sample2][CpT]\tMR[sample3][CpT]\tMR[sample4][CpT]\tMR[sample1][CpN]\tMR[sample2][CpN]\tMR[sample3][CpN]\tMR[sample4][CpN]\tMR[group1][CpG]\tMR[group2][CpG]\tMR[group3][CpG]\tMR[group4][CpG]\tMR[group1][CpA]\tMR[group2][CpA]\tMR[group3][CpA]\tMR[group4][CpA]\tMR[group1][CpC]\tMR[group2][CpC]\tMR[group3][CpC]\tMR[group4][CpC]\tMR[group1][CpT]\tMR[group2][CpT]\tMR[group3][CpT]\tMR[group4][CpT]\tMR[group1][CpN]\tMR[group2][CpN]\tMR[group3][CpN]\tMR[group4][CpN]\tfisherP[group1/group2][CpG]\tfisherP[group1/group3][CpG]\tfisherP[group1/group4][CpG]\tfisherP[group1/group2][CpA]\tfisherP[group1/group3][CpA]\tfisherP[group1/group4][CpA]\tfisherP[group1/group2][CpC]\tfisherP[group1/group3][CpC]\tfisherP[group1/group4][CpC]\tfisherP[group1/group2][CpT]\tfisherP[group1/group3][CpT]\tfisherP[group1/group4][CpT]\tfisherP[group1/group2][CpN]\tfisherP[group1/group3][CpN]\tfisherP[group1/group4][CpN]\tdeltaMR[group1/group2][CpG]\tdeltaMR[group1/group3][CpG]\tdeltaMR[group1/group4][CpG]\tdeltaMR[group1/group2][CpA]\tdeltaMR[group1/group3][CpA]\tdeltaMR[group1/group4][CpA]\tdeltaMR[group1/group2][CpC]\tdeltaMR[group1/group3][CpC]\tdeltaMR[group1/group4][CpC]\tdeltaMR[group1/group2][CpT]\tdeltaMR[group1/group3][CpT]\tdeltaMR[group1/group4][CpT]\tdeltaMR[group1/group2][CpN]\tdeltaMR[group1/group3][CpN]\tdeltaMR[group1/group4][CpN]\n"
                    + "Case4\t5\t9\tannotation7\t\t\t\t\t\t\t\t\t\t\t\t\t66.67\t61.54\t31.25\t31.25\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t66.67\t61.54\t31.25\t31.25\t\t\t\t\t1.000\t1.000\t1.000\t1.000\t1.000\t1.000\t1.000\t1.000\t1.000\t0.7737\t0.05148\t0.05148\t1.000\t1.000\t1.000\t\t\t\t\t\t\t\t\t\t5.128\t35.42\t35.42\t\t\t\n"
                    + "Case4\t13\t17\tannotation8\t\t\t\t\t26.09\t70.59\t37.04\t36.00\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t26.09\t70.59\t37.04\t36.00\t\t\t\t\t\t\t\t\t\t\t\t\t1.000\t1.000\t1.000\t0.009521\t0.5456\t0.5419\t1.000\t1.000\t1.000\t1.000\t1.000\t1.000\t1.000\t1.000\t1.000\t\t\t\t44.50\t10.95\t9.913\t\t\t\t\t\t\t\t\t\n",
            stringWriter.getBuffer().toString());

}

From source file:edu.vt.middleware.servlet.filter.RequestDumperFilter.java

/** {@inheritDoc} */
@SuppressWarnings(value = "unchecked")
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    if (this.config == null) {
        return;/*www  .j av a2  s  .  c  om*/
    }

    // Just pass through to next filter if we're not at TRACE level
    if (!logger.isTraceEnabled()) {
        chain.doFilter(request, response);
        return;
    }

    // Create a variable to hold the (possibly different) request
    // passed to downstream filters
    ServletRequest downstreamRequest = request;

    // Render the generic servlet request properties
    final StringWriter sw = new StringWriter();
    final PrintWriter writer = new PrintWriter(sw);
    writer.println("Dumping request...");
    writer.println("-----------------------------------------------------");
    writer.println("REQUEST received " + Calendar.getInstance().getTime());
    writer.println(" characterEncoding=" + request.getCharacterEncoding());
    writer.println("     contentLength=" + request.getContentLength());
    writer.println("       contentType=" + request.getContentType());
    writer.println("            locale=" + request.getLocale());
    writer.print("           locales=");

    final Enumeration<Locale> locales = request.getLocales();
    for (int i = 0; locales.hasMoreElements(); i++) {
        if (i > 0) {
            writer.print(", ");
        }
        writer.print(locales.nextElement());
    }
    writer.println();

    final Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        final String name = paramNames.nextElement();
        writer.print("         parameter=" + name + "=");

        final String[] values = request.getParameterValues(name);
        for (int i = 0; i < values.length; i++) {
            if (i > 0) {
                writer.print(", ");
            }
            writer.print(values[i]);
        }
        writer.println();
    }
    writer.println("          protocol=" + request.getProtocol());
    writer.println("        remoteAddr=" + request.getRemoteAddr());
    writer.println("        remoteHost=" + request.getRemoteHost());
    writer.println("            scheme=" + request.getScheme());
    writer.println("        serverName=" + request.getServerName());
    writer.println("        serverPort=" + request.getServerPort());
    writer.println("          isSecure=" + request.isSecure());

    // Render the HTTP servlet request properties
    if (request instanceof HttpServletRequest) {
        final HttpServletRequest hrequest = (HttpServletRequest) request;
        writer.println("       contextPath=" + hrequest.getContextPath());

        Cookie[] cookies = hrequest.getCookies();
        if (cookies == null) {
            cookies = new Cookie[0];
        }
        for (int i = 0; i < cookies.length; i++) {
            writer.println("            cookie=" + cookies[i].getName() + "=" + cookies[i].getValue());
        }

        final Enumeration<String> headerNames = hrequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            final String name = headerNames.nextElement();
            final String value = hrequest.getHeader(name);
            writer.println("            header=" + name + "=" + value);
        }
        writer.println("            method=" + hrequest.getMethod());
        writer.println("          pathInfo=" + hrequest.getPathInfo());
        writer.println("       queryString=" + hrequest.getQueryString());
        writer.println("        remoteUser=" + hrequest.getRemoteUser());
        writer.println("requestedSessionId=" + hrequest.getRequestedSessionId());
        writer.println("        requestURI=" + hrequest.getRequestURI());
        writer.println("       servletPath=" + hrequest.getServletPath());

        // Create a wrapped request that contains the request body
        // and that we will pass to downstream filters
        final ByteArrayRequestWrapper wrappedRequest = new ByteArrayRequestWrapper(hrequest);
        downstreamRequest = wrappedRequest;
        writer.println(wrappedRequest.getRequestBodyAsString());
    }
    writer.println("-----------------------------------------------------");

    // Log the resulting string
    writer.flush();
    logger.trace(sw.getBuffer().toString());

    // Pass control on to the next filter
    chain.doFilter(downstreamRequest, response);
}