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.mycore.common.content.util.MCRServletContentHelper.java

/**
 * Consumes the content and writes it to the ServletOutputStream.
 *
 * @param content      The MCRContent resource to serve
 * @param out       The outputBufferSize stream to write to
 * @param ranges        Enumeration of the ranges in ascending non overlapping order the client wanted to retrieve
 * @param contentType   Content type of the resource
 *///w  ww. java 2  s.c om
private static void copy(final MCRContent content, final ServletOutputStream out, final Iterator<Range> ranges,
        final String contentType, final int inputBufferSize, final int outputBufferSize) throws IOException {

    IOException exception = null;

    long lastByte = 0;
    try (final InputStream resourceInputStream = content.getInputStream();
            final InputStream in = isInputStreamBuffered(resourceInputStream, content) ? resourceInputStream
                    : new BufferedInputStream(resourceInputStream, inputBufferSize)) {
        endCurrentTransaction();
        while (exception == null && ranges.hasNext()) {

            final Range currentRange = ranges.next();

            // Writing MIME header.
            out.println();
            out.println("--" + MIME_BOUNDARY);
            if (contentType != null) {
                out.println("Content-Type: " + contentType);
            }
            out.println("Content-Range: bytes " + currentRange.start + "-" + currentRange.end + "/"
                    + currentRange.length);
            out.println();

            // Printing content
            exception = copyRange(in, out, lastByte, currentRange.start, currentRange.end, outputBufferSize);
            lastByte = currentRange.end;
        }
    }
    out.println();
    out.print("--" + MIME_BOUNDARY + "--");

    // Rethrow any exception that has occurred
    if (exception != null) {
        throw exception;
    }

}

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

/**
  * Processes the request made from the HTML visual interface of Strabon Endpoint.
  * //ww w  .j  a  v  a2s .  c  o  m
  * @param request
  * @param response
  * @throws ServletException
  * @throws IOException
  */
private void processVIEWRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    RequestDispatcher dispatcher;

    // check whether Update submit button was fired
    String reqFuncionality = (request.getParameter("submit") == null) ? "" : request.getParameter("submit");

    if (reqFuncionality.equals("Update")) {
        // get the dispatcher for forwarding the rendering of the response
        dispatcher = request.getRequestDispatcher("/Update");
        dispatcher.forward(request, response);

    } else {
        String query = URLDecoder.decode(request.getParameter("query"), "UTF-8");
        String format = request.getParameter("format");
        String handle = request.getParameter("handle");
        String maxLimit = request.getParameter("maxLimit");

        // get stSPARQLQueryResultFormat from given format name
        TupleQueryResultFormat queryResultFormat = stSPARQLQueryResultFormat.valueOf(format);

        if (query == null || format == null || queryResultFormat == null) {
            dispatcher = request.getRequestDispatcher("query.jsp");
            request.setAttribute(ERROR, PARAM_ERROR);
            dispatcher.forward(request, response);

        } else {
            query = strabonWrapper.addLimit(query, maxLimit);
            if ("download".equals(handle)) { // download as attachment
                ServletOutputStream out = response.getOutputStream();

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

                try {
                    strabonWrapper.query(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 if (("map".equals(handle) || "map_local".equals(handle) || "timemap".equals(handle))
                    && (queryResultFormat == stSPARQLQueryResultFormat.KML
                            || queryResultFormat == stSPARQLQueryResultFormat.KMZ)) {
                // show map (only valid for KML/KMZ)

                // get dispatcher
                dispatcher = request.getRequestDispatcher("query.jsp");

                // re-assign handle
                request.setAttribute("handle", handle);

                SecureRandom random = new SecureRandom();
                String temp = new BigInteger(130, random).toString(32);

                // the temporary KML/KMZ file to create in the server
                String tempKMLFile = temp + "." + queryResultFormat.getDefaultFileExtension();
                ;

                try {
                    Date date = new Date();

                    // get the absolute path of the temporary directory
                    if (!request.getParameter("handle").toString().contains("timemap")) {
                        tempDirectory = appName + "-temp";

                        basePath = context.getRealPath("/") + "/../ROOT/" + tempDirectory + "/";
                        // fix the temporary directory for this web application

                        FileUtils.forceMkdir(new File(basePath));

                        @SuppressWarnings("unchecked")
                        Iterator<File> it = FileUtils.iterateFiles(new File(basePath), null, false);
                        while (it.hasNext()) {
                            File tbd = new File((it.next()).getAbsolutePath());
                            if (FileUtils.isFileOlder(new File(tbd.getAbsolutePath()), date.getTime())) {
                                FileUtils.forceDelete(new File(tbd.getAbsolutePath()));
                            }
                        }
                    } else { //timemap case
                        tempDirectory = "js/timemap";
                        basePath = context.getRealPath("/") + tempDirectory + "/";
                        // fix the temporary directory for this web application
                    }

                    // fix the temporary directory for this web application

                    // create temporary KML/KMZ file
                    File file = new File(basePath + tempKMLFile);
                    // if file does not exist, then create it
                    if (!file.exists()) {
                        file.createNewFile();
                    }

                    try {
                        // query and write the result in the temporary KML/KMZ file
                        FileOutputStream fos = new FileOutputStream(basePath + tempKMLFile);
                        strabonWrapper.query(query, format, fos);
                        fos.close();

                        if (request.getParameter("handle").toString().contains("timemap")) {
                            request.setAttribute("pathToKML", tempDirectory + "/" + tempKMLFile);
                        } else {
                            request.setAttribute("pathToKML",
                                    request.getScheme() + "://" + request.getServerName() + ":"
                                            + request.getServerPort() + "/" + tempDirectory + "/"
                                            + tempKMLFile);
                        }

                    } catch (MalformedQueryException e) {
                        logger.error("[StrabonEndpoint.QueryBean] Error during querying. {}", e.getMessage());
                        request.setAttribute(ERROR, e.getMessage());

                    } catch (Exception e) {
                        logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e);
                        request.setAttribute(ERROR, e.getMessage());
                    }

                    dispatcher.forward(request, response);

                } catch (IOException e) {
                    logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e);
                }

            } else { // "plain" is assumed as the default
                dispatcher = request.getRequestDispatcher("query.jsp");
                ByteArrayOutputStream bos = new ByteArrayOutputStream();

                try {
                    strabonWrapper.query(query, format, bos);
                    if (format.equals(Common.getHTMLFormat())) {
                        request.setAttribute(RESPONSE, bos.toString());
                    } else if (format.equals(Format.PIECHART.toString())
                            || format.equals(Format.AREACHART.toString())
                            || format.equals(Format.COLUMNCHART.toString())) {
                        request.setAttribute("format", "CHART");
                        request.setAttribute(RESPONSE, strabonWrapper.getgChartString());
                    }

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

                } catch (MalformedQueryException e) {
                    logger.error("[StrabonEndpoint.QueryBean] Error during querying. {}", e.getMessage());
                    request.setAttribute(ERROR, e.getMessage());

                } catch (Exception e) {
                    logger.error("[StrabonEndpoint.QueryBean] Error during querying.", e);
                    request.setAttribute(ERROR, e.getMessage());

                } finally {
                    dispatcher.forward(request, response);
                }
            }
        }
    }
}

From source file:org.tap4j.plugin.TapResult.java

public void doDownloadAttachment(StaplerRequest request, StaplerResponse response) {
    String f = request.getParameter("f");
    String key = request.getParameter("key");
    try {//from   ww w .java2 s .  c  o  m
        FilePath tapDir = new FilePath(new FilePath(new File(build.getRootDir(), Constants.TAP_DIR_NAME)), f);
        ServletOutputStream sos = response.getOutputStream();
        if (tapDir.exists()) {
            String tapStream = tapDir.readToString();
            TapConsumer consumer = TapConsumerFactory.makeTap13YamlConsumer();
            TestSet ts = consumer.load(tapStream);

            TapAttachment attachment = getAttachment(ts, key);
            if (attachment != null) {
                response.setContentType("application/force-download");
                //response.setContentLength((int)tapDir.length());
                response.setContentLength(attachment.getSize());
                response.setHeader("Content-Transfer-Encoding", "binary");
                response.setHeader("Content-Disposition",
                        "attachment; filename=\"" + attachment.getFileName() + "\"");//fileName);

                sos.write(attachment.getContent());
                sos.print('\n');
            } else {
                sos.println("Couldn't locate attachment in YAMLish: " + f);
            }
        } else {
            sos.println("Couldn't read FilePath.");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
    }
}

From source file:org.apache.cloud.rdf.web.sail.RdfController.java

private void performUpdate(final String query, final SailRepositoryConnection conn,
        final ServletOutputStream os, final String infer, final String vis)
        throws RepositoryException, MalformedQueryException, IOException {
    final Update update = conn.prepareUpdate(QueryLanguage.SPARQL, query);
    if (infer != null && infer.length() > 0) {
        update.setBinding(RdfCloudTripleStoreConfiguration.CONF_INFER,
                VALUE_FACTORY.createLiteral(Boolean.parseBoolean(infer)));
    }/*from  w  w w  .  ja  v a2s. c  om*/

    if (conn.getSailConnection() instanceof RdfCloudTripleStoreConnection && vis != null) {
        final RdfCloudTripleStoreConnection<?> sailConnection = (RdfCloudTripleStoreConnection<?>) conn
                .getSailConnection();
        sailConnection.getConf().set(RdfCloudTripleStoreConfiguration.CONF_CV, vis);
    }

    final long startTime = System.currentTimeMillis();

    try {
        update.execute();
    } catch (final UpdateExecutionException e) {
        final String message = "Update could not be successfully completed for query: ";
        os.print(String.format(message + "%s\n\n", StringEscapeUtils.escapeHtml4(query)));
        log.error(message + LogUtils.clean(query), e);
    }

    log.info(String.format("Update Time = %.3f\n", (System.currentTimeMillis() - startTime) / 1000.));
}

From source file:com.github.zhanhb.ckfinder.download.PathPartial.java

/**
 * Copy the contents of the specified input stream to the specified output
 * stream, and ensure that both streams are closed before returning (even in
 * the face of an exception)./*from w ww  .j a va  2  s  .  c om*/
 *
 * @param path The cache entry for the source resource
 * @param ostream The output stream to write to
 * @param ranges Enumeration of the ranges the client wanted to retrieve
 * @param contentType Content type of the resource
 * @param buffer buffer to copy the resource
 * @exception IOException if an input/output error occurs
 */
private void copy(Path path, ServletOutputStream ostream, Range[] ranges, String contentType, byte[] buffer)
        throws IOException {
    IOException exception = null;
    for (Range currentRange : ranges) {
        try (InputStream stream = Files.newInputStream(path)) {
            // Writing MIME header.
            ostream.println();
            ostream.println("--" + MIME_SEPARATION);
            if (contentType != null) {
                ostream.println(HttpHeaders.CONTENT_TYPE + ": " + contentType);
            }
            ostream.println(HttpHeaders.CONTENT_RANGE + ": " + currentRange);
            ostream.println();
            // Printing content
            copyRange(stream, ostream, currentRange, buffer);
        } catch (IOException ex) {
            exception = ex;
        }
    }
    ostream.println();
    ostream.print("--" + MIME_SEPARATION + "--");
    if (exception != null) {
        throw exception;
    }
}

From source file:org.sakaiproject.signup.tool.jsf.SignupUIBaseBean.java

/**
 * Send a warning message to user about failed ICS file generation
 * @param fileName/*from  w  ww  .jav a 2s. co  m*/
 * @param warningMsg
 */
protected void sendDownloadWarning(String fileName, String warningMsg) {

    FacesContext fc = FacesContext.getCurrentInstance();
    ServletOutputStream out = null;

    try {
        HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

        response.reset();
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "public, must-revalidate, post-check=0, pre-check=0, max-age=0");
        response.setContentType("text/plain");
        response.setHeader("Content-disposition", "attachment; filename=" + fileName);

        out = response.getOutputStream();
        warningMsg = warningMsg != null ? warningMsg : "Missing Scheduler tool on site";
        out.print(warningMsg);

        out.flush();
    } catch (IOException ex) {
        logger.warn("Error generating file for download:" + ex.getMessage());
    } finally {
        try {
            out.close();
        } catch (Exception e) {
            //do nothing;
        }
    }
    fc.responseComplete();

}

From source file:net.sourceforge.fenixedu.presentationTier.Action.teacher.onlineTests.TestsManagementAction.java

public ActionForward downloadTestMarks(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws FenixActionException {
    final String distributedTestCode = getStringFromRequest(request, "distributedTestCode");
    String result = null;//from  ww  w.  j  a  v a2  s.c o  m
    try {
        if (distributedTestCode != null) {
            result = ReadDistributedTestMarksToString.runReadDistributedTestMarksToString(
                    getExecutionCourse(request).getExternalId(), distributedTestCode);
        } else {
            result = ReadDistributedTestMarksToString.runReadDistributedTestMarksToString(
                    getExecutionCourse(request).getExternalId(),
                    request.getParameterValues("distributedTestCodes"));
        }
    } catch (FenixServiceException e) {
        throw new FenixActionException(e);
    }
    try {
        ServletOutputStream writer = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=pauta.xls");
        writer.print(result);
        writer.flush();
        response.flushBuffer();
    } catch (IOException e) {
        throw new FenixActionException();
    }
    return null;
}

From source file:org.apache.cocoon.servlet.CocoonServlet.java

/**
 * Process the specified <code>HttpServletRequest</code> producing output
 * on the specified <code>HttpServletResponse</code>.
 *//*from w  w w  . j av  a 2s. c  o m*/
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    /* HACK for reducing class loader problems.                                     */
    /* example: xalan extensions fail if someone adds xalan jars in tomcat3.2.1/lib */
    if (this.initClassLoader) {
        try {
            Thread.currentThread().setContextClassLoader(this.classLoader);
        } catch (Exception e) {
        }
    }

    // used for timing the processing
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    // add the cocoon header timestamp
    if (this.showCocoonVersion) {
        res.addHeader("X-Cocoon-Version", Constants.VERSION);
    }

    // get the request (wrapped if contains multipart-form data)
    HttpServletRequest request;
    try {
        if (this.enableUploads) {
            request = requestFactory.getServletRequest(req);
        } else {
            request = req;
        }
    } catch (Exception e) {
        if (getLogger().isErrorEnabled()) {
            getLogger().error("Problem with Cocoon servlet", e);
        }

        manageException(req, res, null, null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Problem in creating the Request", null, null, e);
        return;
    }

    // Get the cocoon engine instance

    if (reloadCocoon(request.getPathInfo(), request.getParameter(Constants.RELOAD_PARAM))) {
        disposeCocoon();
        initLogger();
        createCocoon();
    }

    // Check if cocoon was initialized
    if (this.cocoon == null) {
        manageException(request, res, null, null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Initialization Problem", null /* "Cocoon was not initialized" */,
                null /* "Cocoon was not initialized, cannot process request" */, this.exception);
        return;
    }

    // We got it... Process the request
    String uri = request.getServletPath();
    if (uri == null) {
        uri = "";
    }
    String pathInfo = request.getPathInfo();
    if (pathInfo != null) {
        // VG: WebLogic fix: Both uri and pathInfo starts with '/'
        // This problem exists only in WL6.1sp2, not in WL6.0sp2 or WL7.0b.
        if (uri.length() > 0 && uri.charAt(0) == '/') {
            uri = uri.substring(1);
        }
        uri += pathInfo;
    }

    if (uri.length() == 0) {
        /* empty relative URI
         -> HTTP-redirect from /cocoon to /cocoon/ to avoid
            StringIndexOutOfBoundsException when calling
            "".charAt(0)
           else process URI normally
        */
        String prefix = request.getRequestURI();
        if (prefix == null) {
            prefix = "";
        }

        res.sendRedirect(res.encodeRedirectURL(prefix + "/"));
        return;
    }

    String contentType = null;
    ContextMap ctxMap = null;

    Environment env;
    try {
        if (uri.charAt(0) == '/') {
            uri = uri.substring(1);
        }
        // Pass uri into environment without URLDecoding, as it is already decoded.
        env = getEnvironment(uri, request, res);
    } catch (Exception e) {
        if (getLogger().isErrorEnabled()) {
            getLogger().error("Problem with Cocoon servlet", e);
        }

        manageException(request, res, null, uri, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Problem in creating the Environment", null, null, e);
        return;
    }

    try {
        try {
            // Initialize a fresh log context containing the object model: it
            // will be used by the CocoonLogFormatter
            ctxMap = ContextMap.getCurrentContext();
            // Add thread name (default content for empty context)
            String threadName = Thread.currentThread().getName();
            ctxMap.set("threadName", threadName);
            // Add the object model
            ctxMap.set("objectModel", env.getObjectModel());
            // Add a unique request id (threadName + currentTime
            ctxMap.set("request-id", threadName + System.currentTimeMillis());

            if (this.cocoon.process(env)) {
                contentType = env.getContentType();
            } else {
                // We reach this when there is nothing in the processing change that matches
                // the request. For example, no matcher matches.
                getLogger().fatalError("The Cocoon engine failed to process the request.");
                manageException(request, res, env, uri, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Request Processing Failed", "Cocoon engine failed in process the request",
                        "The processing engine failed to process the request. This could be due to lack of matching or bugs in the pipeline engine.",
                        null);
                return;
            }
        } catch (ResourceNotFoundException e) {
            if (getLogger().isDebugEnabled()) {
                getLogger().warn(e.getMessage(), e);
            } else if (getLogger().isWarnEnabled()) {
                getLogger().warn(e.getMessage());
            }

            manageException(request, res, env, uri, HttpServletResponse.SC_NOT_FOUND, "Resource Not Found",
                    "Resource Not Found",
                    "The requested resource \"" + request.getRequestURI() + "\" could not be found", e);
            return;

        } catch (ConnectionResetException e) {
            if (getLogger().isDebugEnabled()) {
                getLogger().debug(e.toString(), e);
            } else if (getLogger().isWarnEnabled()) {
                getLogger().warn(e.toString());
            }

        } catch (IOException e) {
            // Tomcat5 wraps SocketException into ClientAbortException which extends IOException.
            if (getLogger().isDebugEnabled()) {
                getLogger().debug(e.toString(), e);
            } else if (getLogger().isWarnEnabled()) {
                getLogger().warn(e.toString());
            }

        } catch (Exception e) {
            if (getLogger().isErrorEnabled()) {
                getLogger().error("Internal Cocoon Problem", e);
            }

            manageException(request, res, env, uri, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Internal Server Error", null, null, e);
            return;
        }

        stopWatch.stop();
        String timeString = null;
        if (getLogger().isInfoEnabled()) {
            timeString = processTime(stopWatch.getTime());
            getLogger().info("'" + uri + "' " + timeString);
        }

        if (contentType != null && contentType.equals("text/html")) {
            String showTime = request.getParameter(Constants.SHOWTIME_PARAM);
            boolean show = this.showTime;
            if (showTime != null) {
                show = !showTime.equalsIgnoreCase("no");
            }
            if (show) {
                if (timeString == null) {
                    timeString = processTime(stopWatch.getTime());
                }
                boolean hide = this.hiddenShowTime;
                if (showTime != null) {
                    hide = showTime.equalsIgnoreCase("hide");
                }
                ServletOutputStream out = res.getOutputStream();
                out.print((hide) ? "<!-- " : "<p>");
                out.print(timeString);
                out.println((hide) ? " -->" : "</p>");
            }
        }
    } finally {
        if (ctxMap != null) {
            ctxMap.clear();
        }

        try {
            if (request instanceof MultipartHttpServletRequest) {
                if (getLogger().isDebugEnabled()) {
                    getLogger().debug("Deleting uploaded file(s).");
                }
                ((MultipartHttpServletRequest) request).cleanup();
            }
        } catch (IOException e) {
            getLogger().error("Cocoon got an Exception while trying to cleanup the uploaded files.", e);
        }

        /*
         * Servlet Specification 2.2, 6.5 Closure of Response Object:
         *
         *   A number of events can indicate that the servlet has provided all of the
         *   content to satisfy the request and that the response object can be
         *   considered to be closed. The events are:
         *     o The termination of the service method of the servlet.
         *     o When the amount of content specified in the setContentLength method
         *       of the response has been written to the response.
         *     o The sendError method is called.
         *     o The sendRedirect method is called.
         *   When a response is closed, all content in the response buffer, if any remains,
         *   must be immediately flushed to the client.
         *
         * Due to the above, out.flush() and out.close() are not necessary, and sometimes
         * (if sendError or sendRedirect were used) request may be already closed.
         */
    }
}

From source file:org.apache.cloud.rdf.web.sail.RdfController.java

@RequestMapping(value = "/queryrdf", method = { RequestMethod.GET, RequestMethod.POST })
public void queryRdf(@RequestParam("query") final String query,
        @RequestParam(value = RdfCloudTripleStoreConfiguration.CONF_QUERY_AUTH, required = false) String auth,
        @RequestParam(value = RdfCloudTripleStoreConfiguration.CONF_CV, required = false) final String vis,
        @RequestParam(value = RdfCloudTripleStoreConfiguration.CONF_INFER, required = false) final String infer,
        @RequestParam(value = "nullout", required = false) final String nullout,
        @RequestParam(value = RdfCloudTripleStoreConfiguration.CONF_RESULT_FORMAT, required = false) final String emit,
        @RequestParam(value = "padding", required = false) final String padding,
        @RequestParam(value = "callback", required = false) final String callback,
        final HttpServletRequest request, final HttpServletResponse response) {
    // WARNING: if you add to the above request variables,
    // Be sure to validate and encode since they come from the outside and could contain odd damaging character sequences.
    SailRepositoryConnection conn = null;
    final Thread queryThread = Thread.currentThread();
    auth = StringUtils.arrayToCommaDelimitedString(provider.getUserAuths(request));
    final Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override/* ww w. ja  va 2  s.c om*/
        public void run() {
            log.debug("interrupting");
            queryThread.interrupt();

        }
    }, QUERY_TIME_OUT_SECONDS * 1000);

    try {
        final ServletOutputStream os = response.getOutputStream();
        conn = repository.getConnection();

        final Boolean isBlankQuery = StringUtils.isEmpty(query);
        final ParsedOperation operation = QueryParserUtil.parseOperation(QueryLanguage.SPARQL, query, null);

        final Boolean requestedCallback = !StringUtils.isEmpty(callback);
        final Boolean requestedFormat = !StringUtils.isEmpty(emit);

        if (!isBlankQuery) {
            if (operation instanceof ParsedGraphQuery) {
                // Perform Graph Query
                final RDFHandler handler = new RDFXMLWriter(os);
                response.setContentType("text/xml");
                performGraphQuery(query, conn, auth, infer, nullout, handler);
            } else if (operation instanceof ParsedTupleQuery) {
                // Perform Tuple Query
                TupleQueryResultHandler handler;

                if (requestedFormat && emit.equalsIgnoreCase("json")) {
                    handler = new SPARQLResultsJSONWriter(os);
                    response.setContentType("application/json");
                } else {
                    handler = new SPARQLResultsXMLWriter(os);
                    response.setContentType("text/xml");
                }

                performQuery(query, conn, auth, infer, nullout, handler);
            } else if (operation instanceof ParsedUpdate) {
                // Perform Update Query
                performUpdate(query, conn, os, infer, vis);
            } else {
                throw new MalformedQueryException("Cannot process query. Query type not supported.");
            }
        }

        if (requestedCallback) {
            os.print(")");
        }
    } catch (final Exception e) {
        log.error("Error running query", e);
        throw new RuntimeException(e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (final RepositoryException e) {
                log.error("Error closing connection", e);
            }
        }
    }

    timer.cancel();
}

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

/**
 * Serves up a site that can be used to examine and modify active sessions.
 * //from   w  w  w. j  a  v  a2  s . com
 * @param req The HTTP request.
 * @param res The HTTP response.
 * @throws ServletException If the processing fails.
 * @throws IOException If the connection fails.
 */
public synchronized void examine(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    String cmd = req.getParameter("cmd");
    String process = req.getParameter("process");
    String session = req.getParameter("session");
    String variable = req.getParameter("variable");
    String action = req.getParameter("action");
    String value = req.getParameter("value");
    Deployment deployment = null;
    if (process != null)
        deployment = deploymentsByPath.get(process);
    DeploymentSession deploymentSession = null;
    if (session != null)
        deploymentSession = deployment.getActiveSession(session);
    IDataObject parent = null, object = null;
    String fieldName = null;
    if (variable != null) {
        for (String token : variable.split("\\.")) {
            if (object == null)
                object = deploymentSession.getVariableRegistry().getVariable(token);
            else {
                parent = object;
                object = parent.getField(token);
            }
            fieldName = token;
        }
    }
    if ("unlock".equals(cmd)) {
        if (action.startsWith("Save")) {
            IVariableRegistry variables = deploymentSession.getVariableRegistry();
            if (object == null) {
                object = variables.createVariable(parent.getField(fieldName).getType());
                parent.setField(fieldName, object);
            }
            if (object instanceof IBooleanObject)
                ((IBooleanObject) object).setValue(value);
            else if (object instanceof IDateObject)
                ((IDateObject) object).setValue(value);
            else if (object instanceof IDecimalObject)
                ((IDecimalObject) object).setValue(value);
            else if (object instanceof INumberObject)
                ((INumberObject) object).setValue(value);
            else if (object instanceof IStringObject)
                ((IStringObject) object).setValue(value);
        }
        deploymentSession.unlock();
        res.sendRedirect(
                res.encodeRedirectURL("examine?cmd=variables&process=" + process + "&session=" + session));
    } else {
        String base = res.encodeURL("examine?cmd=");
        res.setContentType("text/html");
        ServletOutputStream out = res.getOutputStream();
        out.println("<html><head><title>Runtime Examination</title></head><body>");
        if ("edit".equals(cmd)) {
            out.println("<p>Application: " + process + "</p>");
            out.println("<p>Session: " + deploymentSession.getSessionID() + " : "
                    + deploymentSession.getCurrentPosition() + "</p>");
            deploymentSession.lock();
            out.println("<form action=\"examine\" method=\"post\">");
            out.println("<input type=\"hidden\" name=\"cmd\" value=\"unlock\" />");
            out.println("<input type=\"hidden\" name=\"process\" value=\"" + process + "\" />");
            out.println("<input type=\"hidden\" name=\"session\" value=\"" + session + "\" />");
            out.println("<input type=\"hidden\" name=\"variable\" value=\"" + variable + "\" />");
            out.println("<p>" + variable + " = ");
            out.println("<input type=\"text\" name=\"value\" value=\"");
            if (object != null)
                out.println(object.toString());
            out.println("\" /></p>");
            out.println("<p><input type=\"submit\" name=\"action\" value=\"Save & Unlock\" />&nbsp;");
            out.println("<input type=\"submit\" name=\"action\" value=\"Cancel & Unlock\" /></p>");
            out.println("</form>");
        } else if ("variables".equals(cmd)) {
            out.println("<p>Application: " + process + "</p>");
            out.println("<p>Session: " + deploymentSession.getSessionID() + " : "
                    + deploymentSession.getCurrentPosition() + "</p>");
            out.println("<p>Select a variable to edit:</p><ul>");
            IVariableRegistry variables = deploymentSession.getVariableRegistry();
            String prefix = base + "edit&process=" + process + "&session=" + session + "&variable=";
            String[] variableNames = variables.getVariableNames();
            Arrays.sort(variableNames);
            for (String name : variableNames)
                examineVariable(out, prefix, name, variables.getVariable(name));
            out.println("</ul>");
        } else if ("sessions".equals(cmd)) {
            out.println("<p>Application: " + process + "</p>");
            out.println("<p>Select the session to examine:</p><ul>");
            for (DeploymentSession s : deployment.getActiveSessions()) {
                out.print("<li><a href=\"");
                out.print(base);
                out.print("variables&process=");
                out.print(process);
                out.print("&session=");
                out.print(s.getSessionID());
                out.print("\">");
                out.print(s.getSessionID());
                out.print(" : ");
                out.print(s.getCurrentPosition());
                out.println("</a></li>");
            }
            out.println("</ul>");
        } else {
            out.println("<p>Select the application to examine:</p><ul>");
            for (Object o : deploymentsByPath.keySet()) {
                out.print("<li><a href=\"");
                out.print(base);
                out.print("sessions&process=");
                out.print(o.toString());
                out.print("\">");
                out.print(o.toString());
                out.println("</a></li>");
            }
            out.println("</ul>");
        }
        out.println("</body></html>");
    }
}