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:org.emergent.plumber.UserServlet.java

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String subPath = (String) req.getAttribute(ATTRIB_SUBPATH_KEY);
    if (!"".equals(subPath)) {
        super.doPut(req, resp);
        return;//from   ww w  .  j  a  v a 2  s  .c  om
    }

    // todo delete the user (correct response is undocumented)
    String userName = (String) req.getAttribute(ATTRIB_USERNAME_KEY);
    String weaveTimestamp = String.format("%.2f", System.currentTimeMillis() / 1000.0);
    resp.setHeader("X-Weave-Timestamp", weaveTimestamp);
    PrintWriter writer = resp.getWriter();
    resp.setContentType("text/html");
    resp.setCharacterEncoding("UTF-8");
    writer.append(userName);
}

From source file:com.headstrong.fusion.statemachine.SCXMLStateMachine.java

/**
 * Private utility method that saves the configuration in the fusion temp
 * directory./*from  w ww.jav a  2s. com*/
 * 
 * @param configuration
 *            scxml configuration.
 * @return File handler.
 * @throws IOException
 */
private File persistConfiguration(String configuration) throws IOException {
    String fusion_temp = this.bundleContext.getProperty(Properties.FUSION_TEMP);
    File directory = new File(fusion_temp);
    if (!directory.exists()) {
        directory.mkdir();
    }
    File file = new File(
            fusion_temp + "/" + "/" + "Fusion_State_Machine_" + System.currentTimeMillis() + ".xml");
    // TODO put a check on if the file already exists.
    file.createNewFile();
    PrintWriter writer = new PrintWriter(file);
    writer.append(configuration);
    writer.close();
    return file;
}

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

@Override
protected void writeContent(final PrintWriter writer) {
    final String hydrotopeFileTile = Messages
            .getString("org.kalypso.convert.namodel.manager.HydrotopManager.2"); //$NON-NLS-1$
    writer.append(hydrotopeFileTile).append('\n');

    final Collection<Catchment> catchments = m_hydroHash.getCatchments();
    for (final Catchment catchment : catchments) {
        final CatchmentInfo catchmentInfo = m_hydroHash.getHydrotopInfo(catchment);
        final String checkMsg = catchmentInfo.checkArea();
        if (checkMsg != null)
            getLogger().warning(checkMsg);

        writeCatchment(writer, catchmentInfo);
    }//from   w  w  w . j  a va  2  s.c  om
}

From source file:org.waveprotocol.box.server.robots.dataapi.BaseApiServlet.java

/**
 * Handles an {@link OperationResults} by submitting the deltas that are
 * generated and writing a response to the robot.
 *
 * @param operations the operations//from  w w  w .  j  ava2  s .  co m
 * @param results the results of the operations performed.
 * @param resp the servlet to write the response in.
 * @param version the version of the protocol to use for writing a response.
 * @throws IOException if the response can not be written.
 */
private void handleResults(List<OperationRequest> operations, OperationResults results,
        HttpServletResponse resp, ProtocolVersion version) throws IOException {
    OperationUtil.submitDeltas(results, waveletProvider, LOGGING_REQUEST_LISTENER);

    // Ensure that responses are returned in the same order as corresponding
    // requests.
    LinkedList<JsonRpcResponse> responses = Lists.newLinkedList();
    for (OperationRequest operation : operations) {
        String opId = operation.getId();
        JsonRpcResponse response = results.getResponses().get(opId);
        responses.addLast(response);
    }

    String jsonResponse = robotSerializer.serialize(responses, GsonFactory.JSON_RPC_RESPONSE_LIST_TYPE,
            version);
    LOG.fine("Returning the following Json: " + jsonResponse);

    // Write the response back through the HttpServlet
    try {
        resp.setContentType(JSON_CONTENT_TYPE);
        PrintWriter writer = resp.getWriter();
        writer.append(jsonResponse);
        writer.flush();
        resp.setStatus(HttpServletResponse.SC_OK);
    } catch (IOException e) {
        LOG.severe("IOException during writing of a response", e);
        throw e;
    }
}

From source file:org.apache.sling.hc.core.impl.servlet.HealthCheckExecutorServlet.java

private void sendJsonResponse(final Result overallResult,
        final List<HealthCheckExecutionResult> executionResults, final String jsonpCallback,
        final HttpServletResponse response, boolean includeDebug) throws IOException {
    if (StringUtils.isNotBlank(jsonpCallback)) {
        response.setContentType(CONTENT_TYPE_JSONP);
    } else {//w w  w  .j av a 2 s .c  o m
        response.setContentType(CONTENT_TYPE_JSON);
    }
    response.setCharacterEncoding("UTF-8");

    String resultJson = this.jsonSerializer.serialize(overallResult, executionResults, jsonpCallback,
            includeDebug);
    PrintWriter writer = response.getWriter();
    writer.append(resultJson);
}

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

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String subPath = (String) req.getAttribute(ATTRIB_SUBPATH_KEY);
    if (!"".equals(subPath)) {
        super.doPut(req, resp);
        return;/*from   ww  w . jav a  2  s  .  com*/
    }

    String userName = (String) req.getAttribute(ATTRIB_USERNAME_KEY);
    String body = MiscUtil.readBody(req);
    for (Enumeration enu = req.getHeaderNames(); enu.hasMoreElements();) {
        String hname = (String) enu.nextElement();
        String hval = req.getHeader(hname);
        log(String.format("HEADER (%s) : \"%s\"", hname, hval));
    }
    log("BODY:\n" + body);

    Connection dbCon = null;
    PreparedStatement st = null;
    boolean success = false;
    try {
        JSONObject obj = new JSONObject(body);
        String password = obj.getString("password");
        String email = obj.getString("email");
        dbCon = getDatabaseConnection(req);
        int modCnt = addUser(dbCon, userName, password, email);
        log("SUCCESS: " + modCnt + " " + userName);
        success = modCnt == 1;
    } catch (JSONException e) {
        log(e.getMessage(), e);
    } catch (SQLException e) {
        log(e.getMessage(), e);
    } finally {
        MiscUtil.close(st);
        MiscUtil.close(dbCon);
    }
    if (success) {
        String weaveTimestamp = String.format("%.2f", System.currentTimeMillis() / 1000.0);
        resp.setHeader("X-Weave-Timestamp", weaveTimestamp);
        PrintWriter writer = resp.getWriter();
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        writer.append(userName);
    } else {
        super.doPut(req, resp);
    }
}

From source file:org.apache.unomi.web.EventsCollectorServlet.java

private void doEvent(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Date timestamp = new Date();
    if (request.getParameter("timestamp") != null) {
        timestamp.setTime(Long.parseLong(request.getParameter("timestamp")));
    }/*from   ww w . ja v a 2 s  .c om*/

    //        logger.debug(HttpUtils.dumpRequestInfo(request));

    HttpUtils.setupCORSHeaders(request, response);

    String sessionId = request.getParameter("sessionId");
    if (sessionId == null) {
        logger.error(
                "No sessionId found in incoming request, aborting processing. See debug level for more information");
        if (logger.isDebugEnabled()) {
            logger.debug("Request dump:" + HttpUtils.dumpRequestInfo(request));
        }
        return;
    }

    Session session = profileService.loadSession(sessionId, timestamp);
    if (session == null) {
        logger.error("No session found for sessionId={}, aborting request !", sessionId);
        return;
    }

    String profileIdCookieName = "context-profile-id";

    Profile sessionProfile = session.getProfile();
    Profile profile = null;
    if (sessionProfile.getItemId() != null) {
        // Reload up-to-date profile
        profile = profileService.load(sessionProfile.getItemId());
        if (profile == null || profile instanceof Persona) {
            logger.error("No valid profile found or persona found for profileId={}, aborting request !",
                    session.getProfileId());
            return;
        }
    } else {
        // Session uses anonymous profile, try to find profile from cookie
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (profileIdCookieName.equals(cookie.getName())) {
                profile = profileService.load(cookie.getValue());
            }
        }
        if (profile == null) {
            logger.error("No valid profile found or persona found for profileId={}, aborting request !",
                    session.getProfileId());
            return;
        }
    }

    String payload = HttpUtils.getPayload(request);
    if (payload == null) {
        logger.error("No event payload found for request, aborting !");
        return;
    }

    ObjectMapper mapper = CustomObjectMapper.getObjectMapper();
    JsonFactory factory = mapper.getFactory();
    EventsCollectorRequest events = null;
    try {
        events = mapper.readValue(factory.createParser(payload), EventsCollectorRequest.class);
    } catch (Exception e) {
        logger.error("Cannot read payload " + payload, e);
        return;
    }
    if (events == null || events.getEvents() == null) {
        logger.error("No events found in payload");
        return;
    }

    String thirdPartyId = eventService.authenticateThirdPartyServer(
            ((HttpServletRequest) request).getHeader("X-Unomi-Peer"), request.getRemoteAddr());

    int changes = 0;

    List<String> filteredEventTypes = privacyService.getFilteredEventTypes(profile.getItemId());

    for (Event event : events.getEvents()) {
        if (event.getEventType() != null) {
            Event eventToSend = new Event(event.getEventType(), session, profile, event.getScope(),
                    event.getSource(), event.getTarget(), event.getProperties(), timestamp);
            if (sessionProfile.isAnonymousProfile()) {
                // Do not keep track of profile in event
                eventToSend.setProfileId(null);
            }

            if (!eventService.isEventAllowed(event, thirdPartyId)) {
                logger.debug("Event is not allowed : {}", event.getEventType());
                continue;
            }
            if (filteredEventTypes != null && filteredEventTypes.contains(event.getEventType())) {
                logger.debug("Profile is filtering event type {}", event.getEventType());
                continue;
            }

            eventToSend.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request);
            eventToSend.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response);
            logger.debug("Received event " + event.getEventType() + " for profile=" + sessionProfile.getItemId()
                    + " session=" + session.getItemId() + " target=" + event.getTarget() + " timestamp="
                    + timestamp);
            int eventChanged = eventService.send(eventToSend);
            //if the event execution changes the profile
            if ((eventChanged & EventService.PROFILE_UPDATED) == EventService.PROFILE_UPDATED) {
                profile = eventToSend.getProfile();
            }
            changes |= eventChanged;
        }
    }

    if ((changes & EventService.PROFILE_UPDATED) == EventService.PROFILE_UPDATED) {
        profileService.save(profile);
    }
    if ((changes & EventService.SESSION_UPDATED) == EventService.SESSION_UPDATED) {
        profileService.saveSession(session);
    }

    PrintWriter responseWriter = response.getWriter();
    responseWriter.append("{\"updated\":" + changes + "}");
    responseWriter.flush();
}

From source file:ly.count.android.api.ConnectionProcessor.java

URLConnection urlConnectionForEventData(final String eventData) throws IOException {
    final String urlStr = serverURL_ + "/i?" + eventData;
    final URL url = new URL(urlStr);
    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(CONNECT_TIMEOUT_IN_MILLISECONDS);
    conn.setReadTimeout(READ_TIMEOUT_IN_MILLISECONDS);
    conn.setUseCaches(false);//from   w ww .  j ava  2  s.com
    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 {
        conn.setDoOutput(false);
    }
    return conn;
}

From source file:org.talend.components.marketo.runtime.client.MarketoBulkExecClient.java

public BulkImportResult executePostFileRequest(Class<?> resultClass, String filePath) throws MarketoException {
    String boundary = "Talend_tMarketoBulkExec_" + String.valueOf(System.currentTimeMillis());
    try {//  www.j a  v  a2s  . c  o m
        URL url = new URL(current_uri.toString());
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod("POST");
        urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        urlConn.setRequestProperty("accept", "text/json");
        urlConn.setDoOutput(true);
        String requestBody = buildRequest(filePath); // build the request body
        PrintWriter wr = new PrintWriter(new OutputStreamWriter(urlConn.getOutputStream()));
        wr.append("--" + boundary + "\r\n");
        wr.append("Content-Disposition: form-data; name=\"file\";filename=\"" + filePath + "\";\r\n");
        wr.append("Content-type: text/plain; charset=\"utf-8\"\r\n");
        wr.append("Content-Transfer-Encoding: text/plain\r\n");
        wr.append("MIME-Version: 1.0\r\n");
        wr.append("\r\n");
        wr.append(requestBody);
        wr.append("\r\n");
        wr.append("--" + boundary);
        wr.flush();
        wr.close();
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            InputStream inStream = urlConn.getInputStream();
            InputStreamReader reader = new InputStreamReader(inStream);
            Gson gson = new Gson();
            return (BulkImportResult) gson.fromJson(reader, resultClass);
        } else {
            LOG.error("POST request failed: {}", responseCode);
            throw new MarketoException(REST, responseCode,
                    "Request failed! Please check your request setting!");
        }
    } catch (IOException e) {
        LOG.error("POST request failed: {}", e.getMessage());
        throw new MarketoException(REST, e.getMessage());
    }
}

From source file:org.openspotlight.graph.query.console.command.dynamic.QueryCommand.java

/**
 * Executes query. If there is any problem during executing, it display its error message. Queries that needs variables
 * content or target can't be executed at slql console application.
 * /*ww  w.j a va2  s .c om*/
 * @param reader the reader
 * @param out the out
 * @param state the state
 * @param query the query
 * @param outputFileName the output file name
 */
protected void executeQuery(final ConsoleReader reader, final PrintWriter out, final ConsoleState state,
        final String query, final String outputFileName) {
    try {
        final QueryText slqlText = state.getSession().createQueryText(query);
        if (!slqlText.hasTarget() && slqlText.getVariables() == null) {
            final QueryResult result = slqlText.execute();
            final String outputString = generateOutput(result.getNodes(), state.getAdditionalProperties());
            out.println(outputString);
            if (outputFileName != null) {
                final File outputFile = new File(outputFileName);
                outputFile.createNewFile();
                final PrintWriter fileOut = new PrintWriter(outputFile);
                fileOut.append("Query: " + query);
                fileOut.append("\n\n");
                fileOut.append(outputString);
                fileOut.flush();
                fileOut.close();
            }
        } else if (slqlText.hasTarget()) {
            out.println("ERROR: can't execute queries with target.");
        } else if (slqlText.getVariables() == null) {
            out.println("ERROR: can't execute queries with variables.");
        }
    } catch (final Throwable e) {
        out.print("ERROR: ");
        out.println(e.getMessage());
    }
    out.flush();
}