Example usage for javax.servlet ServletOutputStream println

List of usage examples for javax.servlet ServletOutputStream println

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream println.

Prototype


public void println(double d) throws IOException 

Source Link

Document

Writes a double value to the client, followed by a carriage return-line feed (CRLF).

Usage

From source file:edu.cornell.mannlib.vitro.webapp.controller.SparqlQueryServlet.java

private void doNoModelInContext(HttpServletResponse res) {
    try {//from  ww  w .j  a v  a2 s.c  o m
        res.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
        ServletOutputStream sos = res.getOutputStream();
        sos.println("<html><body>this service is not supporeted by the current "
                + "webapp configuration. A jena model is required in the servlet context.</body></html>");
    } catch (IOException e) {
        log.error("Could not write to ServletOutputStream");
    }
}

From source file:org.xchain.framework.servlet.XChainManager.java

/**
 * Handles requests to unknown command./* w  w  w. ja  v a2  s. c  o  m*/
 */
protected void unknownCommand(HttpServletRequest request, HttpServletResponse response, String commandName)
        throws ServletException, IOException {
    ServletOutputStream out = response.getOutputStream();
    out.println("<html>");
    out.println("  <head>");
    out.println("  </head>");
    out.println("  <body>");
    out.println("    UNKNOWN_COMMAND:" + commandName);
    out.println("  </body>");
    out.println("</html>");
}

From source file:org.xchain.framework.servlet.XChainManager.java

/**
 * Handles requests to the management screen.
 *//*from   ww  w . j  a  va  2s .c  o  m*/
protected void managementScreen(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletOutputStream out = response.getOutputStream();

    out.println("<html>");
    out.println("  <head>");
    out.println("  </head>");
    out.println("  <body>");
    out.println("    NOT IMPLEMENTED");
    out.println("  </body>");
    out.println("</html>");
}

From source file:pivotal.au.se.gemfirexdweb.controller.CreateGatewayReceiverController.java

@RequestMapping(value = "/creategatewayreceiver", method = RequestMethod.POST)
public String createGatewayReceiverAction(
        @ModelAttribute("gatewayReceiverAttribute") NewGatewayReceiver gatewayReceiverAttribute, Model model,
        HttpServletResponse response, HttpServletRequest request, HttpSession session) throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {//from   w  w  w.ja  v  a2 s .  com
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to action an event for create Gateway Receiver");

    String gatewayReceiverName = gatewayReceiverAttribute.getGatewayReceiverName();

    logger.debug("New Gateway Receiver Name = " + gatewayReceiverName);

    // perform some action here with what we have
    String submit = request.getParameter("pSubmit");
    boolean needCloseBracket = false;

    if (submit != null) {
        // build create HDFS Store SQL
        StringBuffer createGatewayReceiver = new StringBuffer();

        createGatewayReceiver.append("CREATE GATEWAYRECEIVER " + gatewayReceiverName + " (\n");

        if (!checkIfParameterEmpty(request, "bindAddress")) {
            createGatewayReceiver.append("BINDADDRESS '" + gatewayReceiverAttribute.getBindAddress() + "' \n");
            needCloseBracket = true;
        }

        if (!checkIfParameterEmpty(request, "startPort")) {
            createGatewayReceiver.append("STARTPORT " + gatewayReceiverAttribute.getStartPort() + " \n");
            needCloseBracket = true;
        }

        if (!checkIfParameterEmpty(request, "endPort")) {
            createGatewayReceiver.append("ENDPORT " + gatewayReceiverAttribute.getEndPort() + " \n");
            needCloseBracket = true;
        }

        if (!checkIfParameterEmpty(request, "socketBufferSize")) {
            createGatewayReceiver
                    .append("SOCKETBUFFERSIZE " + gatewayReceiverAttribute.getSocketBufferSize() + " \n");
            needCloseBracket = true;
        }

        if (!checkIfParameterEmpty(request, "maxTimeBetweenPings")) {
            createGatewayReceiver
                    .append("MAXTIMEBETWEENPINGS " + gatewayReceiverAttribute.getMaxTimeBetweenPings() + " \n");
            needCloseBracket = true;
        }

        if (needCloseBracket) {
            createGatewayReceiver.append(") ");
        }

        if (!checkIfParameterEmpty(request, "serverGroups")) {
            createGatewayReceiver
                    .append("SERVER GROUPS (" + gatewayReceiverAttribute.getServerGroups() + ") \n");
        }

        if (submit.equalsIgnoreCase("create")) {
            Result result = new Result();

            logger.debug("Creating gateway receiver as -> " + createGatewayReceiver.toString());

            result = GemFireXDWebDAOUtil.runCommand(createGatewayReceiver.toString(),
                    (String) session.getAttribute("user_key"));

            model.addAttribute("result", result);

        } else if (submit.equalsIgnoreCase("Show SQL")) {
            logger.debug("Create Async SQL as follows as -> " + createGatewayReceiver.toString());
            model.addAttribute("sql", createGatewayReceiver.toString());
        } else if (submit.equalsIgnoreCase("Save to File")) {
            response.setContentType(SAVE_CONTENT_TYPE);
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + String.format(FILENAME, gatewayReceiverName));

            ServletOutputStream out = response.getOutputStream();
            out.println(createGatewayReceiver.toString());
            out.close();
            return null;
        }

    }

    // This will resolve to /WEB-INF/jsp/create-gatewayreceiver.jsp
    return "create-gatewayreceiver";
}

From source file:DisplayBlobServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    Blob photo = null;//from  w  w  w .j av  a2 s. c om
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;

    String query = "select photo from MyPictures where  id = '001'";
    ServletOutputStream out = response.getOutputStream();

    try {
        conn = getHSQLConnection();
    } catch (Exception e) {
        response.setContentType("text/html");
        out.println("<html><head><title>Person Photo</title></head>");
        out.println("<body><h1>Database Connection Problem.</h1></body></html>");
        return;
    }

    try {
        stmt = conn.createStatement();
        rs = stmt.executeQuery(query);
        if (rs.next()) {
            photo = rs.getBlob(1);
        } else {
            response.setContentType("text/html");
            out.println("<html><head><title>Person Photo</title></head>");
            out.println("<body><h1>No photo found for id= 001 </h1></body></html>");
            return;
        }

        response.setContentType("image/gif");
        InputStream in = photo.getBinaryStream();
        int length = (int) photo.length();

        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        while ((length = in.read(buffer)) != -1) {
            System.out.println("writing " + length + " bytes");
            out.write(buffer, 0, length);
        }

        in.close();
        out.flush();
    } catch (SQLException e) {
        response.setContentType("text/html");
        out.println("<html><head><title>Error: Person Photo</title></head>");
        out.println("<body><h1>Error=" + e.getMessage() + "</h1></body></html>");
        return;
    } finally {
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.sigmah.server.auth.SigmahAuthDictionaryServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    /*// w w w  . j a va  2s  .  co  m
     * Initialize quartz scheduler here, because it needs link{EntityManager}
     * which can only accessed in request scope. 
     */
    injector.getInstance(GlobalExportJobActivator.class);

    if (req.getParameter("remove") != null) {
        final Cookie cookie = new Cookie("authToken", "");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        resp.addCookie(cookie);

    } else {
        final HashMap<String, String> parameters = new HashMap<String, String>();
        parameters.put(SigmahAuthProvider.SHOW_MENUS, String.valueOf(false));

        final String authToken = getAuthToken(req.getCookies());
        if (authToken != null) {
            final AuthenticationDAO authDAO = injector.getInstance(AuthenticationDAO.class);
            final Authentication auth = authDAO.findById(authToken);

            final User user = auth.getUser();

            if (user.getOrganization() == null) {
                log.error(String.format(
                        "User with id=%d, email=%s has no organization set, cannot log into the Sigmah interface.",
                        user.getId(), user.getEmail()));
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Your account is not configured for use with Sigmah");
                return;
            }

            parameters.put(SigmahAuthProvider.USER_ID, Integer.toString(user.getId()));
            parameters.put(SigmahAuthProvider.USER_TOKEN, '"' + authToken + '"');
            parameters.put(SigmahAuthProvider.USER_EMAIL, '"' + user.getEmail() + '"');
            parameters.put(SigmahAuthProvider.USER_NAME, '"' + user.getName() + '"');
            parameters.put(SigmahAuthProvider.USER_FIRST_NAME, '"' + user.getFirstName() + '"');
            parameters.put(SigmahAuthProvider.USER_ORG_ID, Integer.toString(user.getOrganization().getId()));
            parameters.put(SigmahAuthProvider.USER_ORG_UNIT_ID,
                    Integer.toString(user.getOrgUnitWithProfiles().getOrgUnit().getId()));

            // Custom serialization of the profile.
            final ProfileDTO aggregatedProfile = aggregateProfiles(user, null, injector);
            final String aggregatedProfileAsString = ProfileUtils.writeProfile(aggregatedProfile);
            parameters.put(SigmahAuthProvider.USER_AG_PROFILE, '"' + aggregatedProfileAsString + '"');
            if (log.isDebugEnabled()) {
                log.debug("[doGet] Writes aggregated profile: " + aggregatedProfile);
                log.debug("[doGet] String representation of the profile: " + aggregatedProfileAsString);
            }
        }

        final Properties properties = injector.getInstance(Properties.class);
        parameters.put(SigmahAuthProvider.VERSION_NUMBER, '"' + properties.getProperty("version.number") + '"');

        final Charset utf8 = Charset.forName("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        final ServletOutputStream output = resp.getOutputStream();
        output.println("var " + SigmahAuthProvider.DICTIONARY_NAME + " = {");

        boolean first = true;
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            if (first)
                first = false;
            else
                output.println(",");

            output.print(entry.getKey() + ": ");
            output.write(entry.getValue().getBytes(utf8));
        }

        output.println("};");
    }
}

From source file:pivotal.au.se.gemfirexdweb.controller.CreateTriggerController.java

@RequestMapping(value = "/createtrigger", method = RequestMethod.POST)
public String createTriggerAction(@ModelAttribute("triggerAttribute") NewTrigger triggerAttribute, Model model,
        HttpServletResponse response, HttpServletRequest request, HttpSession session) throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {//  www  .j  a va  2  s. c  o m
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to action an event for create Trigger");

    TableDAO tableDAO = GemFireXDWebDAOFactory.getTableDAO();

    List<Table> tables = tableDAO.retrieveTableList((String) session.getAttribute("schema"), null,
            (String) session.getAttribute("user_key"), "tables");

    model.addAttribute("tables", tables);

    String schema = triggerAttribute.getSchemaName().trim();

    if (schema.length() == 0) {
        schema = (String) session.getAttribute("schema");
    }

    logger.debug("New Trigger schema name = " + schema);
    logger.debug("New Trigger name = " + triggerAttribute.getTriggerName());

    // perform some action here with what we have
    String submit = request.getParameter("pSubmit");

    if (submit != null) {
        // build create HDFS Store SQL
        StringBuffer createTrigger = new StringBuffer();

        createTrigger.append("CREATE TRIGGER " + schema + "." + triggerAttribute.getTriggerName() + " \n");
        createTrigger.append(triggerAttribute.getBeforeOrAfter() + " \n");
        createTrigger.append(triggerAttribute.getType() + " \n");

        if (!checkIfParameterEmpty(request, "columnList")) {
            createTrigger.append("OF " + triggerAttribute.getColumnList() + " \n");
        }

        createTrigger.append("ON " + triggerAttribute.getTableName() + " \n");

        if (!checkIfParameterEmpty(request, "referencingOldClause")) {
            createTrigger.append("REFERENCING OLD AS " + triggerAttribute.getReferencingOldClause() + " \n");
        }

        if (!checkIfParameterEmpty(request, "referencingNewClause")) {
            createTrigger.append("REFERENCING NEW AS " + triggerAttribute.getReferencingNewClause() + " \n");
        }

        createTrigger.append(triggerAttribute.getForEachRow() + " \n");

        if (!checkIfParameterEmpty(request, "triggerDefinition")) {
            createTrigger.append(triggerAttribute.getTriggerDefinition() + " \n");
        }

        if (submit.equalsIgnoreCase("create")) {
            Result result = new Result();

            logger.debug("Creating Trigger as -> " + createTrigger.toString());

            result = GemFireXDWebDAOUtil.runCommand(createTrigger.toString(),
                    (String) session.getAttribute("user_key"));

            model.addAttribute("result", result);
            model.addAttribute("tableName", triggerAttribute.getTableName());

        } else if (submit.equalsIgnoreCase("Show SQL")) {
            logger.debug("Create Trigger SQL as follows as -> " + createTrigger.toString());
            model.addAttribute("sql", createTrigger.toString());
            model.addAttribute("tableName", triggerAttribute.getTableName());
        } else if (submit.equalsIgnoreCase("Save to File")) {
            response.setContentType(SAVE_CONTENT_TYPE);
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + String.format(FILENAME, triggerAttribute.getTriggerName()));

            ServletOutputStream out = response.getOutputStream();
            out.println(createTrigger.toString());
            out.close();
            return null;
        }

    }

    // This will resolve to /WEB-INF/jsp/create-trigger.jsp
    return "create-trigger";
}

From source file:com.jsquant.servlet.YahooFinanceProxyCalc.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    /* http://ichart.finance.yahoo.com/table.csv?a=00&c=2005&b=01&e=03&d=05&g=d&f=2008&ignore=.csv&s=GOOG
    Date,Open,High,Low,Close,Volume,Adj Close
    2008-06-03,576.50,580.50,560.61,567.30,4305300,567.30
    2008-06-02,582.50,583.89,571.27,575.00,3674200,575.00
    *//*from w w  w .ja v  a 2  s .  c  o  m*/
    int fromMM = Integer.valueOf(request.getParameter("a")); // 00 == January
    int fromDD = Integer.valueOf(request.getParameter("b"));
    int fromYYYY = Integer.valueOf(request.getParameter("c"));
    int toMM = Integer.valueOf(request.getParameter("d"));
    int toDD = Integer.valueOf(request.getParameter("e"));
    int toYYYY = Integer.valueOf(request.getParameter("f"));
    String resolution = request.getParameter("g").substring(0, 1); // == "d"ay "w"eek "m"onth "y"ear
    ValidationUtils.validateResolution(resolution);
    String symbol = request.getParameter("s");
    ValidationUtils.validateSymbol(symbol);
    String queryString = String.format("a=%02d&b=%02d&c=%d&d=%02d&e=%02d&f=%d&g=%s&s=%s&ignore=.csv", fromMM,
            fromDD, fromYYYY, toMM, toDD, toYYYY,
            URLEncoder.encode(resolution, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING),
            URLEncoder.encode(symbol, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING));
    String cacheKey = String.format("%02d%02d%d-%02d%02d%d-%s-%s-%tF-calc.csv.gz", fromMM, fromDD, fromYYYY,
            toMM, toDD, toYYYY,
            URLEncoder.encode(resolution, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING),
            URLEncoder.encode(symbol, JsquantContextListener.YAHOO_FINANCE_URL_ENCODING), new Date()); // include server date to limit to 1 day, for case where future dates might return less data, but fill cache

    FileCache fileCache = JsquantContextListener.getFileCache(request);
    String responseBody = fileCache.get(cacheKey);
    if (responseBody == null) {
        HttpGet httpget = new HttpGet("http://ichart.finance.yahoo.com/table.csv?" + queryString);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        log.debug("requesting uri=" + httpget.getURI());
        responseBody = JsquantContextListener.getHttpClient(request).execute(httpget, responseHandler);
        //httpget.setReleaseTrigger(releaseTrigger); // no need to close?
        fileCache.put(cacheKey, responseBody);
    }

    String[] lines = responseBody.split("\n");
    List<Stock> dayPrices = new ArrayList<Stock>();
    int index = 0;
    for (String line : lines)
        if (index++ > 0 && line.length() > 0)
            dayPrices.add(new Stock(line));
    Collections.reverse(dayPrices);

    index = 0;
    BigDecimal allTimeHighClose = new BigDecimal(0);
    BigDecimal stopAt = null;
    BigDecimal boughtPrice = null;
    Stock sPrev = null;
    for (Stock s : dayPrices) {
        allTimeHighClose = allTimeHighClose.max(s.adjClose);
        s.allTimeHighClose = allTimeHighClose;
        if (index > 0) {
            sPrev = dayPrices.get(index - 1);
            //true range = max(high,closeprev) - min(low,closeprev)
            s.trueRange = s.high.max(sPrev.adjClose).subtract(s.low.min(sPrev.adjClose));
        }
        int rng = 10;
        if (index > rng) {
            BigDecimal sum = new BigDecimal(0);
            for (Stock s2 : dayPrices.subList(index - rng, index))
                sum = sum.add(s2.trueRange);
            s.ATR10 = sum.divide(new BigDecimal(rng));

            if (allTimeHighClose.equals(s.adjClose)) {
                stopAt = s.adjClose.subtract(s.ATR10);
            }
        }

        s.stopAt = stopAt;

        if (s.stopAt != null && s.adjClose.compareTo(s.stopAt) == -1 && sPrev != null
                && (sPrev.order == OrderAction.BUY || sPrev.order == OrderAction.HOLD)) {
            s.order = OrderAction.SELL;
            s.soldPrice = s.adjClose;
            s.soldDifference = s.soldPrice.subtract(boughtPrice);
        } else if (allTimeHighClose.equals(s.adjClose) && stopAt != null && sPrev != null
                && sPrev.order == OrderAction.IGNORE) {
            s.order = OrderAction.BUY;
            boughtPrice = s.adjClose;
            s.boughtPrice = boughtPrice;
        } else if (sPrev != null && (sPrev.order == OrderAction.HOLD || sPrev.order == OrderAction.BUY)) {
            s.order = OrderAction.HOLD;
        } else {
            s.order = OrderAction.IGNORE;
        }
        index++;
    }

    ServletOutputStream out = response.getOutputStream();
    out.println(lines[0]
            + ",Split,All Time High Close,True Range,ATR10,Stop At,Order State,Bought Price,Sold Price,Sold Difference");
    for (Stock s : dayPrices)
        out.println(s.getCSV());

}

From source file:com.controlj.green.bulktrend.trendserver.SearchServlet.java

private void writeRawCell(ServletOutputStream out, String cssClass, String content) throws IOException {
    out.print("      <td class='" + cssClass + "'>");
    out.print(content);/* www . j  a  v a2 s.c  om*/
    out.println("      </td>");

}

From source file:com.controlj.green.bulktrend.trendserver.SearchServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ParameterizedTrendAcceptor filter = getFilter(req);

    SystemConnection connection = null;//from   w  w  w . ja  v a  2 s.  c  o m
    try {
        connection = DirectAccess.getDirectAccess().getUserSystemConnection(req);
    } catch (InvalidConnectionRequestException e) {
        throw new ServletException("Error getting Add-On connection", e);
    }

    TrendSourceFinder finder = new TrendSourceFinder(connection);

    Collection<TrendSourceInfo> trends;
    try {
        trends = finder.findTrends(finder.getIdForPath(req.getParameter(PARAM_PATH)), filter);
    } catch (SystemException e) {
        writeErrorInRow(resp, e.getMessage());
        throw new ServletException(e);
    } catch (ActionExecutionException e) {
        writeErrorInRow(resp, e.getMessage());
        throw new ServletException(e);
    }

    ServletOutputStream out = resp.getOutputStream();
    disableCache(resp);

    for (TrendSourceInfo trend : trends) {
        out.println("   <tr>");
        writeStringCell(out, "displaypath", trend.getDisplayPath());
        writeStringCell(out, "type", trend.getType().toString());
        writeBooleanCell(out, "enabled", trend.isEnabled());
        writeRawCell(out, "sampleinterval", trend.isCOV() ? "&nbsp;" : mSecToTime(trend.getSampleInterval()));
        writeBooleanCell(out, "cov", trend.isCOV());
        writeStringCell(out, "buffersize", Integer.toString(trend.getBufferSize()));
        writeBooleanCell(out, "historian", trend.isHistorianEnabled());
        writeStringCell(out, "trigger", Integer.toString(trend.getHistorianTrigger()));
        writeRawCell(out, "uploadtime",
                trend.isCOV() && trend.isEnabled() && trend.isHistorianEnabled() ? "&nbsp;"
                        : mSecToTime(trend.getHistorianUploadTime()));
        writeRawCell(out, "lookupstring", prepareLookupStringContent(trend.getLookupString()));
        out.println("   <tr>");
    }
}