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.aimluck.eip.gpdb.util.GpdbUtils.java

/**
 * ??????//from   w w w .  jav  a 2 s.  c o m
 * 
 * @param gpdbItemList
 * 
 * @return
 */
public static String createMsgForPc(RunData rundata, EipTGpdb gpdb, String gpdbItemName, String dispValue,
        Boolean isNew) throws ALDBErrorException {
    VelocityContext context = new VelocityContext();
    boolean enableAsp = JetspeedResources.getBoolean("aipo.asp", false);
    ALEipUser loginUser = null;
    ALBaseUser user = null;

    try {
        loginUser = ALEipUtils.getALEipUser(rundata);
        user = (ALBaseUser) JetspeedSecurity.getUser(new UserIdPrincipal(loginUser.getUserId().toString()));
    } catch (Exception e) {
        return "";
    }
    context.put("loginUser", loginUser.getAliasName().toString());
    context.put("hasEmail", !user.getEmail().equals(""));
    context.put("email", user.getEmail());
    context.put("isNew", isNew);
    // 
    context.put("GpdbName", gpdb.getGpdbName());
    // ??
    context.put("GpdbItemName", gpdbItemName);
    context.put("DispValue", dispValue);

    // 
    context.put("serviceAlias", ALOrgUtilsService.getAlias());
    // Aipo??
    context.put("enableAsp", enableAsp);
    context.put("globalurl", ALMailUtils.getGlobalurl());
    context.put("localurl", ALMailUtils.getLocalurl());
    CustomLocalizationService locService = (CustomLocalizationService) ServiceUtil
            .getServiceByName(LocalizationService.SERVICE_NAME);
    String lang = locService.getLocale(rundata).getLanguage();
    StringWriter writer = new StringWriter();
    try {
        if (lang != null && lang.equals("ja")) {
            Template template = Velocity.getTemplate("portlets/mail/" + lang + "/gpdb-notification-mail.vm",
                    "utf-8");
            template.merge(context, writer);
        } else {
            Template template = Velocity.getTemplate("portlets/mail/gpdb-notification-mail.vm", "utf-8");
            template.merge(context, writer);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    writer.flush();
    String ret = writer.getBuffer().toString();
    return ret;
}

From source file:at.ac.tuwien.dsg.comot.orchestrator.interraction.rsybl.rSYBLInterraction.java

public void sendInitialConfigToRSYBL(CloudService serviceTemplate, DeploymentDescription deploymentDescription,
        CompositionRulesConfiguration compositionRulesConfiguration, String effectsJSON) {

    deploymentDescription = enrichWithElasticityCapabilities(deploymentDescription, serviceTemplate);

    HttpHost endpoint = new HttpHost(rSYBL_BASE_IP, rSYBL_BASE_PORT);

    {// ww  w. j a  v  a2s.co  m
        DefaultHttpClient httpClient = new DefaultHttpClient();
        URI prepareConfigURI = UriBuilder
                .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/prepareControl").build();
        HttpPut prepareConfig = new HttpPut(prepareConfigURI);

        try {
            HttpResponse httpResponse = httpClient.execute(endpoint, prepareConfig);
            EntityUtils.consume(httpResponse.getEntity());

        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        }
    }
    {
        DefaultHttpClient httpClient = new DefaultHttpClient();

        try {

            JAXBContext jAXBContext = JAXBContext.newInstance(DeploymentDescription.class);
            Marshaller marshaller = jAXBContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            StringWriter sw = new StringWriter();

            log.info("Sending deployment description to rSYBL");
            marshaller.marshal(deploymentDescription, sw);
            log.info(sw.toString());

            URI putDeploymentStructureURL = UriBuilder
                    .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/deployment").build();
            HttpPut putDeployment = new HttpPut(putDeploymentStructureURL);

            StringEntity entity = new StringEntity(sw.getBuffer().toString());

            entity.setContentType("application/xml");
            entity.setChunked(true);

            putDeployment.setEntity(entity);

            log.info("Executing request " + putDeployment.getRequestLine());
            HttpResponse response = httpClient.execute(endpoint, putDeployment);
            HttpEntity resEntity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (response.getStatusLine().getStatusCode() == 200) {

            }
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
                System.out.println("Chunked?: " + resEntity.isChunked());
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    {
        DefaultHttpClient httpClient = new DefaultHttpClient();

        try {

            JAXBContext jAXBContext = JAXBContext.newInstance(CloudServiceXML.class);
            CloudServiceXML cloudServiceXML = toRSYBLRepresentation(serviceTemplate);
            Marshaller marshaller = jAXBContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            StringWriter sw = new StringWriter();
            log.info("Sending service description description to rSYBL");
            marshaller.marshal(cloudServiceXML, sw);
            log.info(sw.toString());

            URI putDeploymentStructureURL = UriBuilder
                    .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/description").build();
            HttpPut putDeployment = new HttpPut(putDeploymentStructureURL);

            StringEntity entity = new StringEntity(sw.getBuffer().toString());

            entity.setContentType("application/xml");
            entity.setChunked(true);

            putDeployment.setEntity(entity);

            log.info("Executing request " + putDeployment.getRequestLine());
            HttpResponse response = httpClient.execute(endpoint, putDeployment);
            HttpEntity resEntity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (response.getStatusLine().getStatusCode() == 200) {

            }
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
                System.out.println("Chunked?: " + resEntity.isChunked());
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    {
        DefaultHttpClient httpClient = new DefaultHttpClient();

        try {

            JAXBContext jAXBContext = JAXBContext.newInstance(CompositionRulesConfiguration.class);
            Marshaller marshaller = jAXBContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            StringWriter sw = new StringWriter();
            log.info("Sending  updated composition rules");
            marshaller.marshal(compositionRulesConfiguration, sw);
            log.info(sw.toString());

            URI putDeploymentStructureURL = UriBuilder
                    .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/compositionRules").build();
            HttpPut putDeployment = new HttpPut(putDeploymentStructureURL);

            StringEntity entity = new StringEntity(sw.getBuffer().toString());

            entity.setContentType("application/xml");
            entity.setChunked(true);

            putDeployment.setEntity(entity);

            log.info("Executing request " + putDeployment.getRequestLine());
            HttpResponse response = httpClient.execute(endpoint, putDeployment);
            HttpEntity resEntity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (response.getStatusLine().getStatusCode() == 200) {

            }
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
                System.out.println("Chunked?: " + resEntity.isChunked());
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    {
        DefaultHttpClient httpClient = new DefaultHttpClient();

        try {

            URI putDeploymentStructureURL = UriBuilder
                    .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/elasticityCapabilitiesEffects")
                    .build();
            HttpPut putDeployment = new HttpPut(putDeploymentStructureURL);

            String jsonEffectsDescription = capabilitiesToJSON(serviceTemplate);

            StringEntity entity = new StringEntity(jsonEffectsDescription);

            entity.setContentType("application/json");
            entity.setChunked(true);

            putDeployment.setEntity(entity);

            log.info("Send updated Effects");
            log.info(effectsJSON);

            HttpResponse response = httpClient.execute(endpoint, putDeployment);

            HttpEntity resEntity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (response.getStatusLine().getStatusCode() == 200) {

            }
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
                System.out.println("Chunked?: " + resEntity.isChunked());
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        URI prepareConfigURI = UriBuilder
                .fromPath(rSYBL_BASE_URL + "/" + serviceTemplate.getId() + "/startControl").build();
        HttpPut prepareConfig = new HttpPut(prepareConfigURI);

        try {
            HttpResponse httpResponse = httpClient.execute(endpoint, prepareConfig);
            EntityUtils.consume(httpResponse.getEntity());

        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        }
    }

}

From source file:com.netspective.sparx.panel.editor.PanelEditor.java

/**
 * Renders the panel editor. When the panel editor is in ADD, EDIT, or DELETE modes, it has an active element
 * and the display of the editor is broken into two columns. The left column is for display of the
 * active element's "action" item while the right column contains all the elements in their inactive display
 * mode./* ww w  .  ja  v  a 2 s  .  c om*/
 *
 * @param writer writer to render the output to
 * @param nc     current navigation context
 */
public void render(Writer writer, NavigationContext nc, PanelEditorState state) throws IOException {
    if (getRequireRequestParam() != null) {
        if (nc.getHttpRequest().getParameter(getRequireRequestParam()) == null)
            throw new RuntimeException("Record editor panel '" + getQualifiedName() + "' requires the request "
                    + "parameter '" + getRequireRequestParam() + "'.");
    }
    if (!isInitialized())
        initialize();
    int mode = state.getCurrentMode();
    BasicHtmlPanelValueContext pvc = new BasicHtmlPanelValueContext(nc, this);

    // only when the mode is in DISPLAY mode, the panel editor is displayed
    HtmlPanelSkin skin = null;
    skin = nc.getActiveTheme().getTemplateSkin("panel-editor-full");
    /*
    if (mode != PanelEditor.MODE_DISPLAY && mode != PanelEditor.MODE_MANAGE)
    {
    skin = nc.getActiveTheme().getTemplateSkin("panel-editor-compressed");
    }
    else
    {
    skin = nc.getActiveTheme().getTemplateSkin("panel-editor-full");
    }
    */

    nc.getHttpRequest().setAttribute(PREV_MODE_REQ_ATTRIBUTE, translateModeToString(state.getCurrentMode()));

    String activeElement = state.getActiveElement();
    StringWriter activeEditorWriter = new StringWriter();
    StringWriter activeDisplayWriter = new StringWriter();
    StringWriter inactiveWriter = new StringWriter();
    PanelEditorContentElement[] elements = getElementsAsArray();
    for (int i = 0; i < elements.length; i++) {
        if (activeElement != null && elements[i].getName().equals(activeElement)) {
            elements[i].renderEditorContent(activeEditorWriter, nc, state);
            elements[i].renderDisplayContent(activeDisplayWriter, nc, state);
        } else {
            elements[i].renderDisplayContent(inactiveWriter, nc, state);
        }
    }
    preparePanelActionStates(nc, pvc, state, mode);
    if (mode != PanelEditor.MODE_DISPLAY)
        writer.write("<table class=\"panel-editor-table-manage\"><tr>\n");
    else
        writer.write("<table class=\"panel-editor-table\"><tr>\n");
    if (activeElement != null)
        writer.write("<td class=\"active-content\">" + activeEditorWriter.getBuffer().toString() + "</td>");

    writer.write("<td class=\"display-content\">");
    skin.renderPanelRegistration(writer, pvc);
    skin.renderFrameBegin(writer, pvc);
    writer.write((activeElement != null ? activeDisplayWriter.getBuffer().toString() : "")
            + inactiveWriter.getBuffer().toString());
    skin.renderFrameEnd(writer, pvc);
    writer.write("</td></tr></table>\n");
}

From source file:de.betterform.xml.xforms.XFormsProcessorImpl.java

public void writeExternal(ObjectOutput objectOutput) throws IOException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("serializing XFormsFormsProcessorImpl");
    }//from   www  .  j  a  v  a  2s. c  om
    try {
        if (getXForms().getDocumentElement().hasAttribute("bf:serialized")) {
            objectOutput.writeUTF(DOMUtil.serializeToString(getXForms()));
        } else {
            getXForms().getDocumentElement().setAttributeNS(NamespaceConstants.BETTERFORM_NS, "bf:baseURI",
                    getBaseURI());
            getXForms().getDocumentElement().setAttributeNS(NamespaceConstants.BETTERFORM_NS, "bf:serialized",
                    "true");

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("....::: XForms before writing ::::....");
                DOMUtil.prettyPrintDOM(getXForms());
            }

            DefaultSerializer serializer = new DefaultSerializer(this);
            Document serializedForm = serializer.serialize();

            StringWriter stringWriter = new StringWriter();
            Transformer transformer = null;
            StreamResult result = new StreamResult(stringWriter);
            try {
                transformer = TransformerFactory.newInstance().newTransformer();
                transformer.setOutputProperty(OutputKeys.METHOD, "xml");
                transformer.transform(new DOMSource(serializedForm), result);
            } catch (TransformerConfigurationException e) {
                throw new IOException("TransformerConfiguration invalid: " + e.getMessage());
            } catch (TransformerException e) {
                throw new IOException("Error during serialization transform: " + e.getMessage());
            }
            objectOutput.writeUTF(stringWriter.getBuffer().toString());
        }
    } catch (XFormsException e) {
        throw new IOException("baseURI couldn't be set");
    }

    objectOutput.flush();
    objectOutput.close();

}

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

/**
 * Make a prettyprinted JSON text of this JSONObject.
 * <p>//from w ww . j  a  v a  2  s.c  o  m
 * Warning: This method assumes that the data structure is acyclical.
 *
 * @param indentFactor
 *            The number of spaces to add to each level of indentation.
 * @return a printable, displayable, portable, transmittable representation
 *         of the object, beginning with <code>{</code>&nbsp;<small>(left
 *         brace)</small> and ending with <code>}</code>&nbsp;<small>(right
 *         brace)</small>.
 * @throws JSONException
 *             If the object contains an invalid number.
 */
public String toString(int indentFactor) throws JSONException {
    StringWriter w = new StringWriter();
    synchronized (w.getBuffer()) {
        return this.write(w, indentFactor, 0).toString();
    }
}

From source file:org.apache.maven.plugin.dependency.AbstractAnalyzeMojo.java

private void writeDependencyXML(Set<Artifact> artifacts) {
    if (!artifacts.isEmpty()) {
        getLog().info("Add the following to your pom to correct the missing dependencies: ");

        StringWriter out = new StringWriter();
        PrettyPrintXMLWriter writer = new PrettyPrintXMLWriter(out);

        for (Artifact artifact : artifacts) {
            // called because artifact will set the version to -SNAPSHOT only if I do this. MNG-2961
            artifact.isSnapshot();/*from   w  w w.  j  a  va 2s. c  o m*/

            writer.startElement("dependency");
            writer.startElement("groupId");
            writer.writeText(artifact.getGroupId());
            writer.endElement();
            writer.startElement("artifactId");
            writer.writeText(artifact.getArtifactId());
            writer.endElement();
            writer.startElement("version");
            writer.writeText(artifact.getBaseVersion());
            if (!StringUtils.isBlank(artifact.getClassifier())) {
                writer.startElement("classifier");
                writer.writeText(artifact.getClassifier());
                writer.endElement();
            }
            writer.endElement();

            if (!Artifact.SCOPE_COMPILE.equals(artifact.getScope())) {
                writer.startElement("scope");
                writer.writeText(artifact.getScope());
                writer.endElement();
            }
            writer.endElement();
        }

        getLog().info("\n" + out.getBuffer());
    }
}

From source file:org.runnerup.export.EndomondoSynchronizer.java

@Override
public Status upload(SQLiteDatabase db, long mID) {
    Status s;/*from  w  w  w.j a v  a  2  s  .  co m*/
    if ((s = connect()) != Status.OK) {
        return s;
    }

    EndomondoTrack tcx = new EndomondoTrack(db);
    HttpURLConnection conn = null;
    Exception ex = null;
    try {
        EndomondoTrack.Summary summary = new EndomondoTrack.Summary();
        StringWriter writer = new StringWriter();
        tcx.export(mID, writer, summary);

        String workoutId = deviceId + "-" + Long.toString(mID);
        Log.e(getName(), "workoutId: " + workoutId);

        StringBuilder url = new StringBuilder();
        url.append(UPLOAD_URL).append("?authToken=").append(authToken);
        url.append("&workoutId=").append(workoutId);
        url.append("&sport=").append(summary.sport);
        url.append("&duration=").append(summary.duration);
        url.append("&distance=").append(summary.distance);
        if (summary.hr != null) {
            url.append("&heartRateAvg=").append(summary.hr.toString());
        }
        url.append("&gzip=true");
        url.append("&extendedResponse=true");

        conn = (HttpURLConnection) new URL(url.toString()).openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(RequestMethod.POST.name());
        conn.addRequestProperty("Content-Type", "application/octet-stream");
        OutputStream out = new GZIPOutputStream(new BufferedOutputStream(conn.getOutputStream()));
        out.write(writer.getBuffer().toString().getBytes());
        out.flush();
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        JSONObject res = parseKVP(in);
        conn.disconnect();

        Log.e(getName(), "res: " + res.toString());

        int responseCode = conn.getResponseCode();
        String amsg = conn.getResponseMessage();
        if (responseCode == HttpStatus.SC_OK && "OK".contentEquals(res.getString("_0"))) {
            s.activityId = mID;
            return s;
        }
        ex = new Exception(amsg);
    } catch (IOException e) {
        ex = e;
    } catch (JSONException e) {
        ex = e;
    }

    s = Synchronizer.Status.ERROR;
    s.ex = ex;
    if (ex != null) {
        ex.printStackTrace();
    }
    return s;
}

From source file:org.hexlogic.model.DockerNode.java

@VsoMethod(showInApi = true, name = "getHostInfo", description = "Returns information about the docker node")
public String getHostInfo() throws Exception {
    log.debug("Getting host info...");
    DockerClient dockerClient = null;//from  www .  j  av a 2 s .  c  o  m
    try {
        configureNode();
        dockerClient = getDockerClient();
        return dockerClient.infoCmd().exec().toString();
    } catch (Exception e) {
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);
        log.error("Error while getting host info: " + sw.getBuffer().toString());
        // Throw error detail message so vCO can display it
        throw new Exception("Error while getting host info: " + sw.getBuffer().toString());
    }
}

From source file:com.prowidesoftware.swift.model.SwiftMessage.java

/**
 * Gets a proprietary XML representation of this message.<br />
  * Notice: it is neither a standard nor the MX version of this MT.
 * @see XMLWriterVisitor/* w w  w .  j  a  va2  s  .com*/
 * @see XMLParser
 * @return the MT message serialized into the proprietary XML
 * @since 7.8.4
 */
public final String toXml() {
    final StringWriter w = new StringWriter();
    visit(new XMLWriterVisitor(w, true));
    final String xml = w.getBuffer().toString();
    if (log.isLoggable(Level.FINEST)) {
        log.finest("xml: " + xml);
    }
    return xml;
}

From source file:org.hexlogic.model.DockerNode.java

@VsoMethod(showInApi = false)
public InspectImageResponse inspectDockerImage(DockerImage image) throws Exception {
    log.debug("Running inspectDockerImage...");
    DockerClient dockerClient = null;//w  w  w  .  j  a v a 2  s.  c  o m
    try {
        configureNode();
        dockerClient = getDockerClient();

        return dockerClient.inspectImageCmd(image.getImageId()).exec();
    } catch (Exception e) {
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw, true);
        e.printStackTrace(pw);

        log.error("Error running inspectDockerImage: " + sw.getBuffer().toString());
        throw e;
    }
}