Example usage for javax.servlet ServletOutputStream print

List of usage examples for javax.servlet ServletOutputStream print

Introduction

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

Prototype


public void print(double d) throws IOException 

Source Link

Document

Writes a double value to the client, with no carriage return-line feed (CRLF) at the end.

Usage

From source file:org.expath.servlex.rest.DeployWebapp.java

/**
 * Deploy a XAR or a XAW file./*from  www .  j  a  va 2  s .c om*/
 * 
 * @param req The HTTP request object.
 * 
 * @param resp The HTTP response object.
 * 
 * @throws IOException In case of any I/O error.
 * 
 * @throws ServletException In case of any other error.
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    resp.setContentType("application/xml");
    resp.setCharacterEncoding("UTF-8");
    ServletOutputStream out = resp.getOutputStream();
    try {
        if (!myRepo.canInstall()) {
            error(501, "Not Implemented", "Install not supported, storage is read-only.");
        }
        // name will be null if the package is not a webapp
        String name = doInstall(req);
        out.println("<success>");
        if (name == null) {
            out.print("   <msg>The package");
        } else {
            out.print("   <msg>The webapp at ");
            out.print(name);
        }
        out.println(" has been successfully installed.</msg>");
        out.println("</success>");
    } catch (RestError ex) {
        out.println("<error>");
        out.println("   <msg>" + ex.getUserMessage() + "</msg>");
        out.println("</error>");
        ex.sendError(resp);
    } catch (ServlexException ex) {
        out.println("<error>");
        out.println("   <msg>Unexpected exception: " + ex.getMessage() + "</msg>");
        out.println("</error>");
        ex.sendError(resp);
    } catch (RuntimeException ex) {
        out.println("<error>");
        out.println("   <msg>Unexpected runtime error: " + ex.getMessage() + "</msg>");
        out.println("   <msg>Please report this to the mailing list, see Servlex logs");
        out.println("      for additional information about the error.</msg>");
        out.println("</error>");
        resp.sendError(500, "Internal Server Error");
    }
}

From source file:eu.earthobservatory.org.StrabonEndpoint.BrowseBean.java

/**
 * Processes the request made by a client of the endpoint that uses it as a
 * service.//from w  w w . j  a v  a2  s.co  m
 * 
 * @param request
 * @param response
 * @throws IOException
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    ServletOutputStream out = response.getOutputStream();

    // get the stSPARQL Query Result format (we check only the Accept
    // header)
    stSPARQLQueryResultFormat format = stSPARQLQueryResultFormat.forMIMEType(request.getHeader("accept"));

    // get the query
    String query = request.getParameter("query");

    // check for required parameters
    if (format == null || query == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.print(ResponseMessages.getXMLHeader());
        out.print(ResponseMessages.getXMLException(PARAM_ERROR));
        out.print(ResponseMessages.getXMLFooter());

    } else {
        // decode the query
        query = URLDecoder.decode(request.getParameter("query"), "UTF-8");

        response.setContentType(format.getDefaultMIMEType());
        try {
            strabonWrapper.query(query, format.getName(), out);
            response.setStatus(HttpServletResponse.SC_OK);

        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.print(ResponseMessages.getXMLHeader());
            out.print(ResponseMessages.getXMLException(e.getMessage()));
            out.print(ResponseMessages.getXMLFooter());
        }
    }

    out.flush();
}

From source file:edu.usu.sdl.openstorefront.web.action.resolution.RangeResolution.java

@Override
protected void stream(HttpServletResponse response) throws Exception {
    int bufferLength;
    if (in != null && totalLength >= 0) {
        byte[] buffer = new byte[512];
        long count = 0;

        try {//  w ww . jav  a 2s.c o m
            ServletOutputStream out = response.getOutputStream();

            List<Range<Long>> byteRanges = parseRangeHeader(request.getHeader("Range"));
            if (byteRanges == null) {
                while ((bufferLength = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bufferLength);
                }
            } else {
                for (Range<Long> byteRange : byteRanges) {
                    // See RFC 2616 section 14.16
                    if (byteRanges.size() > 1) {
                        out.print("--" + MULTIPART_BOUNDARY + "\r\n");
                        out.print("Content-Type: " + contentType + "\r\n");
                        out.print("Content-Range: bytes " + byteRange.getStart() + "-" + byteRange.getEnd()
                                + "/" + totalLength + "\r\n");
                        out.print("\r\n");
                    }
                    if (count < byteRange.getStart()) {
                        long skip;

                        skip = byteRange.getStart() - count;
                        long actualbytesSkiped = in.skip(skip);
                        log.log(Level.FINEST, MessageFormat.format("Actual Bytes Skipped from range: {0}",
                                actualbytesSkiped));
                        count += skip;
                    }
                    while ((bufferLength = in.read(buffer, 0,
                            (int) Math.min(buffer.length, byteRange.getEnd() + 1 - count))) != -1) {
                        try {
                            out.write(buffer, 0, bufferLength);
                        } catch (IOException io) {
                            //Client Abort
                            break;
                        }
                        count += bufferLength;
                        if (byteRange.getEnd() + 1 == count) {
                            break;
                        }
                    }
                    if (byteRanges.size() > 1) {
                        out.print("\r\n");
                    }
                }
                if (byteRanges.size() > 1) {
                    out.print("--" + MULTIPART_BOUNDARY + "--\r\n");
                }
            }
        } catch (IOException io) {
            //Ignore Client Abort
            log.log(Level.FINEST, "Range Resolution Error ", io);
        } finally {
            try {
                in.close();
            } catch (Exception e) {
                log.log(Level.WARNING, "Error closing input stream", e);
            }
        }
    }

}

From source file:org.wso2.sample.identity.oauth2.IDTokenExtractorServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    String idToken = req.getParameter("idToken");
    String user = null;/*from  w  w  w  .j a  v a 2 s  .c  om*/
    String sid = null;

    ServletOutputStream out = resp.getOutputStream();

    try {
        user = (String) SignedJWT.parse(idToken).getJWTClaimsSet().getSubject();

        sid = SessionIdStore.getSid(idToken);

        HttpSession session = req.getSession();
        if (user != null) {
            log.info("Logged in user: " + user);
            session.setAttribute(OAuth2Constants.LOGGED_IN_USER, user);
        }

        if (sid != null) {
            SessionIdStore.storeSession(sid, session);
        }

        resp.setContentType("application/json");
        JSONObject respData = new JSONObject();
        respData.put("user", user);

        out.print(respData.toString());

    } catch (ParseException e) {
        log.error("Invalid Token sent to IDTokenExtractorServlet.", e);
    }
}

From source file:eu.earthobservatory.org.StrabonEndpoint.DescribeBean.java

/**
 * Processes the request made from the HTML visual interface of Strabon Endpoint.
 * //w  ww. ja va2 s .co m
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
private void processVIEWRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // get the dispatcher for forwarding the rendering of the response
    RequestDispatcher dispatcher = request.getRequestDispatcher("describe.jsp");

    String query = URLDecoder.decode(request.getParameter("query"), "UTF-8");
    String format = request.getParameter("format");
    String handle = request.getParameter("handle");
    RDFFormat rdfFormat = RDFFormat.valueOf(format);

    if (format == null || query == null || rdfFormat == null) {
        request.setAttribute(ERROR, PARAM_ERROR);
        dispatcher.forward(request, response);

    } else {
        // set the query, format and handle to be selected in the rendered page
        //request.setAttribute("query", URLDecoder.decode(query, "UTF-8"));
        //request.setAttribute("format", URLDecoder.decode(reqFormat, "UTF-8"));
        //request.setAttribute("handle", URLDecoder.decode(handle, "UTF-8"));

        if ("download".equals(handle)) { // download as attachment
            ServletOutputStream out = response.getOutputStream();

            response.setContentType(rdfFormat.getDefaultMIMEType());
            response.setHeader("Content-Disposition", "attachment; filename=results."
                    + rdfFormat.getDefaultFileExtension() + "; " + rdfFormat.getCharset());

            try {
                strabonWrapper.describe(query, format, out);
                response.setStatus(HttpServletResponse.SC_OK);

            } catch (Exception e) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                out.print(ResponseMessages.getXMLHeader());
                out.print(ResponseMessages.getXMLException(e.getMessage()));
                out.print(ResponseMessages.getXMLFooter());
            }

            out.flush();

        } else //plain
        {
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();

                strabonWrapper.describe(query, format, bos);

                request.setAttribute(RESPONSE, StringEscapeUtils.escapeHtml(bos.toString()));

            } catch (Exception e) {
                request.setAttribute(ERROR, e.getMessage());
            }
            dispatcher.forward(request, response);
        }
    }
}

From source file:org.apache.roller.weblogger.ui.struts2.editor.WeblogExport.java

/**
 * Returns an output stream to the client containing a text file of all
 * entries and comments. This will include draft entries as well.
 *
 * Currently the only file format supported is mtimport.
 *///  w  w w  .  j av a  2  s . c om
public void exportEntries() throws WebloggerException {

    if (!WebloggerConfig.getBooleanProperty("weblog.export.enabled")) {
        throw new WebloggerException("ERROR: export is disabled");
    }

    try {
        WeblogEntryManager wmgr = WebloggerFactory.getWeblogger().getWeblogEntryManager();

        URLStrategy urlStrategy;
        urlStrategy = WebloggerFactory.getWeblogger().getUrlStrategy();

        List rawEntries;
        rawEntries = wmgr.getWeblogEntries(getActionWeblog(), null, null, null, null, null, null, null, null,
                null, null, 0, -1);

        List<WeblogEntryWrapper> entries;
        entries = new ArrayList<WeblogEntryWrapper>();

        for (Object entry : rawEntries) {
            entries.add(WeblogEntryWrapper.wrap((WeblogEntry) entry, urlStrategy));
        }

        // Compile the resource URL pattern using the weblog handle
        baseUrlPattern = Pattern
                .compile("(<[\\s\\S]+?=[\"'])(http[s]*?://[\\S]+/" + getActionWeblog().getHandle()
                        + "/resource/|/" + getActionWeblog().getHandle() + "/resource/)");

        // Produce the selected output format
        String output;
        output = formatAsMoveableType(entries);
        /*
        if (format.equals(ATOM_FORMAT)) {
        output = formatAsAtom(entries);
        }
        else {
        output = formatAsMoveableType(entries);
        }
        */

        if (!response.isCommitted()) {
            response.reset();

            SimpleDateFormat dateFormat;
            dateFormat = new SimpleDateFormat("MMddyyyy'T'HHmmss");

            StringBuilder fileName;
            fileName = new StringBuilder();
            fileName.append(getActionWeblog().getHandle());
            fileName.append("-entries-");
            fileName.append(dateFormat.format(System.currentTimeMillis()));

            if (format.equals(ATOM_FORMAT)) {
                fileName.append(".xml");
            } else {
                fileName.append(".txt");
            }

            // Force the browser to download the export file
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setContentLength(output.getBytes("UTF-8").length);
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName.toString() + "\"");

            ServletOutputStream outputStream;
            outputStream = response.getOutputStream();
            outputStream.print(output);
            outputStream.flush();
            outputStream.close();
        }
    } catch (WebloggerException e) {
        log.error("Error looking up entries: ", e);
    } catch (IOException e) {
        log.error("Error getting output stream: ", e);
    }
}

From source file:org.exist.security.realm.openid.AuthenticatorOpenIdServlet.java

public String authRequest(String userSuppliedString, HttpServletRequest httpReq, HttpServletResponse httpResp)
        throws IOException, ServletException {

    if (OpenIDRealm.instance == null) {
        ServletOutputStream out = httpResp.getOutputStream();
        httpResp.setContentType("text/html; charset=\"UTF-8\"");
        httpResp.addHeader("pragma", "no-cache");
        httpResp.addHeader("Cache-Control", "no-cache");

        httpResp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        out.print("<html><head>");
        out.print("<title>OpenIDServlet Error</title>");
        out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></link></head>");
        out.print("<body><div id=\"container\"><h1>Error found</h1>");

        out.print("<h2>Message:");
        out.print("OpenID realm wasn't initialized.");
        out.print("</h2>");

        //out.print(HTTPUtils.printStackTraceHTML(t));

        out.print("</div></body></html>");
        return null;
    }//from  www. j  av a2s.co m
    try {
        String returnAfterAuthentication = httpReq.getParameter("return_to");

        // configure the return_to URL where your application will receive
        // the authentication responses from the OpenID provider
        String returnToUrl = httpReq.getRequestURL().toString() + "?is_return=true&exist_return="
                + returnAfterAuthentication;

        // perform discovery on the user-supplied identifier
        List<?> discoveries = manager.discover(userSuppliedString);

        // attempt to associate with the OpenID provider
        // and retrieve one service endpoint for authentication
        DiscoveryInformation discovered = manager.associate(discoveries);

        // store the discovery information in the user's session
        httpReq.getSession().setAttribute("openid-disc", discovered);

        // obtain a AuthRequest message to be sent to the OpenID provider
        AuthRequest authReq = manager.authenticate(discovered, returnToUrl);

        if (authReq.getOPEndpoint().indexOf("myopenid.com") > 0) {
            SRegRequest sregReq = SRegRequest.createFetchRequest();

            sregReq.addAttribute(AXSchemaType.FULLNAME.name().toLowerCase(), true);
            sregReq.addAttribute(AXSchemaType.EMAIL.name().toLowerCase(), true);
            sregReq.addAttribute(AXSchemaType.COUNTRY.name().toLowerCase(), true);
            sregReq.addAttribute(AXSchemaType.LANGUAGE.name().toLowerCase(), true);

            authReq.addExtension(sregReq);
        } else {

            FetchRequest fetch = FetchRequest.createFetchRequest();

            fetch.addAttribute(AXSchemaType.FIRSTNAME.getAlias(), AXSchemaType.FIRSTNAME.getNamespace(), true);
            fetch.addAttribute(AXSchemaType.LASTNAME.getAlias(), AXSchemaType.LASTNAME.getNamespace(), true);
            fetch.addAttribute(AXSchemaType.EMAIL.getAlias(), AXSchemaType.EMAIL.getNamespace(), true);
            fetch.addAttribute(AXSchemaType.COUNTRY.getAlias(), AXSchemaType.COUNTRY.getNamespace(), true);
            fetch.addAttribute(AXSchemaType.LANGUAGE.getAlias(), AXSchemaType.LANGUAGE.getNamespace(), true);

            // wants up to three email addresses
            fetch.setCount(AXSchemaType.EMAIL.getAlias(), 3);

            authReq.addExtension(fetch);
        }

        if (!discovered.isVersion2()) {
            // Option 1: GET HTTP-redirect to the OpenID Provider endpoint
            // The only method supported in OpenID 1.x
            // redirect-URL usually limited ~2048 bytes
            httpResp.sendRedirect(authReq.getDestinationUrl(true));
            return null;

        } else {
            // Option 2: HTML FORM Redirection (Allows payloads >2048 bytes)

            Object OPEndpoint = authReq.getDestinationUrl(false);

            ServletOutputStream out = httpResp.getOutputStream();

            httpResp.setContentType("text/html; charset=UTF-8");
            httpResp.addHeader("pragma", "no-cache");
            httpResp.addHeader("Cache-Control", "no-cache");

            out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
            out.println("<head>");
            out.println("    <title>OpenID HTML FORM Redirection</title>");
            out.println("</head>");
            out.println("<body onload=\"document.forms['openid-form-redirection'].submit();\">");
            out.println("    <form name=\"openid-form-redirection\" action=\"" + OPEndpoint
                    + "\" method=\"post\" accept-charset=\"utf-8\">");

            Map<String, String> parameterMap = authReq.getParameterMap();
            for (Entry<String, String> entry : parameterMap.entrySet()) {
                out.println("   <input type=\"hidden\" name=\"" + entry.getKey() + "\" value=\""
                        + entry.getValue() + "\"/>");
            }

            out.println("        <button type=\"submit\">Continue...</button>");
            out.println("    </form>");
            out.println("</body>");
            out.println("</html>");

            out.flush();
        }
    } catch (OpenIDException e) {
        // present error to the user
        LOG.debug("OpenIDException", e);

        ServletOutputStream out = httpResp.getOutputStream();
        httpResp.setContentType("text/html; charset=\"UTF-8\"");
        httpResp.addHeader("pragma", "no-cache");
        httpResp.addHeader("Cache-Control", "no-cache");

        httpResp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

        out.print("<html><head>");
        out.print("<title>OpenIDServlet Error</title>");
        out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></link></head>");
        out.print("<body><div id=\"container\"><h1>Error found</h1>");

        out.print("<h2>Message:");
        out.print(e.getMessage());
        out.print("</h2>");

        Throwable t = e.getCause();
        if (t != null) {
            // t can be null
            out.print(HTTPUtils.printStackTraceHTML(t));
        }

        out.print("</div></body></html>");
    }

    return null;
}

From source file:eu.earthobservatory.org.StrabonEndpoint.QueryBean.java

/**
  * Processes the request made by a client of the endpoint that uses it as a service. 
  * /*from w w w . j  ava2 s.  c  om*/
  * @param request
  * @param response
  * @throws IOException 
  */
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    ServletOutputStream out = response.getOutputStream();

    // get desired formats (we check only the Accept header)
    List<stSPARQLQueryResultFormat> formats = parseMultiValuedAcceptHeader(request.getHeader("accept"));

    // get the query and the limit
    String query = request.getParameter("query");
    String maxLimit = request.getParameter("maxLimit");

    // check for required parameters
    if (formats.size() == 0 || query == null) {
        logger.error("[StrabonEndpoint.QueryBean] {}", PARAM_ERROR);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.print(ResponseMessages.getXMLHeader());
        out.print(ResponseMessages.getXMLException(PARAM_ERROR));
        out.print(ResponseMessages.getXMLFooter());

    } else {
        // just use the first specified format
        stSPARQLQueryResultFormat format = formats.get(0);

        // decode the query
        query = URLDecoder.decode(request.getParameter("query"), "UTF-8");

        response.setContentType(format.getDefaultMIMEType());

        try {
            query = strabonWrapper.addLimit(query, maxLimit);
            strabonWrapper.query(query, format.getName(), out);
            response.setStatus(HttpServletResponse.SC_OK);

        } catch (Exception e) {
            logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.print(ResponseMessages.getXMLHeader());
            out.print(ResponseMessages.getXMLException(e.getMessage()));
            out.print(ResponseMessages.getXMLFooter());
        }
    }

    out.flush();
}

From source file:com.indeed.imhotep.web.QueryServlet.java

private SelectExecutionStats handleSelectStatement(final SelectRequestArgs args, final HttpServletResponse resp,
        SelectStatement parsedQuery, final ExecutionManager.QueryTracker queryTracker) throws IOException {
    // hashing is done before calling translate so only original JParsec parsing is considered
    final String queryForHashing = parsedQuery.toHashKeyString();

    final IQLQuery iqlQuery = IQLTranslator.translate(parsedQuery,
            args.interactive ? imhotepInteractiveClient : imhotepClient, args.imhotepUserName, metadata,
            imhotepLocalTempFileSizeLimit, imhotepDaemonTempFileSizeLimit);

    // TODO: handle requested format mismatch: e.g. cached CSV but asked for TSV shouldn't have to rerun the query
    final String queryHash = getQueryHash(queryForHashing, iqlQuery.getShardVersionList(), args.csv);
    final String cacheFileName = queryHash + (args.csv ? ".csv" : ".tsv");
    final boolean isCached = queryCache.isFileCached(cacheFileName);

    final QueryMetadata queryMetadata = new QueryMetadata();

    queryMetadata.addItem("IQL-Cached", isCached, true);
    final DateTime newestShard = getLatestShardVersion(iqlQuery.getShardVersionList());
    queryMetadata.addItem("IQL-Newest-Shard", newestShard, args.returnNewestShardVersion);

    final String shardList = shardListToString(iqlQuery.getShardVersionList());
    queryMetadata.addItem("IQL-Shard-List", shardList, args.returnShardlist);

    final List<Interval> timeIntervalsMissingShards = iqlQuery.getTimeIntervalsMissingShards();
    if (timeIntervalsMissingShards.size() > 0) {
        final String missingIntervals = intervalListToString(timeIntervalsMissingShards);
        queryMetadata.addItem("IQL-Missing-Shards", missingIntervals);
    }/*  ww  w  .  j av  a  2s  . com*/

    queryMetadata.setPendingHeaders(resp);

    if (args.headOnly) {
        return new SelectExecutionStats(true);
    }
    final ServletOutputStream outputStream = resp.getOutputStream();
    if (args.progress) {
        outputStream.print(": This is the start of the IQL Query Stream\n\n");
    }
    if (!args.asynchronous) {
        ResultServlet.setContentType(resp, args.avoidFileSave, args.csv, args.progress);
        if (!args.cacheReadDisabled && isCached) {
            log.trace("Returning cached data in " + cacheFileName);

            // read metadata from cache
            try {
                final InputStream metadataCacheStream = queryCache
                        .getInputStream(cacheFileName + METADATA_FILE_SUFFIX);
                final QueryMetadata cachedMetadata = QueryMetadata.fromStream(metadataCacheStream);
                queryMetadata.mergeIn(cachedMetadata);

                queryMetadata.setPendingHeaders(resp);
                resp.setHeader("Access-Control-Expose-Headers", StringUtils.join(resp.getHeaderNames(), ", "));
                if (args.progress) {
                    outputStream.println("event: header");
                    outputStream.print("data: ");
                    outputStream.print(queryMetadata.toJSON() + "\n\n");
                }
            } catch (Exception e) {
                log.info("Failed to load metadata cache from " + cacheFileName + METADATA_FILE_SUFFIX, e);
            }

            final InputStream cacheInputStream = queryCache.getInputStream(cacheFileName);
            final int rowsWritten = IQLQuery.copyStream(cacheInputStream, outputStream, iqlQuery.getRowLimit(),
                    args.progress);
            outputStream.close();
            return new SelectExecutionStats(isCached, rowsWritten, false, queryHash, 0);
        }
        final IQLQuery.WriteResults writeResults;
        final IQLQuery.ExecutionResult executionResult;
        try {
            // TODO: should we always get totals? opt out http param?
            executionResult = iqlQuery.execute(args.progress, outputStream, true);
            queryMetadata.addItem("IQL-Timings", executionResult.getTimings().replace('\n', '\t'),
                    args.progress);
            queryMetadata.addItem("IQL-Imhotep-Temp-Bytes-Written",
                    executionResult.getImhotepTempFilesBytesWritten(), args.progress);
            queryMetadata.addItem("IQL-Totals", Arrays.toString(executionResult.getTotals()), args.getTotals);

            queryMetadata.setPendingHeaders(resp);
            resp.setHeader("Access-Control-Expose-Headers", StringUtils.join(resp.getHeaderNames(), ", "));

            if (args.progress) {
                outputStream.println("event: header");
                outputStream.print("data: ");
                outputStream.print(queryMetadata.toJSON() + "\n\n");
            }
            final Iterator<GroupStats> groupStats = executionResult.getRows();
            final int groupingColumns = Math.max(1,
                    (parsedQuery.groupBy == null || parsedQuery.groupBy.groupings == null) ? 1
                            : parsedQuery.groupBy.groupings.size());
            final int selectColumns = Math.max(1,
                    (parsedQuery.select == null || parsedQuery.select.getProjections() == null) ? 1
                            : parsedQuery.select.getProjections().size());
            if (!args.asynchronous) {
                writeResults = iqlQuery.outputResults(groupStats, outputStream, args.csv, args.progress,
                        iqlQuery.getRowLimit(), groupingColumns, selectColumns, args.cacheWriteDisabled);
            } else {
                writeResults = new IQLQuery.WriteResults(0, null, groupStats, 0);
            }
            if (!args.cacheWriteDisabled && !isCached) {
                executorService.submit(new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        try {
                            try {
                                final OutputStream metadataCacheStream = queryCache
                                        .getOutputStream(cacheFileName + METADATA_FILE_SUFFIX);
                                queryMetadata.toStream(metadataCacheStream);
                                metadataCacheStream.close();
                            } catch (Exception e) {
                                log.warn("Failed to upload metadata cache: " + cacheFileName, e);
                            }
                            try {
                                uploadResultsToCache(writeResults, cacheFileName, args.csv);
                            } catch (Exception e) {
                                log.warn("Failed to upload cache: " + cacheFileName, e);
                            }
                        } finally {
                            Closeables2.closeQuietly(queryTracker, log);
                        }
                        return null;
                    }
                });
                queryTracker.markAsynchronousRelease(); // going to be closed asynchronously after cache is uploaded
            }
        } catch (ImhotepOutOfMemoryException e) {
            throw Throwables.propagate(e);
        } finally {
            Closeables2.closeQuietly(iqlQuery, log);
        }
        outputStream.close();
        return new SelectExecutionStats(isCached, writeResults, queryHash,
                executionResult.getImhotepTempFilesBytesWritten());
    } else {
        // TODO: rework the async case to use the same code path as the sync case above except running under an executor
        if (!isCached && args.cacheWriteDisabled) {
            throw new IllegalStateException("Query cache is disabled so only synchronous calls can be served");
        }

        resp.setContentType("application/json");

        if (!isCached) {
            executorService.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    try {
                        // TODO: get totals working with the cache
                        final IQLQuery.ExecutionResult executionResult = iqlQuery.execute(false, null, false);
                        final Iterator<GroupStats> groupStats = executionResult.getRows();

                        final OutputStream cacheStream = queryCache.getOutputStream(cacheFileName);
                        IQLQuery.writeRowsToStream(groupStats, cacheStream, args.csv, Integer.MAX_VALUE, false);
                        cacheStream.close(); // has to be closed
                        return null;
                    } finally {
                        Closeables2.closeQuietly(iqlQuery, log);
                        Closeables2.closeQuietly(queryTracker, log);
                    }
                }
            });
            queryTracker.markAsynchronousRelease(); // going to be closed asynchronously after cache is uploaded
        }

        final URL baseURL = new URL(args.requestURL);
        final URL resultsURL = new URL(baseURL, "results/" + cacheFileName);

        final ObjectMapper mapper = new ObjectMapper();
        final ObjectNode ret = mapper.createObjectNode();
        ret.put("filename", resultsURL.toString());
        mapper.writeValue(outputStream, ret);
        outputStream.close();
        // we don't know number of rows as it's handled asynchronously
        return new SelectExecutionStats(isCached, new IQLQuery.WriteResults(0, null, null, 0), queryHash, 0);
    }
}

From source file:org.eclipse.vtp.framework.engine.http.HttpConnector.java

/**
 * @param out//from w ww  . java2 s . c  om
 * @param prefix
 * @param name
 * @param var
 * @throws IOException
 */
private void examineVariable(ServletOutputStream out, String prefix, String name, IDataObject var)
        throws IOException {
    if (var instanceof IBooleanObject || var instanceof IDateObject || var instanceof IDecimalObject
            || var instanceof INumberObject || var instanceof IStringObject) {
        out.print("<li>");
        out.print(name);
        out.print(" = ");
        out.print(var.toString());
        out.print("&nbsp;&nbsp;<a href=\"");
        out.print(prefix);
        out.print(name);
        out.print("\">Lock & Edit</a></li>");
    } else if (!(var instanceof IArrayObject)) {
        String[] fieldNames = var.getType().getFieldNames();
        Arrays.sort(fieldNames);
        for (String fieldName : fieldNames)
            examineVariable(out, prefix, name + "." + fieldName, var.getField(fieldName));
    }
}