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.npower.dm.hibernate.management.OTAClientProvJobBeanImpl.java

/**
 * Bookmark//from  w w w . j a  v a 2 s  .c o  m
 * @param profile
 * @param valueFetcher
 * @return
 * @throws DMException
 * @throws IOException
 * @throws Exception
 */
private SmsWapMessageDecorator buildWapPushMessage4Nokia_Bookmark(ProfileConfig profile,
        ValueFetcher<ProfileCategory, String, String> valueFetcher) throws DMException, IOException, Exception {
    SmsWapMessageDecorator result = null;
    ProfileConvertor converter = this.getProfileConverter(profile, valueFetcher);
    NokiaOtaBookmarkSettings setting = (NokiaOtaBookmarkSettings) converter.convertToNokiaOTA(profile);
    // Convert to XML
    StringWriter writer = new StringWriter();
    setting.writeXmlTo(new TextXmlWriter(writer));
    String content = writer.getBuffer().toString();

    result = new SmsWapMessageDecorator(setting.getSmsWapPushMessage(),
            ClientProvTemplate.NOKIA_OTA_7_0_ENCODER, content);
    return result;
}

From source file:com.serli.maven.plugin.quality.mojo.LicenseMojo.java

private StringBuffer printResults() {
    StringWriter out = new StringWriter();
    PrettyPrintXMLWriter writer = new PrettyPrintXMLWriter(out);
    writer.startElement("licenses");
    writer = printProjectLicense(writer);
    writer = printMissingHeader(writer);
    writer = printDependenciesLicense(writer);
    writer.endElement();/*from www  . ja v  a2s  . co m*/
    return out.getBuffer();
}

From source file:com.funambol.json.gui.GuiServlet.java

private void writeError(Exception ex, HttpServletResponse response, String action, HttpServletRequest request)
        throws IOException {
    log.error("An error occurred handling action [" + action + "]", ex);
    String errorPage = HTMLManager.getHtmlHeaderFor("An error occurred processing request:");
    response.setStatus(500);//  w  w w .j  a v  a 2 s.  c  om
    if (action != null) {
        errorPage += "Action was [" + action + "]<b>";
    }

    if (ex != null) {
        errorPage += "Exception was <b>]";
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        ex.printStackTrace(pw);
        errorPage += sw.getBuffer();
    }

    errorPage += HTMLManager.closePage(buildCommonFooter(request));
    sendHtmlPage(response, errorPage);
}

From source file:com.github.safrain.remotegsh.server.RgshFilter.java

private void performShellExecute(HttpServletRequest request, HttpServletResponse response) throws IOException {
    ShellSession session = getSession(request.getParameter("sid"));
    if (session == null) {
        response.setStatus(410);// Http status GONE
        return;/*from   w  ww .  ja  v  a  2  s .  co m*/
    }
    ScriptEngine engine = session.getEngine();

    String action = request.getParameter("action");
    if (action == null) {
        StringWriter responseWriter = new StringWriter();
        engine.getContext().setWriter(responseWriter);
        engine.getContext().setErrorWriter(response.getWriter());
        String script = toString(request.getInputStream(), charset);
        JSONObject json = new JSONObject();
        try {
            try {
                Object result = engine.eval(script);
                json.put("result", String.valueOf(result));
                response.setStatus(200);
                json.put("response", responseWriter.getBuffer().toString());
            } catch (ScriptException e) {
                log.log(Level.SEVERE, "Error while running shell command:" + script, e);
                response.setStatus(500);
                e.getCause().printStackTrace(response.getWriter());
                return;
            }
        } catch (JSONException e) {
            log.log(Level.SEVERE, "Error while running shell command:" + script, e);
            response.setStatus(500);
            e.printStackTrace(response.getWriter());
            return;
        }
        response.getWriter().write(json.toString());
    } else {
        Invocable invocable = (Invocable) engine;
        try {
            invocable.invokeFunction("shellAction", action);
        } catch (ScriptException e) {
            response.setStatus(500);
            e.printStackTrace(response.getWriter());
        } catch (NoSuchMethodException e) {
            response.setStatus(500);
            response.getWriter().println("Action not supported");
        } catch (Exception e) {
            response.setStatus(500);
            e.printStackTrace(response.getWriter());
        }
    }

}

From source file:com.ggvaidya.scinames.complexquery.ComplexQueryViewController.java

@FXML
private void copyToClipboard(ActionEvent evt) {
    try {/* w ww  . j  av a 2  s.c o m*/
        StringWriter writer = new StringWriter();
        List<List<String>> dataAsTable = getDataAsTable();

        fillCSVFormat(CSVFormat.TDF, writer, getDataAsTable());

        Clipboard clipboard = Clipboard.getSystemClipboard();
        HashMap<DataFormat, Object> content = new HashMap<>();
        content.put(DataFormat.PLAIN_TEXT, writer.getBuffer().toString());
        clipboard.setContent(content);

        Alert window = new Alert(Alert.AlertType.CONFIRMATION,
                (dataAsTable.get(0).size() - 1) + " rows written to clipboard.");
        window.showAndWait();
    } catch (IOException e) {
        Alert window = new Alert(Alert.AlertType.ERROR, "Could not save CSV to the clipboard: " + e);
        window.showAndWait();
    }
}

From source file:com.jskaleel.xml.JSONArray.java

/**
 * Make a prettyprinted JSON text of this JSONArray. Warning: This method
 * assumes that the data structure is acyclical.
 *
 * @param indentFactor//w w  w . ja  va  2 s. c o m
 *            The number of spaces to add to each level of indentation.
 * @return a printable, displayable, transmittable representation of the
 *         object, beginning with <code>[</code>&nbsp;<small>(left
 *         bracket)</small> and ending with <code>]</code>
 *         &nbsp;<small>(right bracket)</small>.
 * @throws JSONException
 */
public String toString(int indentFactor) throws JSONException {
    StringWriter sw = new StringWriter();
    synchronized (sw.getBuffer()) {
        return this.write(sw, indentFactor, 0).toString();
    }
}

From source file:de.micromata.genome.gwiki.page.search.SearchFoundHighlighterFilter.java

public Void filter(GWikiFilterChain<Void, GWikiServeElementFilterEvent, GWikiServeElementFilter> chain,
        GWikiServeElementFilterEvent event) {
    String words = event.getWikiContext().getRequestParameter("_gwhiwords");
    if (StringUtils.isEmpty(words) == true) {
        return chain.nextFilter(event);
    }/*from   w  w w . j  a v a 2  s  .c  o  m*/
    GWikiElement el = event.getElement();
    if (el == null || (el instanceof GWikiWikiPage) == false) {
        return chain.nextFilter(event);
    }
    // el.getElementInfo().get

    HttpServletResponse resp = event.getWikiContext().getResponse();

    final StringWriter sout = new StringWriter();
    final PrintWriter pout = new PrintWriter(sout);
    final Holder<Boolean> skip = new Holder<Boolean>(Boolean.FALSE);
    HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(resp) {

        @Override
        public void sendRedirect(String location) throws IOException {
            skip.set(Boolean.TRUE);
            super.sendRedirect(location);
        }

        @Override
        public ServletOutputStream getOutputStream() throws IOException {
            skip.set(Boolean.TRUE);
            return super.getOutputStream();
        }

        @Override
        public PrintWriter getWriter() throws IOException {
            return pout;
        }

        @Override
        public void resetBuffer() {
            sout.getBuffer().setLength(0);
        }
    };
    event.getWikiContext().setResponse(wrapper);
    chain.nextFilter(event);
    if (skip.get() == Boolean.TRUE) {
        return null;
    }
    try {
        PrintWriter pr = resp.getWriter();
        String orgString = sout.getBuffer().toString();
        if (StringUtils.containsIgnoreCase(orgString, "<html") == false) {
            pr.print(orgString);
            return null;
        }

        StringWriter filteredContent = new StringWriter();
        SearchHilightHtmlFilter filter = new SearchHilightHtmlFilter(filteredContent,
                Converter.parseStringTokens(words, ", ", false));
        filter.doFilter(orgString);
        // System.out.println("\n\nOrig:\n" + sout.getBuffer().toString() + "\n\nFiltered:\n" + filteredContent.getBuffer().toString());

        // pr
        // .println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
        pr.print(filteredContent.getBuffer().toString());
    } catch (IOException ex) {
        throw new RuntimeIOException(ex);
    }
    return null;
}

From source file:com.commerce4j.storefront.controllers.SyndicationController.java

public ModelAndView register(HttpServletRequest request, HttpServletResponse response) {

    ModelAndView mav = new ModelAndView("jsonView");

    String userName = request.getParameter("userName");
    String emailAddress = request.getParameter("emailAddress");
    String userPass = request.getParameter("userPass");
    String confirmPassword = request.getParameter("confirmPassword");
    String firstName = request.getParameter("firstName");
    String countryId = request.getParameter("countryId");
    String lastName = request.getParameter("lastName");
    String cellPhone = request.getParameter("cellPhone");
    String acceptTermAndConditions = request.getParameter("acceptTermAndConditions");

    List<Message> errors = new ArrayList<Message>();

    // validate countryId
    if (StringUtils.isBlank(countryId)) {
        errors.add(newError("countryId", getString("errors.notEmpty"),
                new Object[] { getString("register.countryId") }));
    }/*from   w  ww. j a  v a 2 s .  com*/

    // validate user
    if (StringUtils.isEmpty(userName)) {
        errors.add(newError("userName", getString("errors.notEmpty"),
                new Object[] { getString("register.userName") }));
    } else {
        // validate user name existence
        if (!getProfileDSO().isUserValid(userName)) {
            errors.add(newError("userName", getString("errors.userAlreadyExists"), new Object[] { userName }));
        }
    }

    // validate email address
    if (StringUtils.isEmpty(emailAddress)) {
        errors.add(newError("emailAddress", getString("errors.notEmpty"),
                new Object[] { getString("register.emailAddress") }));
    } else {

        // validate emailAddress format
        if (!EmailValidator.validate(emailAddress)) {
            errors.add(newError("emailAddress", getString("errors.emailInvalidFormat"),
                    new Object[] { emailAddress }));
        } else {
            // validate emailAddress existence
            if (!getProfileDSO().isEmailValid(emailAddress)) {
                errors.add(newError("emailAddress", getString("errors.emailAlreadyExists"),
                        new Object[] { emailAddress }));
            }
        }

    }

    // validate password
    if (StringUtils.isEmpty(userPass)) {
        errors.add(newError("userPass", getString("errors.notEmpty"),
                new Object[] { getString("register.userPass") }));
    }

    if (StringUtils.isEmpty(firstName)) {
        errors.add(newError("firstName", getString("errors.notEmpty"),
                new Object[] { getString("register.firstName") }));
    }

    if (StringUtils.isEmpty(cellPhone)) {
        errors.add(newError("cellPhone", getString("errors.notEmpty"),
                new Object[] { getString("register.cellPhone") }));
    }

    if (StringUtils.isEmpty(countryId)) {
        errors.add(newError("countryId", getString("errors.notEmpty"),
                new Object[] { getString("register.countryId") }));
    }

    if (StringUtils.isEmpty(lastName)) {
        errors.add(newError("lastName", getString("errors.notEmpty"),
                new Object[] { getString("register.lastName") }));
    }

    if (!StringUtils.equalsIgnoreCase(acceptTermAndConditions, "true")) {
        errors.add(newError("acceptTermAndConditions", getString("errors.acceptTermAndConditions")));
    }

    if (StringUtils.isEmpty(confirmPassword)) {
        errors.add(newError("confirmPassword", getString("errors.notEmpty"),
                new Object[] { getString("register.confirmPassword") }));
    }

    if (!StringUtils.equals(userPass, confirmPassword)) {
        errors.add(newError("userPass", getString("errors.passwordDoesNotMatch")));
    }

    // proceed to registration, if no errors found.
    if (errors.isEmpty()) {

        // create a user and get the newly generated user id,
        // this user by default is disabled, need to
        // validate after registration
        long userId = getProfileDSO().registerUser(userName, userPass, emailAddress, firstName, lastName,
                cellPhone, new Integer(countryId));

        // data objets

        UserDAO userDAO = (UserDAO) getBean("userDAO");
        UserDTO userDTO = userDAO.findById(userId);
        ConfigDAO configDAO = (ConfigDAO) getBean("configDAO");

        // set other user properties
        if (StringUtils.isNumeric(countryId)) {
            CountryDTO country = new CountryDTO();
            country.setCountryId(new Integer(countryId));
            userDTO.setCountry(country);
        }

        if (logger.isDebugEnabled()) {
            logger.debug("UID @ " + userId + "/" + userDTO.getGuid());
        }

        // check if store is configured for mail confirmation
        final String CONFIRM_KEY = "REGISTRATION_MAIL_CONFIRM";
        String confirmEmailAddress = configDAO.findById(CONFIRM_KEY);

        // send confirmation mail if mailer is configured
        if (StringUtils.equalsIgnoreCase("Yes", confirmEmailAddress)) {
            SendMail mailer = (SendMail) getBean("mailer");
            if (mailer != null)
                try {

                    // get variables from database
                    String storeName = configDAO.findById("STORE_NAME");
                    String storeURL = configDAO.findById("STORE_URL");
                    String from = configDAO.findById("REGISTRATION_MAIL_FROM");
                    String subject = configDAO.findById("REGISTRATION_MAIL_SUBJECT");
                    String prefixURL = "/profile.jspa?aid=confirm&uid=";
                    String url = storeURL + prefixURL + userDTO.getGuid();

                    // get store
                    StoreDTO store = new StoreDTO();
                    store.setStoreId(1);
                    store.setStoreName(storeName);
                    store.setStoreUrl(storeURL);

                    // build registration information object
                    RegistrationInfo info = new RegistrationInfo();
                    info.setUser(userDTO);
                    info.setStore(store);
                    info.setUrl(url);

                    // serializae registration object to XML
                    File inputFile = File.createTempFile("UID" + userId, "xml");
                    XStream xstream = new XStream();
                    xstream.alias("registration", RegistrationInfo.class);
                    xstream.toXML(info, new FileOutputStream(inputFile));

                    // transform xml object source to html mail output
                    StringWriter outWriter = new StringWriter();
                    InputStream xslStream = getClass().getResourceAsStream("/templates/welcome_mail.xsl");
                    InputStream xmlStream = new FileInputStream(inputFile);
                    xslTransform(xmlStream, xslStream, outWriter);

                    // send mail using mailer implementation
                    mailer.sendMessage(from, new String[] { emailAddress }, subject,
                            outWriter.getBuffer().toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    if (logger.isErrorEnabled()) {
                        logger.error(e);
                    }
                }
        } else {
            // if no email confirmation is required, then set the user
            // active
            userDTO.setActive(1);
            userDAO.update(userDTO);
        }

        // all ok, send nice response
        mav.addObject("responseCode", SUCCESS);
        mav.addObject("responseMessage", "Registro Completo");
        mav.addObject("userId", userId);

    } else {

        // something wron, send failure response
        mav.addObject("responseCode", FAILURE);
        mav.addObject("responseMessage", "Registro Incompleto, favor verificar");
        mav.addObject("errors", errors);
    }

    return mav;

}

From source file:edu.cornell.med.icb.goby.modes.TestDiscoverSVMethylationRatesMode.java

@Test
public void testMethylationFormatSwap() throws IOException, JSAPException {
    final MethylationRateVCFOutputFormat outputFormat = new MethylationRateVCFOutputFormat();
    DiscoverVariantIterateSortedAlignments iterator = new DiscoverVariantIterateSortedAlignments(outputFormat) {
        @Override/*from   www.j a v  a 2 s .co m*/
        public CharSequence getReferenceId(int targetIndex) {
            return "ref-id";
        }
    };
    DiscoverSequenceVariantsMode mode = new DiscoverSequenceVariantsMode() {
        @Override
        public String[] getSamples() {
            return new String[] { "not-so", "methylated" };
        }

        @Override
        public String[] getGroups() {
            return new String[] { "not-so", "methylated", };
        }

        @Override
        public int[] getReaderIndexToGroupIndex() {
            return new int[] { 0, 1 }; // sample index is group index;
        }

        @Override
        public ArrayList<GroupComparison> getGroupComparisons() {
            ArrayList<GroupComparison> list = new ArrayList<GroupComparison>();
            list.add(new GroupComparison("methylated", "not-so", 0, 1, 0));
            return list;
        }
    };
    StringWriter writer = new StringWriter();
    outputFormat.allocateStorage(2, 2);
    outputFormat.defineColumns(new PrintWriter(writer), mode);
    outputFormat.setGenome(genome);

    outputFormat.setMinimumEventThreshold(0);
    outputFormat.writeRecord(iterator, makeTwoSampleCounts(), 0, 0, list4(), 0, 1);
    String stringB = writer.getBuffer().toString();
    assertTrue(stringB, stringB.contains("1/2:A=10,T=4,N=2:16:0:33"));
    assertTrue(stringB, stringB.contains("0/1/2:A=5,T=1,C=9,N=1:16:0:0"));
    assertTrue(stringB, stringB.contains("#Cm_Group[methylated]=10;"));
    assertTrue(stringB, stringB.contains("#C_Group[methylated]=20;"));
    // check biomart-span included in result:
    assertTrue("biomart span must be included in result: " + stringB, stringB.contains("ref-id:1:1"));
}

From source file:com.evolveum.midpoint.prism.util.JaxbTestUtil.java

public String marshalElementToString(JAXBElement<?> jaxbElement, Map<String, Object> properties)
        throws JAXBException {
    StringWriter writer = new StringWriter();
    Marshaller marshaller = getMarshaller();
    for (Entry<String, Object> entry : properties.entrySet()) {
        marshaller.setProperty(entry.getKey(), entry.getValue());
    }/* w w  w  .j  av  a2  s . co m*/
    marshaller.marshal(jaxbElement, writer);
    return writer.getBuffer().toString();
}