Example usage for java.io StringWriter append

List of usage examples for java.io StringWriter append

Introduction

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

Prototype

public StringWriter append(char c) 

Source Link

Document

Appends the specified character to this writer.

Usage

From source file:com.epimorphics.lda.renderers.common.Page.java

/**
 * @return A list of links to pages that remove one of the currently active
 *         sorts/*from w w  w .j  a  va2 s  .co  m*/
 */
public List<Link> sortRemovalLinks() {
    List<Link> links = new ArrayList<Link>();
    EldaURL eu = pageURL();

    URLParameterValue sorts = eu.getParameter(QueryParameter._SORT);

    if (sorts != null) {
        for (String sortOn : sorts.values()) {
            boolean asc = true;
            String path = sortOn;
            if (sortOn.startsWith("-")) {
                asc = false;
                path = sortOn.substring(1);
            }

            StringWriter buf = new StringWriter();
            String sep = "";

            for (String p : StringUtils.split(path, ".")) {
                String uri = shortNameRenderer().expand(p);
                RDFNodeWrapper n = new CommonNodeWrapper(getModelW(), RDFUtil.asRDFNode(uri));
                buf.append(sep);
                buf.append(n.getName());
                sep = " &raquo; ";
            }

            buf.append(asc ? "" : " (descending)");

            links.add(createRemovalLink(eu, QueryParameter._SORT, "sort by", sortOn, buf.toString()));
        }

    }

    return links;
}

From source file:de.micromata.genome.gwiki.page.gspt.ExtendedTemplate.java

/**
 * Escape literal.//from   ww  w  . j  av a  2  s. c o m
 *
 * @param text the text
 * @return the string
 */
private String escapeLiteral(String text) {
    StringWriter ret = new StringWriter();
    for (int i = 0; i < text.length(); ++i) {
        char c = text.charAt(i);
        switch (c) {
        case '"':
            ret.append("\\\"");
            break;
        case '\\':
            ret.append("\\\\");
            break;
        case '\n':
            ret.append("\\n");
            break;
        case '\r':
            ret.append("\\r");
            break;
        default:
            ret.append(c);
            break;
        }
    }
    return ret.toString();
}

From source file:eu.elf.license.LicenseQueryHandler.java

/**
 * Send SOAP Message for activating/deactivating/deleting a license
 *
 * @param bcs//from  w  w w  . j  av a  2 s  .c o  m
 * @param query
 * @param SOAPAction
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
private Boolean sendSOAP(BasicCookieStore bcs, String query, String SOAPAction) throws IOException {
    log.debug("Querying SOAP - URL:", SOAPAddress, "- Payload:\n", query);
    InputStream response = null;
    try {
        List<Cookie> cookieList = bcs.getCookies();
        StringWriter cookieHeader = new StringWriter();
        for (Cookie c : cookieList) {
            cookieHeader.append(c.getName());
            cookieHeader.append("=");
            cookieHeader.append(c.getValue());
            cookieHeader.append("; ");
        }
        HttpURLConnection conn = IOHelper.getConnection(SOAPAddress);
        IOHelper.setContentType(conn, "text/xml; charset=utf-8");
        IOHelper.writeHeader(conn, "SOAPAction", SOAPAction);
        IOHelper.writeHeader(conn, "Cookie", cookieHeader.toString());

        IOHelper.writeToConnection(conn, query);
        response = conn.getInputStream();
        IOHelper.debugResponse(response);
        int code = conn.getResponseCode();
        if (code == 200) {
            return true;
        } else {
            return false;
        }
    } finally {
        IOHelper.close(response);
    }

}

From source file:eu.elf.license.LicenseQueryHandler.java

/**
 * Send SOAP Message and return response
 * /*from   ww  w . ja v a 2s . c  o m*/
 * @param bcs
 * @param query
 * @param SOAPAction
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
private String sendSOAPGetResponse(BasicCookieStore bcs, String query, String SOAPAction) throws IOException {
    log.debug("Querying SOAP - URL:", SOAPAddress, "- Payload:\n", query);

    InputStream response = null;
    String responseString = "";

    try {
        List<Cookie> cookieList = bcs.getCookies();
        StringWriter cookieHeader = new StringWriter();
        for (Cookie c : cookieList) {
            cookieHeader.append(c.getName());
            cookieHeader.append("=");
            cookieHeader.append(c.getValue());
            cookieHeader.append("; ");
        }

        HttpURLConnection conn = IOHelper.getConnection(SOAPAddress);
        IOHelper.setContentType(conn, "text/xml; charset=utf-8");
        IOHelper.writeHeader(conn, "SOAPAction", SOAPAction);
        IOHelper.writeHeader(conn, "Cookie", cookieHeader.toString());

        IOHelper.writeToConnection(conn, query);
        response = conn.getInputStream();
        int code = conn.getResponseCode();

        if (code == 200) {
            responseString = new Scanner(response, "UTF-8").useDelimiter("\\A").next();

            return responseString;
        } else {
            return "";
        }
    } finally {
        IOHelper.close(response);
    }

}

From source file:org.eclipse.cft.server.core.internal.client.ClientRequestFactory.java

public BaseClientRequest<List<CFServiceInstance>> getDeleteServicesRequest(final List<String> services) {
    return new BehaviourRequest<List<CFServiceInstance>>(Messages.CloudFoundryServerBehaviour_DELETE_SERVICES,
            behaviour) {//from w  w  w . ja  v  a 2s. co  m
        @Override
        protected List<CFServiceInstance> doRun(CloudFoundryOperations client, SubMonitor progress)
                throws CoreException {

            SubMonitor serviceProgress = SubMonitor.convert(progress, services.size());

            List<String> boundServices = new ArrayList<String>();
            for (String service : services) {
                serviceProgress
                        .subTask(NLS.bind(Messages.CloudFoundryServerBehaviour_DELETING_SERVICE, service));

                boolean shouldDelete = true;
                try {
                    CloudServiceInstance instance = client.getServiceInstance(service);
                    List<CloudServiceBinding> bindings = (instance != null) ? instance.getBindings() : null;
                    shouldDelete = bindings == null || bindings.isEmpty();
                } catch (Throwable t) {
                    // If it is a server or network error, it will still be
                    // caught below
                    // when fetching the list of apps:
                    // [96494172] - If fetching service instances fails, try
                    // finding an app with the bound service through the
                    // list of
                    // apps. This is treated as an alternate way only if the
                    // primary form fails as fetching list of
                    // apps may be potentially slower
                    List<CloudApplication> apps = behaviour.getApplications(progress);
                    if (apps != null) {
                        for (int i = 0; shouldDelete && i < apps.size(); i++) {
                            CloudApplication app = apps.get(i);
                            if (app != null) {
                                List<String> appServices = app.getServices();
                                if (appServices != null) {
                                    for (String appServ : appServices) {
                                        if (service.equals(appServ)) {
                                            shouldDelete = false;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if (shouldDelete) {
                    client.deleteService(service);
                } else {
                    boundServices.add(service);
                }
                serviceProgress.worked(1);
            }
            if (!boundServices.isEmpty()) {
                StringWriter writer = new StringWriter();
                int size = boundServices.size();
                for (int i = 0; i < size; i++) {
                    writer.append(boundServices.get(i));
                    if (i < size - 1) {
                        writer.append(',');
                        writer.append(' ');
                    }
                }
                String boundServs = writer.toString();
                CloudFoundryPlugin.getCallback().displayAndLogError(CloudFoundryPlugin.getErrorStatus(NLS
                        .bind(Messages.CloudFoundryServerBehaviour_ERROR_DELETE_SERVICES_BOUND, boundServs)));

            }
            return CloudServicesUtil.asServiceInstances(client.getServices());
        }
    };
}

From source file:org.sakaiproject.rubrics.logic.impl.RubricsServiceImpl.java

/**
 * Put the rubric association.//w ww.j  a  v  a 2s.c  om
 * @param targetUri The association href.
 * @param json The json to post.
 * @return
 */
private String putRubricResource(String targetUri, String json, String toolId) throws IOException {
    log.debug(String.format("PUT to URI '%s' body:", targetUri, json));

    HttpURLConnection conn = null;
    try {
        URL url = new URL(targetUri);
        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Content-Length", "" + json.length());
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("PUT");
        String cookie = "JSESSIONID=" + sessionManager.getCurrentSession().getId() + ""
                + System.getProperty(SERVER_ID_PROPERTY);
        conn.setRequestProperty("Cookie", cookie);
        conn.setRequestProperty("Authorization", "Bearer " + generateJsonWebToken(toolId));

        try (OutputStream os = conn.getOutputStream()) {
            os.write(json.getBytes("UTF-8"));
            os.close();
        }

        // read the response
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output;
        StringWriter result = new StringWriter();
        while ((output = br.readLine()) != null) {
            result.append(output + "\n");
        }

        return result.toString();

    } catch (IOException ioException) {

        log.warn(String.format("Error updating a rubric resource at %s", targetUri), ioException);
        return null;
    } finally {
        if (conn != null) {
            try {
                conn.disconnect();
            } catch (Exception e) {

            }
        }
    }
}

From source file:org.sakaiproject.rubrics.logic.impl.RubricsServiceImpl.java

/**
 * Posts the rubric association.// www . j  ava 2 s. c o m
 * @param json The json to post.
 * @return
 */
private String postRubricResource(String targetUri, String json, String toolId) throws IOException {
    log.debug(String.format("Post to URI '%s' body:", targetUri, json));

    HttpURLConnection conn = null;
    try {
        URL url = new URL(targetUri);
        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/hal+json; charset=UTF-8");
        conn.setRequestProperty("Content-Length", "" + json.length());
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        String cookie = "JSESSIONID=" + sessionManager.getCurrentSession().getId() + ""
                + System.getProperty(SERVER_ID_PROPERTY);
        conn.setRequestProperty("Cookie", cookie);
        conn.setRequestProperty("Authorization", "Bearer " + generateJsonWebToken(toolId));

        try (OutputStream os = conn.getOutputStream()) {
            os.write(json.getBytes("UTF-8"));
            os.close();
        }

        // read the response
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output;
        StringWriter result = new StringWriter();
        while ((output = br.readLine()) != null) {
            result.append(output + "\n");
        }

        return result.toString();

    } catch (IOException ioException) {

        log.warn(String.format("Error creating a rubric resource at %s", targetUri), ioException);
        return null;

    } finally {
        if (conn != null) {
            try {
                conn.disconnect();
            } catch (Exception e) {

            }
        }
    }
}

From source file:de.micromata.genome.gwiki.page.gspt.ExtendedTemplate.java

/**
 * Element to code.//from  ww  w. j a v a 2s .  co  m
 *
 * @param elements the elements
 * @return the string
 */
private String elementToCode(List<ParseElement> elements) {
    StringWriter sw = new StringWriter();
    boolean genClass = (getFlags() & Flags.GenGsptPageBase.getFlags()) == Flags.GenGsptPageBase.getFlags();
    // TODO roger here flag for servlet
    sw.append("import javax.servlet.*;\n");
    sw.append("import javax.servlet.jsp.*;\n");
    sw.append("\nServletConfig getServletConfig() { return servletConfig; }\n\n");

    for (ParseElement el : elements) {
        switch (el.type) {
        case GlobalCode:
            sw.append(el.text);
            break;
        }
    }

    if (genClass == true) {
        sw.append("class TClass extends de.micromata.genome.web.gspt.GsptPageBase { \n");
    }
    for (ParseElement el : elements) {
        switch (el.type) {
        case ClassCode:
            sw.append(el.text);
            break;
        }
    }
    if (genClass == true) {
        sw.append("  public void _gsptService(javax.servlet.jsp.PageContext pageContext) {\n");
        sw.append("   javax.servlet.http.HttpServletResponse response = pageContext.getResponse();\n");
        sw.append("   javax.servlet.http.HttpServletRequest request = pageContext.getRequest();\n");

    }
    for (ParseElement el : elements) {
        switch (el.type) {
        case AssignExpr:
            // sw.append("${").append(el.text).append("}");
            sw.append("out.print(").append(el.text).append(");");
            break;
        case ClassCode:
        case GlobalCode:
            break;
        case Code:
            sw.append(el.text);
            break;
        case Comment:
            // sw.append("/* ").append(el.text).append(" */");
            break;
        case ConstString:
            if (Flags.UseHereConstString.isFlagSet(flags) == true)
                sw.append("out.print('''").append(escapeQuote(el.text.toString(), '\'')).append("''');\n");
            else if (Flags.UseHereExprString.isFlagSet(flags) == true)
                sw.append("out.print(\"\"\"").append(escapeQuote(el.text.toString(), '"')).append("\"\"\");\n");
            else
                sw.append("out.print(\"").append(escapeLiteral(el.text.toString())).append("\");\n");
            break;
        case Statement:
            sw.append(patchStatement(el.text.toString()));
            break;
        }
    }
    if (genClass == true) {
        sw.append("}\n}\n") //
                .append("TClass tcls = new TClass();\n") //
                .append("tcls.setServletConfig(servletConfig);\n") //
                .append("tcls.service(pageContext);\n"); //
    }
    return sw.toString();
}

From source file:org.sakaiproject.rubrics.logic.impl.RubricsServiceImpl.java

/**
 * Returns the JSON string for the rubric evaluation
 * @param toolId the tool id, something like "sakai.assignment"
 * @param associatedToolItemId the id of the tool item which has a rubric associated to it (e.g. assignment ID)
 * @param evaluatedItemId  the id of the tool item which is being evaluated using a rubric (e.g. assignment submission ID)
 * @return/*ww w . ja v  a 2s.  c  o  m*/
 */
public String getRubricEvaluation(String toolId, String associatedToolItemId, String evaluatedItemId)
        throws IOException {

    HttpURLConnection conn = null;
    try {
        URL url = new URL(serverConfigurationService.getServerUrl() + RBCS_SERVICE_URL_PREFIX
                + "evaluations/search/by-tool-item-and-associated-item-and-evaluated-item-ids?toolId=" + toolId
                + "&itemId=" + associatedToolItemId + "&evaluatedItemId=" + evaluatedItemId);

        String cookie = "JSESSIONID=" + sessionManager.getCurrentSession().getId() + ""
                + System.getProperty(SERVER_ID_PROPERTY);

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Cookie", cookie);
        conn.setRequestProperty("Authorization", "Bearer" + generateJsonWebToken(toolId));

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output;
        StringWriter result = new StringWriter();
        while ((output = br.readLine()) != null) {
            result.append(output + "\n");
        }

        return result.toString();

    } catch (MalformedURLException e) {

        log.warn("Error getting a rubric evaluation " + e.getMessage());
        return null;

    } catch (IOException e) {

        log.warn("Error getting a rubric evaluation" + e.getMessage());
        return null;
    } finally {
        if (conn != null) {
            try {
                conn.disconnect();
            } catch (Exception e) {

            }
        }
    }
}

From source file:org.overture.codegen.vdm2java.JavaFormat.java

public String format(List<AFormalParamLocalParamCG> params) throws AnalysisException {
    StringWriter writer = new StringWriter();

    if (params.size() <= 0) {
        return "";
    }/*from   w w w  .  j a va  2s .co  m*/

    final String finalPrefix = " final ";

    AFormalParamLocalParamCG firstParam = params.get(0);
    writer.append(finalPrefix);
    writer.append(format(firstParam));

    for (int i = 1; i < params.size(); i++) {
        AFormalParamLocalParamCG param = params.get(i);
        writer.append(", ");
        writer.append(finalPrefix);
        writer.append(format(param));
    }
    return writer.toString();
}