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:io.selendroid.server.common.SelendroidResponse.java

private JSONObject buildErrorValue(Throwable e, int status, String messagePrefix) throws JSONException {
    JSONObject errorValue = new JSONObject();
    errorValue.put("class", e.getClass().getCanonicalName());

    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);

    if (messagePrefix != null) {
        printWriter.append(messagePrefix);
    }//from w  w w.j  a  va  2 s .co  m

    // Also include the Selendroid stack trace. Only do this in case of unknown errors for easier debugging.
    // In case of an expected error the stack trace is unnecessary and users often find it confusing.
    if (status == StatusCode.UNKNOWN_ERROR.getCode()) {
        e.printStackTrace(printWriter);
    } else {
        printWriter.append(e.getMessage());
    }

    errorValue.put("message", stringWriter.toString());

    /*
      The WebDriver protocol does not define a way to add exception stack traces to responses.
      The workaround above puts the stack trace in the response message.
      Apparently Selenium's BeanToJsonConverter would also work.
            
      JSONArray stackTrace = new JSONArray();
      for (StackTraceElement el : t.getStackTrace()) {
          JSONObject frame = new JSONObject();
          frame.put("lineNumber", el.getLineNumber());
          frame.put("className", el.getClassName());
          frame.put("methodName", el.getMethodName());
          frame.put("fileName", el.getFileName());
          stackTrace.put(frame);
      }
      errorValue.put("stackTrace", stackTrace);
    */
    return errorValue;
}

From source file:com.ikon.servlet.CssServlet.java

/**
 * //from   w ww  .  j a  v a 2s  . c om
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String path = request.getPathInfo();
    OutputStream os = null;

    try {
        if (path.length() > 1) {
            String[] foo = path.substring(1).split("/");

            if (foo.length > 1) {
                String context = foo[0];
                String name = foo[1];
                Css css = CssDAO.getInstance().findByContextAndName(context, name);

                if (css == null) {
                    InputStream is = null;

                    try {
                        if (Css.CONTEXT_FRONTEND.equals(context)) {

                        } else if (Css.CONTEXT_EXTENSION.equals(context)) {

                        }
                        /*
                        if (is != null) {
                           css = new Css();
                           css.setContent(IOUtils.toString(is));
                           css.setContext(context);
                           css.setName(name);
                           css.setActive(true);
                        }
                        */
                    } finally {
                        IOUtils.closeQuietly(is);
                    }
                }

                if (css != null) {
                    // Prepare file headers
                    WebUtils.prepareSendFile(request, response, css.getName() + ".css", MimeTypeConfig.MIME_CSS,
                            false);
                    PrintWriter out = new PrintWriter(
                            new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
                    out.append(css.getContent());
                    out.flush();
                }
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(os);
    }
}

From source file:com.openkm.servlet.CssServlet.java

/**
 * //from w  ww.j a va 2 s .  c o  m
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String path = request.getPathInfo();
    OutputStream os = null;

    try {
        if (path.length() > 1) {
            String[] foo = path.substring(1).split("/");

            if (foo.length > 1) {
                String context = foo[0];
                String name = foo[1];
                Css css = CssDAO.getInstance().findByContextAndName(context, name);

                if (css == null) {
                    InputStream is = null;

                    try {
                        if (Css.CONTEXT_FRONTEND.equals(context)) {

                        } else if (Css.CONTEXT_EXTENSION.equals(context)) {
                            if ("htmlEditor".equals(name)) {
                                is = getServletContext().getResourceAsStream("/css/tiny_mce/content.css");
                            }
                        }

                        if (is != null) {
                            css = new Css();
                            css.setContent(IOUtils.toString(is));
                            css.setContext(context);
                            css.setName(name);
                            css.setActive(true);
                        }
                    } finally {
                        IOUtils.closeQuietly(is);
                    }
                }

                if (css != null) {
                    // Prepare file headers
                    WebUtils.prepareSendFile(request, response, css.getName() + ".css", MimeTypeConfig.MIME_CSS,
                            false);
                    PrintWriter out = new PrintWriter(
                            new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
                    out.append(css.getContent());
                    out.flush();
                }
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(os);
    }
}

From source file:org.wso2.carbon.analytics.servlet.AnalyticsRecordProcessor.java

/**
 * Get record count//from   w  w w . j ava2  s .c  o m
 *
 * @param req  HttpRequest which has the required parameters to do the operation.
 * @param resp HttpResponse which returns the result of the intended operation.
 * @throws ServletException
 * @throws IOException
 */

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String sessionId = req.getHeader(AnalyticsAPIConstants.SESSION_ID);
    if (sessionId == null || sessionId.trim().isEmpty()) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
    } else {
        try {
            ServiceHolder.getAuthenticator().validateSessionId(sessionId);
        } catch (AnalyticsAPIAuthenticationException e) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
        }
        String operation = req.getParameter(AnalyticsAPIConstants.OPERATION);
        boolean securityEnabled = Boolean
                .parseBoolean(req.getParameter(AnalyticsAPIConstants.ENABLE_SECURITY_PARAM));
        if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.GET_RECORD_COUNT_OPERATION)) {
            int tenantIdParam = MultitenantConstants.INVALID_TENANT_ID;
            if (!securityEnabled)
                tenantIdParam = Integer.parseInt(req.getParameter(AnalyticsAPIConstants.TENANT_ID_PARAM));
            String userName = req.getParameter(AnalyticsAPIConstants.USERNAME_PARAM);
            String tableName = req.getParameter(AnalyticsAPIConstants.TABLE_NAME_PARAM);
            long timeFrom = Long.parseLong(req.getParameter(AnalyticsAPIConstants.TIME_FROM_PARAM));
            long timeTo = Long.parseLong(req.getParameter(AnalyticsAPIConstants.TIME_TO_PARAM));
            try {
                long recordCount;
                if (!securityEnabled)
                    recordCount = ServiceHolder.getAnalyticsDataService().getRecordCount(tenantIdParam,
                            tableName, timeFrom, timeTo);
                else
                    recordCount = ServiceHolder.getSecureAnalyticsDataService().getRecordCount(userName,
                            tableName, timeFrom, timeTo);
                PrintWriter outputWriter = resp.getWriter();
                outputWriter.append(AnalyticsAPIConstants.RECORD_COUNT).append(AnalyticsAPIConstants.SEPARATOR)
                        .append(String.valueOf(recordCount));
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (AnalyticsException e) {
                resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, e.getMessage());
            }
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                    "unsupported operation performed with get request!");
            log.error("unsupported operation performed : " + operation + " with get request!");
        }
    }
}

From source file:org.uberfire.server.UberfireServlet.java

private void loadHeader(PrintWriter writer) {
    final String content = (String) TemplateRuntime.execute(headerTemplate);
    writer.append(content);
}

From source file:org.uberfire.server.UberfireServlet.java

private void loadFooter(PrintWriter writer) {
    final String content = (String) TemplateRuntime.execute(footerTemplate);
    writer.append(content);
}

From source file:org.wso2.carbon.analytics.servlet.AnalyticsTableProcessor.java

/**
 * Get the all tables for tenant or check table exists
 *
 * @param req HttpRequest which has the required parameters to do the operation.
 * @param resp HttpResponse which returns the result of the intended operation.
 * @throws ServletException/*from   w w w .  j  ava2s .c  o  m*/
 * @throws IOException
 */
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String sessionId = req.getHeader(AnalyticsAPIConstants.SESSION_ID);
    if (sessionId == null || sessionId.trim().isEmpty()) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
    } else {
        try {
            ServiceHolder.getAuthenticator().validateSessionId(sessionId);
        } catch (AnalyticsAPIAuthenticationException e) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No session id found, Please login first!");
        }
        String operation = req.getParameter(AnalyticsAPIConstants.OPERATION);
        boolean securityEnabled = Boolean
                .parseBoolean(req.getParameter(AnalyticsAPIConstants.ENABLE_SECURITY_PARAM));
        int tenantIdParam = MultitenantConstants.INVALID_TENANT_ID;
        if (!securityEnabled)
            tenantIdParam = Integer.parseInt(req.getParameter(AnalyticsAPIConstants.TENANT_ID_PARAM));
        String userName = req.getParameter(AnalyticsAPIConstants.USERNAME_PARAM);
        if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.TABLE_EXISTS_OPERATION)) {
            String tableName = req.getParameter(AnalyticsAPIConstants.TABLE_NAME_PARAM);
            try {
                boolean tableExists;
                if (!securityEnabled)
                    tableExists = ServiceHolder.getAnalyticsDataService().tableExists(tenantIdParam, tableName);
                else
                    tableExists = ServiceHolder.getSecureAnalyticsDataService().tableExists(userName,
                            tableName);
                PrintWriter output = resp.getWriter();
                output.append(AnalyticsAPIConstants.TABLE_EXISTS).append(AnalyticsAPIConstants.SEPARATOR)
                        .append(String.valueOf(tableExists));
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (AnalyticsException e) {
                resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, e.getMessage());
            }
        } else if (operation != null
                && operation.trim().equalsIgnoreCase(AnalyticsAPIConstants.LIST_TABLES_OPERATION)) {
            try {
                List<String> tableNames;
                if (!securityEnabled)
                    tableNames = ServiceHolder.getAnalyticsDataService().listTables(tenantIdParam);
                else
                    tableNames = ServiceHolder.getSecureAnalyticsDataService().listTables(userName);
                resp.getOutputStream().write(GenericUtils.serializeObject(tableNames));
                resp.setStatus(HttpServletResponse.SC_OK);
            } catch (AnalyticsException e) {
                resp.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, e.getMessage());
            }
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                    "unsupported operation performed with get request!");
            log.error("unsupported operation performed : " + operation + " with get request!");
        }
    }
}

From source file:org.apache.commons.jci.examples.serverpages.ServerPageServlet.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log("Request " + request.getRequestURI());

    final CompilationResult result = jspListener.getCompilationResult();
    final CompilationProblem[] errors = result.getErrors();

    if (errors.length > 0) {

        // if there are errors we provide the compilation errors instead of the jsp page

        final PrintWriter out = response.getWriter();

        out.append("<html><body>");

        for (CompilationProblem problem : errors) {
            out.append(problem.toString()).append("<br/>").append('\n');
        }//ww w . j a v  a  2  s .co m

        out.append("</body></html>");

        out.flush();
        out.close();
        return;
    }

    final String servletClassname = convertRequestToServletClassname(request);

    log("Checking for serverpage " + servletClassname);

    final HttpServlet servlet = servletsByClassname.get(servletClassname);

    if (servlet == null) {
        log("No servlet  for " + request.getRequestURI());
        response.sendError(404);
        return;
    }

    log("Delegating request to " + servletClassname);

    servlet.service(request, response);
}

From source file:org.b3log.symphony.processor.FileUploadServlet.java

@Override
public void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    if (QN_ENABLED) {
        return;/*from   ww  w . jav a  2s.c o m*/
    }

    final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
    final UserQueryService userQueryService = beanManager.getReference(UserQueryService.class);
    final UserMgmtService userMgmtService = beanManager.getReference(UserMgmtService.class);

    try {
        if (null == userQueryService.getCurrentUser(req) && !userMgmtService.tryLogInWithCookie(req, resp)) {
            resp.sendError(HttpServletResponse.SC_FORBIDDEN);

            return;
        }
    } catch (final ServiceException e) {
        LOGGER.log(Level.ERROR, "Gets file failed", e);

        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        return;
    }

    final MultipartRequestInputStream multipartRequestInputStream = new MultipartRequestInputStream(
            req.getInputStream());
    multipartRequestInputStream.readBoundary();
    multipartRequestInputStream.readDataHeader("UTF-8");

    final String mimeType = multipartRequestInputStream.getLastHeader().getContentType();

    String suffix;
    String[] exts = MimeTypes.findExtensionsByMimeTypes(mimeType, false);
    if (null == exts || 0 == exts.length || exts.length > 1) {
        suffix = StringUtils.substringAfterLast(multipartRequestInputStream.getLastHeader().getFileName(), ".");
    } else {
        suffix = exts[0];
    }

    final String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;

    final OutputStream output = new FileOutputStream(UPLOAD_DIR + fileName);
    IOUtils.copy(multipartRequestInputStream, output);

    IOUtils.closeQuietly(multipartRequestInputStream);
    IOUtils.closeQuietly(output);

    final JSONObject data = new JSONObject();
    data.put("key", Latkes.getServePath() + "/upload/" + fileName);

    resp.setContentType("application/json");

    final PrintWriter writer = resp.getWriter();
    writer.append(data.toString());
    writer.flush();
    writer.close();
}

From source file:de.smartics.maven.plugin.jboss.modules.index.Indexer.java

/**
 * Writes the index.//from  w  w  w .j  a  v  a  2 s  .  c  o  m
 *
 * @throws MojoExecutionException on any problem writing the file.
 */
public void writeIndex() throws MojoExecutionException {
    final File indexFile = new File(outputDirectory, "META-INF/INDEX.LIST");
    indexFile.getParentFile().mkdirs();

    PrintWriter writer = null;
    try {
        writer = new PrintWriter(new OutputStreamWriter(FileUtils.openOutputStream(indexFile), "UTF-8"));
        for (final String fileName : fileNames) {
            writer.append(fileName).append('\n');
        }
    } catch (final IOException e) {
        throw new MojoExecutionException(
                String.format("Cannot write index file '%s'.", indexFile.getAbsoluteFile()), e);
    } finally {
        IOUtils.closeQuietly(writer);
    }
}