Example usage for java.io PrintWriter append

List of usage examples for java.io PrintWriter append

Introduction

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

Prototype

public PrintWriter append(char c) 

Source Link

Document

Appends the specified character to this writer.

Usage

From source file:se.vgregion.alfrescoclient.test.AlfrescoServiceTest.java

@Before
public void before() {

    alfrescoService = new AlfrescoService("http://localhost:" + port, HEADER_FIELD);

    server.setHandler(new AbstractHandler() {

        @Override//from  w ww. j a  v a2s.c o m
        public void handle(String target, Request baseRequest, HttpServletRequest httpServletRequest,
                HttpServletResponse httpServletResponse) throws IOException, ServletException {

            if (httpServletRequest.getHeader(HEADER_FIELD).equals(USER_ID)) {
                correctSSOHeader = true;
            }

            String request = httpServletRequest.getRequestURI();

            httpServletResponse.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = httpServletResponse.getWriter();

            if (request.contains("calendar")) {

                writer.append("{\"events\": [ { \"name\": \"1332762617639-415.ics\", \"title\": \"Test\", "
                        + "\"where\": \"\", \"when\": \"2012-03-26T12:00:00.000+02:00\", \"url\":"
                        + " \"page/site/redpilllinpro/calendar?date=2012-03-26\", \"start\": \"12:00\","
                        + " \"end\": \"13:00\", \"endDate\" : \"2012-03-26T13:00:00.000+02:00\", \"site\":"
                        + " \"redpilllinpro\", \"siteTitle\": \"Redpill Linpro\", \"allday\": \"false\","
                        + " \"tags\": \"\", \"duration\": \"PT1H\", \"isoutlook\": \"false\" } ] }");

                writer.close();

            } else {
                writer.append("[{" + " \"url\" : \"\\/alfresco\\/wcservice\\/api\\/sites\\/apa\","
                        + " \"sitePreset\" : \"site-dashboard\"," + " \"shortName\" : \"apa\","
                        + " \"title\" : \"Apa\"," + " \"description\" : \"\","
                        + "  \"node\" : \"\\/alfresco\\/wcservice\\/api\\/node\\/workspace\\/SpacesStore\\/b0548376-4678-45bf-962b-7169b13550d3\","
                        + " \"tagScope\" : \"\\/alfresco\\/wcservice\\/api\\/tagscopes\\/workspace\\/SpacesStore\\/b0548376-4678-45bf-962b-7169b13550d3\","
                        + " \"isPublic\" : false," + " \"visibility\" : \"MODERATED\", "
                        + "\"siteManagers\" : [  \"susro3\"  , \"admin\" ]" + " }" + "," + "{"
                        + " \"url\" : \"\\/alfresco\\/wcservice\\/api\\/sites\\/bepa\","
                        + " \"sitePreset\" : \"site-dashboard\"," + " \"shortName\" : \"bepa\","
                        + " \"title\" : \"Bepa\"," + " \"description\" : \"\","
                        + "  \"node\" : \"\\/alfresco\\/wcservice\\/api\\/node\\/workspace\\/SpacesStore\\/b0548376-4678-45bf-962b-7169b13550d3\","
                        + " \"tagScope\" : \"\\/alfresco\\/wcservice\\/api\\/tagscopes\\/workspace\\/SpacesStore\\/b0548376-4678-45bf-962b-7169b13550d3\","
                        + " \"isPublic\" : false," + " \"visibility\" : \"MODERATED\", "
                        + "\"siteManagers\" : [  \"susro3\"  , \"admin\" ]" + " }" + " ]");

                writer.close();
            }

            httpServletResponse.setStatus(HttpServletResponse.SC_OK);

        }

    });

    try {
        server.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.github.jknack.amd4j.Optimizer.java

@Override
public CharSequence walk(final Module module) {
    buffer = new StringBuilder();
    PrintWriter writer = null;
    try {// w  ww . j  a  v  a 2 s .co  m
        module.traverse(this);
        Writer out = config.getOut();
        Minifier minifier = config.getOptimize();
        CharSequence minified = minifier.minify(config, buffer);
        if (out != null) {
            writer = new PrintWriter(out);
            writer.append(minified);
        }
        return minified;
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:count.ly.messaging.ConnectionProcessor.java

URLConnection urlConnectionForEventData(final String eventData) throws IOException {
    String urlStr = serverURL_ + "/i?";
    if (!eventData.contains("&crash="))
        urlStr += eventData;//from  w w  w. j  a  va2  s.c  om
    final URL url = new URL(urlStr);
    final HttpURLConnection conn;
    if (Countly.publicKeyPinCertificates == null) {
        conn = (HttpURLConnection) url.openConnection();
    } else {
        HttpsURLConnection c = (HttpsURLConnection) url.openConnection();
        c.setSSLSocketFactory(sslContext_.getSocketFactory());
        conn = c;
    }
    conn.setConnectTimeout(CONNECT_TIMEOUT_IN_MILLISECONDS);
    conn.setReadTimeout(READ_TIMEOUT_IN_MILLISECONDS);
    conn.setUseCaches(false);
    conn.setDoInput(true);
    String picturePath = UserData.getPicturePathFromQuery(url);
    if (Countly.sharedInstance().isLoggingEnabled()) {
        Log.d(Countly.TAG, "Got picturePath: " + picturePath);
    }
    if (!picturePath.equals("")) {
        //Uploading files:
        //http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests

        File binaryFile = new File(picturePath);
        conn.setDoOutput(true);
        // Just generate some unique random value.
        String boundary = Long.toHexString(System.currentTimeMillis());
        // Line separator required by multipart/form-data.
        String CRLF = "\r\n";
        String charset = "UTF-8";
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        OutputStream output = conn.getOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
        // Send binary file.
        writer.append("--" + boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName()
                + "\"").append(CRLF);
        writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()))
                .append(CRLF);
        writer.append("Content-Transfer-Encoding: binary").append(CRLF);
        writer.append(CRLF).flush();
        FileInputStream fileInputStream = new FileInputStream(binaryFile);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fileInputStream.read(buffer)) != -1) {
            output.write(buffer, 0, len);
        }
        output.flush(); // Important before continuing with writer!
        writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
        fileInputStream.close();

        // End of multipart/form-data.
        writer.append("--" + boundary + "--").append(CRLF).flush();
    } else if (eventData.contains("&crash=")) {
        if (Countly.sharedInstance().isLoggingEnabled()) {
            Log.d(Countly.TAG, "Using post because of crash");
        }
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(eventData);
        writer.flush();
        writer.close();
        os.close();
    } else {
        conn.setDoOutput(false);
    }
    return conn;
}

From source file:org.emergent.plumber.StorageServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String msg = null;/*from   w w  w . jav  a 2 s. c om*/
    try {
        msg = getMsg(req);
        log("resp: " + msg);
    } catch (SQLException e) {
        log(e.getMessage(), e);
    }

    if (msg != null) {
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.append(msg);
    } else {
        resp.sendError(404);
    }
}

From source file:org.openmrs.web.servlet.QuickReportServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    String reportType = request.getParameter("reportType");
    HttpSession session = request.getSession();

    if (reportType == null || reportType.length() == 0) {
        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.null");
        return;//from   w  ww  . j a v a  2s . com
    }
    if (!Context.hasPrivilege(PrivilegeConstants.GET_PATIENTS)) {
        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                "Privilege required: " + PrivilegeConstants.GET_PATIENTS);
        session.setAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR,
                request.getRequestURI() + "?" + request.getQueryString());
        response.sendRedirect(request.getContextPath() + "/login.htm");
        return;
    }

    try {
        Velocity.init();
    } catch (Exception e) {
        log.error("Error initializing Velocity engine", e);
    }
    VelocityContext velocityContext = new VelocityContext();
    PrintWriter report = response.getWriter();

    report.append("Report: " + reportType + "<br/><br/>\n\n");

    if (reportType.equals("RETURN VISIT DATE THIS WEEK")) {
        doReturnVisitDate(velocityContext, report, request);
    }
    if (reportType.equals("ATTENDED CLINIC THIS WEEK")) {
        doAttendedClinic(velocityContext, report, request);
    } else if (reportType.equals("VOIDED OBS")) {
        doVoidedObs(velocityContext, report, request);
    }

    try {
        Velocity.evaluate(velocityContext, report, this.getClass().getName(), getTemplate(reportType));
    } catch (Exception e) {
        log.error("Error evaluating report type " + reportType, e);
    }

}

From source file:org.emergent.plumber.StorageServlet.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String body = MiscUtil.readBody(req);
    log("BODY:\n" + body);
    long tsmillis = getServerTimestamp(req);
    Connection dbCon = null;// w  w  w.j av  a  2  s  .  com
    PreparedStatement st = null;
    String rspMsg = null;
    try {
        JSONObject retval = new JSONObject();
        double serverTimestamp = MiscUtil.toWeaveTimestampDouble(tsmillis);
        retval.put("modified", serverTimestamp);
        JSONObject clientObj = new JSONObject(body);
        updateClient(req, tsmillis, clientObj);
        rspMsg = retval.toString();
    } catch (SQLException e) {
        log(e.getMessage(), e);
    } catch (JSONException e) {
        log(e.getMessage(), e);
    } finally {
        MiscUtil.close(st);
        MiscUtil.close(dbCon);
    }

    if (rspMsg != null) {
        //      resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.append(rspMsg);
    } else {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:org.marketcetera.orderloader.OrderLoaderMain.java

/**
 * Prints the usage to the output.//from   w ww.j  av  a 2s  .  c o m
 */
private void usage() {
    HelpFormatter formatter = new HelpFormatter();
    PrintWriter pw = new PrintWriter(mMsgStream);
    pw.append(ERROR_USAGE.getText());
    pw.println();
    formatter.printOptions(pw, HelpFormatter.DEFAULT_WIDTH, options, HelpFormatter.DEFAULT_LEFT_PAD,
            HelpFormatter.DEFAULT_DESC_PAD);
    pw.println();
    pw.flush();
    exit();
}

From source file:demo.project.ExportTable.java

/**
 * @param w/*from  w w  w  .j  ava 2 s. c o  m*/
 * @param ranker
 */
private void write(PrintWriter w, ColumnRanker ranker) {
    dumpHeader(w, ranker);
    int i = 0;
    for (IRow row : ranker) {
        w.print(i++);
        for (Iterator<ARankColumnModel> it = table.getColumnsOf(ranker); it.hasNext();) {
            ARankColumnModel col = it.next();
            w.append('\t').print(toValue(row, col));
            if (col instanceof ACompositeRankColumnModel) {
                addAll(w, row, ((ACompositeRankColumnModel) col).getChildren());
            }
        }
        w.println();
    }
}

From source file:org.emergent.plumber.StorageServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //    int length = req.getContentLength();
    String ctype = req.getContentType();
    String cenc = req.getCharacterEncoding();
    //    this.log("CLEN: " + length);
    this.log("CTYPE: " + ctype);
    this.log("CENC : " + cenc);
    String body = MiscUtil.readBody(req);
    this.log("BODY:\n" + body);
    long tsmillis = getServerTimestamp(req);

    String rspMsg = null;/* w  w  w .  j  ava  2s . c  o m*/
    try {
        JSONObject retval = new JSONObject();
        double serverTimestamp = MiscUtil.toWeaveTimestampDouble(tsmillis);
        retval.put("modified", serverTimestamp);
        JSONArray successArray = new JSONArray();
        JSONArray failedArray = new JSONArray();
        JSONArray clientsArray = new JSONArray(body);
        for (int ii = 0; ii < clientsArray.length(); ii++) {
            // todo catch exceptions in loop
            JSONObject clientObj = clientsArray.getJSONObject(ii);
            String nodeId = clientObj.getString("id");
            updateClient(req, tsmillis, clientObj);
            successArray.put(nodeId);
        }
        //      failedArray.put(nodeId);
        retval.put("success", successArray);
        retval.put("failed", failedArray);
        rspMsg = retval.toString();
    } catch (SQLException e) {
        log(e.getMessage(), e);
    } catch (JSONException e) {
        log(e.getMessage(), e);
    }

    log("RESPONSE: " + rspMsg);
    if (rspMsg != null) {
        resp.setContentType("application/json");
        PrintWriter writer2 = resp.getWriter();
        writer2.append(rspMsg);
    } else {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:org.kalypso.model.hydrology.internal.preprocessing.NAControlConverter.java

private void writeResultsToGenerate(final NAModellControl controlFE, final PrintWriter writer) {
    final int minutesOfTimeStep = m_metaControl.getMinutesOfTimestep();
    final double hoursOfTimeStep = minutesOfTimeStep / 60d;
    writer.append(" " + hoursOfTimeStep + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
    writer.append(getBoolean(controlFE.doGenerateTMP()) + "       Temperatur                 .tmp\n"); //$NON-NLS-1$
    writer.append(getBoolean(controlFE.doGeneratePRE()) + "       Niederschlag               .pre\n"); //$NON-NLS-1$
    writer.append(getBoolean(controlFE.doGenerateSCH()) + "       Schnee                     .sch\n"); //$NON-NLS-1$
    writer.append(getBoolean(controlFE.doGenerateBOF()) + "       Bodenfeuchte               .bof\n"); //$NON-NLS-1$
    writer.append(getBoolean(controlFE.doGenerateBSP()) + "       Bodenspeicher              .bsp\n"); //$NON-NLS-1$
    writer.append(getBoolean(controlFE.doGenerateGWS()) + "       Grundwasserstand           .gws\n"); //$NON-NLS-1$
    writer.append(getBoolean(controlFE.doGenerateQGS()) + "       Gesamtabfluss Knoten       .qgs\n"); //$NON-NLS-1$
    writer.append(getBoolean(controlFE.doGenerateQGG()) + "       Gesamtabfluss TG           .qgg\n"); //$NON-NLS-1$
    writer.append(getBoolean(controlFE.doGenerateQNA()) + "       nat. Oberflaechenabfluss   .qna\n"); //$NON-NLS-1$
    writer.append(getBoolean(controlFE.doGenerateQIF()) + "       Interflow                  .qif\n"); //$NON-NLS-1$
    writer.append(getBoolean(controlFE.doGenerateQVS()) + "       Abfluss vers. Flaechen     .qvs\n"); //$NON-NLS-1$
    writer.append(getBoolean(controlFE.doGenerateQBS()) + "       Basisabfluss               .qbs\n"); //$NON-NLS-1$
    writer.append(getBoolean(controlFE.doGenerateQT1()) + "       Kluftgrundw1               .qt1\n"); //$NON-NLS-1$
    writer.append(getBoolean(controlFE.doGenerateQTG()) + "       Kluftgrundw                .qtg\n"); //$NON-NLS-1$
    writer.append(getBoolean(controlFE.doGenerateQGW()) + "       Grundwasserabfluss         .qgw\n"); //$NON-NLS-1$
    // sollte nicht bei der Ausgabe erzeugt werden, da Berechnung mit kap. Aufstieg noch nicht implementiert!
    writer.append("n" + "       Kapil.Aufstieg/Perkolation .kap\n"); //$NON-NLS-1$ //$NON-NLS-2$
    writer.append(getBoolean(controlFE.doGenerateVET()) + "       Evapotranspiration         .vet\n"); //$NON-NLS-1$

    writer.append(getBoolean(controlFE.doGenerateHYD()) + "       Ausgabe Hydrotope          .hyd\n"); //$NON-NLS-1$

    // if "2": output of *.txt and *.bil
    if (controlFE.doGenerateBIL())
        writer.append("2" + "       Abflussbilanz              .bil\n"); //$NON-NLS-1$ //$NON-NLS-2$
    else/*  w  ww.  ja  v a 2s. co  m*/
        writer.append("n" + "       Abflussbilanz              .bil\n"); //$NON-NLS-1$ //$NON-NLS-2$
    writer.append(getBoolean(controlFE.doGenerateNMQ()) + "       Statistische Abflusswerte  .nmq\n"); //$NON-NLS-1$
    // Folgende Dateien werden zustzlich mit Speicherinhalt generiert .sph, .spv, .spn, .spb
    writer.append(getBoolean(controlFE.doGenerateSPI()) + "       Speicherinhalt             .spi\n"); //$NON-NLS-1$
    writer.append(getBoolean(controlFE.doGenerateSUP()) + "       Speicherueberlauf          .sup\n"); //$NON-NLS-1$

    // IMPORTANT: number of lines is important and mut not be changed; we need to write dummy entries for old suds stuff
    writer.append("n       xxxx not used xxxxxxxxxxx  .xxx\n"); //$NON-NLS-1$
    writer.append("n       xxxx not used xxxxxxxxxxx  .xxx\n"); //$NON-NLS-1$
    writer.append("n       xxxx not used xxxxxxxxxxx  .xxx\n"); //$NON-NLS-1$
    writer.append("n       xxxx not used xxxxxxxxxxx  .xxx\n"); //$NON-NLS-1$
    writer.append("n       xxxx not used xxxxxxxxxxx  .xxx\n"); //$NON-NLS-1$
}