Example usage for javax.servlet.http HttpServletRequest getContentType

List of usage examples for javax.servlet.http HttpServletRequest getContentType

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getContentType.

Prototype

public String getContentType();

Source Link

Document

Returns the MIME type of the body of the request, or null if the type is not known.

Usage

From source file:petascope.PetascopeInterface.java

@Override
public void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws ServletException {
    setServletURL(httpRequest);/*  w ww . j a v  a  2  s .c  om*/
    setCORSHeader(httpResponse);

    // NOTE: admin can change Service Prodiver, Identification then session *reloadPage* will exist and value is true
    HttpSession session = httpRequest.getSession();
    if (session.getAttribute("reloadMetadata") != null
            && Boolean.valueOf(session.getAttribute("reloadMetadata").toString()) == true) {
        try {
            meta = new DbMetadataSource(ConfigManager.METADATA_DRIVER, ConfigManager.METADATA_URL,
                    ConfigManager.METADATA_USER, ConfigManager.METADATA_PASS, false);

            // Then remove session as it does not need anymore
            session.removeAttribute("reloadMetadata");
        } catch (Exception e) {
            log.error("Stack trace: {}", e);
            throw new ServletException("Error initializing metadata database", e);
        }
    } else {
        // it is just normal query without updating metadata then session is null
        meta.clearCache();
    }

    String request = null;
    String requestBody = null;

    /* Process the request */
    try {
        try {
            //Check if this is a wms request and handled it accordingly
            if (wms13Adapter.handleGetRequests(httpRequest, httpResponse)) {
                //this is a wms13 request, and it was handled in the handleGetRequests
                //stop further execution
                return;
            }

            meta.ensureConnection();

            requestBody = IOUtils.toString(httpRequest.getReader());

            log.trace("POST Request length: {}", httpRequest.getContentLength());
            log.trace("POST request body  : \n------START REQUEST--------\n{}\n------END REQUEST------\n",
                    requestBody);
            log.trace("GET Query string   : {}", httpRequest.getQueryString());

            Map<String, String> params = buildParameterDictionary(requestBody);
            Map<String, String> paramMap = buildParameterMap(httpRequest);
            log.trace("Request parameters : {}", params);

            // GET interface processing
            String service = paramMap.get(KVPSymbols.KEY_SERVICE);

            // REST interface checks
            // get the uri contained after the context name i.e after petascope
            // in example.com/petascope/rest/wcs/... returns [rest,wcs]
            String pathInfo = httpRequest.getPathInfo();
            log.debug("Analyzing path info \"{}\" for REST interface checks.", pathInfo);
            // Java API: "This method returns null if there was no extra path information."
            String[] prsUrl = (null == pathInfo) ? new String[0] : pathInfo.substring(1).split("/");
            ArrayList<String> splitURI = new ArrayList<String>(Arrays.asList(prsUrl));
            if (service == null && splitURI.size() > 1
                    && (splitURI.get(0).equalsIgnoreCase(RESTProtocolExtension.REST_PROTOCOL_WCS_IDENTIFIER)
                            || splitURI.get(0).equals(RESTProtocolExtension.REST_PROTOCOL_WCPS_IDENTIFIER))) {
                service = splitURI.get(0).toUpperCase();
            }

            if (service != null) {
                // Removed WPS support as it doesn't work. Using 52n instead -- DM 2012-may-24
                //                    if (service.equals("WPS")) {
                //                        WpsServer wpsServer = new WpsServer(httpResponse, httpRequest);
                //                        request = wpsServer.request;
                //                    } else
                if (service.equals(petascope.wcs2.parsers.BaseRequest.SERVICE)) {
                    // extract version
                    String version = null;
                    String operation = paramMap.get(WCPS_REQUEST_GET_PARAMETER);

                    //This might be a REST operation, try to get the operation from the uri
                    if (operation == null && splitURI.size() > 2) {
                        operation = RESTProtocolExtension
                                .mapRestResourcesToCoverageOperation(httpRequest.getRequestURI());
                    }

                    if (operation.equals(RequestHandler.GET_CAPABILITIES)) {
                        version = paramMap.get(KVPSymbols.KEY_ACCEPTVERSIONS);
                        if (version == null && splitURI.size() > 1) {
                            version = splitURI.get(1);
                        }
                        log.trace(KVPSymbols.KEY_ACCEPTVERSIONS + ": " + version);
                        if (version == null) {
                            version = ConfigManager.WCS_DEFAULT_VERSION;
                        } else {
                            String[] versions = version.split(KVPSymbols.VERSIONS_SEP);
                            version = "";
                            for (String v : versions) {
                                if (ConfigManager.WCS_VERSIONS.contains(v) && !v.startsWith("1")) { // the WCS 1.1 server doesn't support GET-KVP
                                    version = v;
                                    break;
                                }
                            }
                        }
                    } else if (operation.equals(RequestHandler.DESCRIBE_COVERAGE)
                            || operation.equals(RequestHandler.PROCESS_COVERAGE)
                            || operation.equals(RequestHandler.GET_COVERAGE)
                            || operation.equals(RequestHandler.INSERT_COVERAGE)
                            || operation.equals(RequestHandler.DELETE_COVERAGE)
                            || operation.equals(RequestHandler.UPDATE_COVERAGE)) {
                        version = paramMap.get(KVPSymbols.KEY_VERSION);
                        if (version == null && splitURI.size() > 1) {
                            version = splitURI.get(1);
                        }
                    }

                    // handle request
                    request = StringUtil.urldecode(httpRequest.getQueryString(), httpRequest.getContentType());
                    handleWcsRequest(version, paramMap.get(WCPS_REQUEST_GET_PARAMETER), request, httpResponse,
                            httpRequest);
                    return;
                }
            }

            // To preserve compatibility with previous client versions, we allow
            // GET requests with parameter "query"
            String request2 = null;
            request2 = paramMap.get(WCPS_QUERY_GET_PARAMETER);
            if (request2 == null) {
                request2 = StringUtil.urldecode(params.get(WCPS_QUERY_GET_PARAMETER),
                        httpRequest.getContentType());
            }

            // splitURI list can be of size 0 if there is not path info in the HTTP request.
            if (request2 == null && splitURI.size() > 0
                    && splitURI.get(0).equalsIgnoreCase(RESTProtocolExtension.REST_PROTOCOL_WCPS_IDENTIFIER)) {
                if (splitURI.size() > 2
                        && splitURI.get(1).equals(RESTProtocolExtension.REST_PROTOCOL_WCPS_IDENTIFIER)) {
                    String queryDecoded = StringUtil.urldecode(splitURI.get(2), httpRequest.getContentType());
                    request2 = RasUtil.abstractWCPSToRasql(queryDecoded, wcps);
                }
            } else if (request2 != null) {
                log.debug("Received Abstract Syntax Request via GET: \n\t\t{}", request2);
                request2 = RasUtil.abstractWCPStoXML(request2);
            }
            request = StringUtil.urldecode(params.get(WCPS_REQUEST_GET_PARAMETER),
                    httpRequest.getContentType());
            if (request == null && request2 != null) {
                request = request2;
            }

            // Empty request ?
            if (request == null && (requestBody == null || requestBody.length() == 0)) {
                if (paramMap.size() > 0) {
                    throw new WCSException(ExceptionCode.NoApplicableCode,
                            "Couldn't understand the recieved request, is the service attribute missing?");
                } else {
                    printUsage(httpResponse, request);
                    return;
                }
            }

            //   No parameters, just XML in the request body:
            if (request == null && requestBody != null && requestBody.length() > 0) {
                request = StringUtil.urldecode(requestBody, httpRequest.getContentType());
            }

            log.debug("Petascope Request: \n------START REQUEST--------\n{}" + "\n------END REQUEST------\n",
                    request);

            String root = XMLUtil.getRootElementName(request);
            log.debug("Root Element name: {}", root);
            if (root == null) {
                return;
            }
            if (root.equals(XMLSymbols.LABEL_ENVELOPE)) {
                handleWcs2Request(request, httpResponse, httpRequest);
            } else if (root.endsWith(XMLSymbols.LABEL_PROCESSCOVERAGE_REQUEST)) {
                /* ProcessCoverages is defined in the WCPS extension to WcsServer */
                handleProcessCoverages(request, httpResponse);
            } else if (root.equals(RequestHandler.GET_CAPABILITIES)) {
                // extract the version that the client prefers
                Document doc = XMLUtil.buildDocument(null, request);
                String version = "";
                List<Element> acceptVersions = XMLUtil.collectAll(doc.getRootElement(),
                        XMLSymbols.LABEL_ACCEPT_VERSIONS);
                if (!acceptVersions.isEmpty()) {
                    List<Element> versions = XMLUtil.collectAll(ListUtil.head(acceptVersions),
                            XMLSymbols.LABEL_VERSION);
                    for (Element v : versions) {
                        String val = XMLUtil.getText(v);
                        if (val != null && ConfigManager.WCS_VERSIONS.contains(val)) {
                            version = val;
                            break;
                        }
                    }
                } else {
                    version = ConfigManager.WCS_DEFAULT_VERSION; // by default the latest supported by petascope
                }
                handleWcsRequest(version, root, request, httpResponse, httpRequest);
            } else if (root.equals(RequestHandler.DESCRIBE_COVERAGE) || root.equals(RequestHandler.GET_COVERAGE)
                    || root.equals(RequestHandler.PROCESS_COVERAGE)
                    || root.equals(RequestHandler.INSERT_COVERAGE)
                    || root.equals(RequestHandler.DELETE_COVERAGE)
                    || root.equals(RequestHandler.UPDATE_COVERAGE)) {
                Document doc = XMLUtil.buildDocument(null, request);
                String version = doc.getRootElement().getAttributeValue(KVPSymbols.KEY_VERSION);
                handleWcsRequest(version, root, request, httpResponse, httpRequest);
            } else {
                // error
                handleUnknownRequest(request, httpResponse);
            }
        } catch (WCSException e) {
            throw e;
        } catch (SecoreException e) {
            throw new WCSException(ExceptionCode.SecoreError, e);
        } catch (Exception e) {
            // Finally, cast all other exceptions into a WCSException
            log.error("Runtime error : {}", e.getMessage());
            throw new WCSException(ExceptionCode.RuntimeError,
                    "Runtime error while processing request: " + e.getMessage(), e);
        }
    } // And catch all WCSExceptions, to display to the client
    catch (WCSException e) {
        printError(httpResponse, request, e);
    }
}

From source file:com.recomdata.datasetexplorer.proxy.XmlHttpProxyServlet.java

public void doProcess(HttpServletRequest req, HttpServletResponse res, boolean isPost) {
    StringBuffer bodyContent = null;
    OutputStream out = null;/*  ww  w  .j  a  v  a2s  . c  o m*/
    PrintWriter writer = null;
    String serviceKey = null;

    try {
        BufferedReader in = req.getReader();
        String line = null;
        while ((line = in.readLine()) != null) {
            if (bodyContent == null)
                bodyContent = new StringBuffer();
            bodyContent.append(line);
        }
    } catch (Exception e) {
    }
    try {
        if (requireSession) {
            // check to see if there was a session created for this request
            // if not assume it was from another domain and blow up
            // Wrap this to prevent Portlet exeptions
            HttpSession session = req.getSession(false);
            if (session == null) {
                res.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
        }
        serviceKey = req.getParameter("id");
        // only to preven regressions - Remove before 1.0
        if (serviceKey == null)
            serviceKey = req.getParameter("key");
        // check if the services have been loaded or if they need to be reloaded
        if (services == null || configUpdated()) {
            getServices(res);
        }
        String urlString = null;
        String xslURLString = null;
        String userName = null;
        String password = null;
        String format = "json";
        String callback = req.getParameter("callback");
        String urlParams = req.getParameter("urlparams");
        String countString = req.getParameter("count");
        // encode the url to prevent spaces from being passed along
        if (urlParams != null) {
            urlParams = urlParams.replace(' ', '+');
        }

        try {
            if (services.has(serviceKey)) {
                JSONObject service = services.getJSONObject(serviceKey);
                // default to the service default if no url parameters are specified
                if (urlParams == null && service.has("defaultURLParams")) {
                    urlParams = service.getString("defaultURLParams");
                }
                String serviceURL = service.getString("url");
                // build the URL
                if (urlParams != null && serviceURL.indexOf("?") == -1) {
                    serviceURL += "?";
                } else if (urlParams != null) {
                    serviceURL += "&";
                }
                String apikey = "";
                if (service.has("username"))
                    userName = service.getString("username");
                if (service.has("password"))
                    password = service.getString("password");
                if (service.has("apikey"))
                    apikey = service.getString("apikey");
                urlString = serviceURL + apikey;
                if (urlParams != null)
                    urlString += "&" + urlParams;
                if (service.has("xslStyleSheet")) {
                    xslURLString = service.getString("xslStyleSheet");
                }
            }
            //code for passing the url directly through instead of using configuration file
            else if (req.getParameter("url") != null) {
                String serviceURL = req.getParameter("url");
                // build the URL
                if (urlParams != null && serviceURL.indexOf("?") == -1) {
                    serviceURL += "?";
                } else if (urlParams != null) {
                    serviceURL += "&";
                }
                urlString = serviceURL;
                if (urlParams != null)
                    urlString += urlParams;
            } else {
                writer = res.getWriter();
                if (serviceKey == null)
                    writer.write("XmlHttpProxyServlet Error: id parameter specifying serivce required.");
                else
                    writer.write("XmlHttpProxyServlet Error : service for id '" + serviceKey + "' not  found.");
                writer.flush();
                return;
            }
        } catch (Exception ex) {
            getLogger().severe("XmlHttpProxyServlet Error loading service: " + ex);
        }

        Map paramsMap = new HashMap();
        paramsMap.put("format", format);
        // do not allow for xdomain unless the context level setting is enabled.
        if (callback != null && allowXDomain) {
            paramsMap.put("callback", callback);
        }
        if (countString != null) {
            paramsMap.put("count", countString);
        }

        InputStream xslInputStream = null;

        if (urlString == null) {
            writer = res.getWriter();
            writer.write(
                    "XmlHttpProxyServlet parameters:  id[Required] urlparams[Optional] format[Optional] callback[Optional]");
            writer.flush();
            return;
        }
        // default to JSON
        res.setContentType(responseContentType);
        out = res.getOutputStream();
        // get the stream for the xsl stylesheet
        if (xslURLString != null) {
            // check the web root for the resource
            URL xslURL = null;
            xslURL = ctx.getResource(resourcesDir + "xsl/" + xslURLString);
            // if not in the web root check the classpath
            if (xslURL == null) {
                xslURL = XmlHttpProxyServlet.class.getResource(classpathResourcesDir + "xsl/" + xslURLString);
            }
            if (xslURL != null) {
                xslInputStream = xslURL.openStream();
            } else {
                String message = "Could not locate the XSL stylesheet provided for service id " + serviceKey
                        + ". Please check the XMLHttpProxy configuration.";
                getLogger().severe(message);
                try {
                    out.write(message.getBytes());
                    out.flush();
                    return;
                } catch (java.io.IOException iox) {
                }
            }
        }
        if (!isPost) {
            xhp.doGet(urlString, out, xslInputStream, paramsMap, userName, password);
        } else {
            if (bodyContent == null)
                getLogger().info(
                        "XmlHttpProxyServlet attempting to post to url " + urlString + " with no body content");
            xhp.doPost(urlString, out, xslInputStream, paramsMap, bodyContent.toString(), req.getContentType(),
                    userName, password);
        }
    } catch (Exception iox) {
        iox.printStackTrace();
        getLogger().severe("XmlHttpProxyServlet: caught " + iox);
        try {
            writer = res.getWriter();
            writer.write(iox.toString());
            writer.flush();
        } catch (java.io.IOException ix) {
            ix.printStackTrace();
        }
        return;
    } finally {
        try {
            if (out != null)
                out.close();
            if (writer != null)
                writer.close();
        } catch (java.io.IOException iox) {
        }
    }
}

From source file:com.jpeterson.littles3.StorageEngine.java

/**
 * Write/* w  w  w .j  a  v  a2  s .  co m*/
 * 
 * @param req
 *            the HttpServletRequest object that contains the request the
 *            client made of the servlet
 * @param resp
 *            the HttpServletResponse object that contains the response the
 *            servlet returns to the client
 * @throws IOException
 *             if an input or output error occurs while the servlet is
 *             handling the PUT request
 * @throws ServletException
 *             if the request for the PUT cannot be handled
 */
@SuppressWarnings("unchecked")
public void methodPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    OutputStream out = null;

    try {
        S3ObjectRequest or;

        try {
            or = S3ObjectRequest.create(req, resolvedHost(),
                    (Authenticator) getWebApplicationContext().getBean(BEAN_AUTHENTICATOR));
        } catch (InvalidAccessKeyIdException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidAccessKeyId");
            return;
        } catch (InvalidSecurityException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity");
            return;
        } catch (RequestTimeTooSkewedException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "RequestTimeTooSkewed");
            return;
        } catch (SignatureDoesNotMatchException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "SignatureDoesNotMatch");
            return;
        } catch (AuthenticatorException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity");
            return;
        }
        logger.debug("S3ObjectRequest: " + or);

        CanonicalUser requestor = or.getRequestor();

        if (or.getKey() != null) {
            String value;
            long contentLength;
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            DigestOutputStream digestOutputStream = null;
            S3Object oldS3Object = null;
            S3Object s3Object;
            StorageService storageService;
            Bucket bucket;
            String bucketName = or.getBucket();
            String key = or.getKey();

            if (!isValidKey(key)) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "KeyTooLong");
                return;
            }

            storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE);

            if (req.getParameter(PARAMETER_ACL) != null) {
                // write access control policy
                Acp acp;
                CanonicalUser owner;
                s3Object = storageService.load(bucketName, key);

                if (s3Object == null) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchKey");
                    return;
                }

                acp = s3Object.getAcp();
                try {
                    acp.canWrite(requestor);
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                // save owner
                owner = acp.getOwner();

                try {
                    acp = Acp.decode(req.getInputStream());
                } catch (IOException e) {
                    e.printStackTrace();
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "MalformedACLError");
                    return;
                }

                // maintain owner
                acp.setOwner(owner);

                s3Object.setAcp(acp);

                storageService.store(s3Object);
            } else {
                // make sure requestor can "WRITE" to the bucket
                try {
                    bucket = storageService.loadBucket(bucketName);
                    bucket.canWrite(requestor);
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                } catch (DataAccessException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
                    return;
                }

                try {
                    oldS3Object = storageService.load(bucket.getName(), key);
                } catch (DataRetrievalFailureException e) {
                    // ignore
                }

                // create a new S3Object for this request to store an object
                try {
                    s3Object = storageService.createS3Object(bucket, key, requestor);
                } catch (DataAccessException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
                    return;
                }

                out = s3Object.getOutputStream();
                digestOutputStream = new DigestOutputStream(out, messageDigest);

                // Used instead of req.getContentLength(); because Amazon
                // limit is 5 gig, which is bigger than an int
                value = req.getHeader("Content-Length");
                if (value == null) {
                    resp.sendError(HttpServletResponse.SC_LENGTH_REQUIRED, "MissingContentLength");
                    return;
                }
                contentLength = Long.valueOf(value).longValue();

                if (contentLength > 5368709120L) {
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "EntityTooLarge");
                    return;
                }

                long written = 0;
                int count;
                byte[] b = new byte[4096];
                ServletInputStream in = req.getInputStream();

                while (((count = in.read(b, 0, b.length)) > 0) && (written < contentLength)) {
                    digestOutputStream.write(b, 0, count);
                    written += count;
                }
                digestOutputStream.flush();

                if (written != contentLength) {
                    // transmission truncated
                    if (out != null) {
                        out.close();
                        out = null;
                    }
                    if (digestOutputStream != null) {
                        digestOutputStream.close();
                        digestOutputStream = null;
                    }
                    // clean up
                    storageService.remove(s3Object);
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "IncompleteBody");
                    return;
                }

                s3Object.setContentDisposition(req.getHeader("Content-Disposition"));
                s3Object.setContentLength(contentLength);
                s3Object.setContentMD5(req.getHeader("Content-MD5"));
                value = req.getContentType();
                logger.debug("Put - Content-Type: " + value);
                if (value == null) {
                    value = S3Object.DEFAULT_CONTENT_TYPE;
                }
                s3Object.setContentType(value);
                logger.debug("Put - get content-type: " + s3Object.getContentType());
                s3Object.setLastModified(System.currentTimeMillis());

                // metadata
                int prefixLength = HEADER_PREFIX_USER_META.length();
                String name;
                for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) {
                    String headerName = (String) headerNames.nextElement();
                    if (headerName.startsWith(HEADER_PREFIX_USER_META)) {
                        name = headerName.substring(prefixLength).toLowerCase();
                        for (Enumeration headers = req.getHeaders(headerName); headers.hasMoreElements();) {
                            value = (String) headers.nextElement();
                            s3Object.addMetadata(name, value);
                        }
                    }
                }

                // calculate ETag, hex encoding of MD5
                value = new String(Hex.encodeHex(digestOutputStream.getMessageDigest().digest()));
                resp.setHeader("ETag", value);
                s3Object.setETag(value);

                grantCannedAccessPolicies(req, s3Object.getAcp(), requestor);

                // NOTE: This could be reengineered to have a two-phase
                // commit.
                if (oldS3Object != null) {
                    storageService.remove(oldS3Object);
                }
                storageService.store(s3Object);
            }
        } else if (or.getBucket() != null) {
            StorageService storageService;
            Bucket bucket;

            storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE);

            if (req.getParameter(PARAMETER_ACL) != null) {
                // write access control policy
                Acp acp;
                CanonicalUser owner;

                logger.debug("User is providing new ACP for bucket " + or.getBucket());

                try {
                    bucket = storageService.loadBucket(or.getBucket());
                } catch (DataAccessException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
                    return;
                }

                acp = bucket.getAcp();
                try {
                    acp.canWrite(requestor);
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                // save owner
                owner = acp.getOwner();

                try {
                    acp = Acp.decode(req.getInputStream());
                } catch (IOException e) {
                    e.printStackTrace();
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "MalformedACLError");
                    return;
                }

                // maintain owner
                acp.setOwner(owner);

                bucket.setAcp(acp);

                logger.debug("Saving bucket ACP");
                logger.debug("ACP: " + Acp.encode(bucket.getAcp()));

                storageService.storeBucket(bucket);
            } else {
                // validate bucket
                String bucketName = or.getBucket();

                if (!isValidBucketName(bucketName)) {
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "InvalidBucketName");
                    return;
                }

                try {
                    bucket = storageService.createBucket(bucketName, requestor);
                } catch (BucketAlreadyExistsException e) {
                    resp.sendError(HttpServletResponse.SC_CONFLICT, "BucketAlreadyExists");
                    return;
                }

                grantCannedAccessPolicies(req, bucket.getAcp(), requestor);

                storageService.storeBucket(bucket);
            }
        }
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        logger.error("Unable to use MD5", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "InternalError");
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    } finally {
        if (out != null) {
            out.close();
            out = null;
        }
    }
}

From source file:org.apache.jsp.fileUploader_jsp.java

public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    PageContext pageContext = null;//  www  . j av  a 2 s. c o m
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
        response.setContentType("text/html; charset=utf-8");
        pageContext = _jspxFactory.getPageContext(this, request, response, "", true, 8192, true);
        _jspx_page_context = pageContext;
        application = pageContext.getServletContext();
        config = pageContext.getServletConfig();
        session = pageContext.getSession();
        out = pageContext.getOut();
        _jspx_out = out;

        out.write("<!--\n");
        out.write("Copyright 2012 The Infinit.e Open Source Project\n");
        out.write("\n");
        out.write("Licensed under the Apache License, Version 2.0 (the \"License\");\n");
        out.write("you may not use this file except in compliance with the License.\n");
        out.write("You may obtain a copy of the License at\n");
        out.write("\n");
        out.write("  http://www.apache.org/licenses/LICENSE-2.0\n");
        out.write("\n");
        out.write("Unless required by applicable law or agreed to in writing, software\n");
        out.write("distributed under the License is distributed on an \"AS IS\" BASIS,\n");
        out.write("WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n");
        out.write("See the License for the specific language governing permissions and\n");
        out.write("limitations under the License.\n");
        out.write("-->\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write(
                "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
        out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
        out.write("<head>\n");
        out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n");
        out.write("<title>Infinit.e File Upload Tool</title>\n");
        out.write("<style media=\"screen\" type=\"text/css\">\n");
        out.write("\n");
        out.write("body \n");
        out.write("{\n");
        out.write("\tfont: 14px Arial,sans-serif;\n");
        out.write("}\n");
        out.write("h2\n");
        out.write("{\n");
        out.write("\tfont-family: \"Times New Roman\";\n");
        out.write("\tfont-style: italic;\n");
        out.write("\tfont-variant: normal;\n");
        out.write("\tfont-weight: normal;\n");
        out.write("\tfont-size: 24px;\n");
        out.write("\tline-height: 29px;\n");
        out.write("\tfont-size-adjust: none;\n");
        out.write("\tfont-stretch: normal;\n");
        out.write("\t-x-system-font: none;\n");
        out.write("\tcolor: #d2331f;\n");
        out.write("\tmargin-bottom: 25px;\n");
        out.write("}\n");
        out.write(".show {\n");
        out.write("display: ;\n");
        out.write("visibility: visible;\n");
        out.write("}\n");
        out.write(".hide {\n");
        out.write("display: none;\n");
        out.write("visibility: hidden;\n");
        out.write("}\n");
        out.write("</style>\n");
        out.write("<script language=\"javascript\" src=\"AppConstants.js\"> </script>\n");
        out.write("</head>\n");
        out.write("\n");
        out.write("<body onload=\"populate()\">\n");

        if (API_ROOT == null) {
            ServletContext context = session.getServletContext();
            String realContextPath = context.getRealPath("/");
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("javascript");
            try { // EC2 Machines
                FileReader reader = new FileReader(realContextPath + "/AppConstants.js");
                engine.eval(reader);
                reader.close();
                engine.eval("output = getEndPointUrl();");
                API_ROOT = (String) engine.get("output");
                SHARE_ROOT = API_ROOT + "share/get/";
            } catch (Exception je) {
                try { ////////////Windows + Tomcat
                    FileReader reader = new FileReader(realContextPath + "\\..\\AppConstants.js");
                    engine.eval(reader);
                    reader.close();
                    engine.eval("output = getEndPointUrl();");
                    API_ROOT = (String) engine.get("output");
                    SHARE_ROOT = API_ROOT + "share/get/";
                } catch (Exception e) {
                    System.err.println(e.toString());
                }
            }
            if (null == API_ROOT) {
                // Default to localhost
                API_ROOT = "http://localhost:8080/api/";
                SHARE_ROOT = "$infinite/share/get/";
            }

            if (API_ROOT.contains("localhost"))
                localCookie = true;
            else
                localCookie = false;
        }
        Boolean isLoggedIn = isLoggedIn(request, response);
        if (isLoggedIn == null) {
            out.println("The Infinit.e API cannot be reached.");
            out.println(API_ROOT);
        }

        else if (isLoggedIn == true) {
            showAll = (request.getParameter("sudo") != null);
            DEBUG_MODE = (request.getParameter("debug") != null);
            communityList = generateCommunityList(request, response);

            if (request.getParameter("logout") != null) {
                logOut(request, response);
                out.println("<div style=\" text-align: center;\">");
                out.println("<meta http-equiv=\"refresh\" content=\"0\">");
                out.println("</div>");
            } else {

                out.println("<div style=\" text-align: center;\">");
                String contentType = request.getContentType();
                if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {

                    //      Create a new file upload handler
                    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
                    //      Parse the request
                    FileItemIterator iter = upload.getItemIterator(request);
                    byte[] fileBytes = null;
                    String fileDS = null;
                    byte[] iconBytes = null;
                    String iconDS = null;
                    Set<String> communities = new HashSet<String>();
                    boolean isFileSet = false;
                    while (iter.hasNext()) {
                        FileItemStream item = iter.next();
                        String name = item.getFieldName();
                        InputStream stream = item.openStream();
                        if (item.isFormField()) {
                            if (name.equalsIgnoreCase("communities")) {
                                communities.add(Streams.asString(stream));
                            } else
                                request.setAttribute(name, Streams.asString(stream));

                            //out.println("<b>" + name + ":</b>" + request.getAttribute(name).toString()+"</br>");
                        } else {
                            if (name.equalsIgnoreCase("file")) {
                                if (!item.getName().equals(""))
                                    isFileSet = true;
                                fileDS = item.getContentType();
                                fileBytes = IOUtils.toByteArray(stream);

                                // Check if this should be a java-archive (rather than just an octet stream)
                                if (fileDS.equals("application/octet-stream")) {
                                    ZipInputStream zis = new ZipInputStream(
                                            new ByteArrayInputStream(fileBytes));
                                    ZipEntry entry;
                                    while ((entry = zis.getNextEntry()) != null) {
                                        if (entry.getName().endsWith(".class")) {
                                            fileDS = "application/java-archive";
                                            break;
                                        }
                                    }
                                }
                                // Reset stream, and read
                            }
                        }
                    }

                    ////////////////////////////////////Delete Share ////////////////////////////////
                    if (request.getAttribute("deleteId") != null) {
                        String fileId = request.getAttribute("deleteId").toString();
                        if (fileId != null && fileId != "")
                            removeFromShare(fileId, request, response).toString();

                    }
                    ////////////////////////////////////Update Community Info////////////////////////////////
                    else if (null == fileBytes) {
                        String shareId = request.getAttribute("DBId").toString();
                        if (shareId != null && shareId != "")
                            addRemoveCommunities(shareId, communities, request, response);
                    } else {
                        //////////////////////////////////////////////////////////////////////////////////

                        Boolean newUpload = (request.getAttribute("DBId").toString().length() == 0);

                        ///////////////////////////////// SWF Manip  /////////////////////////////////
                        String shareId = request.getAttribute("DBId").toString();
                        String fileUrl = "";
                        String fileId = "";
                        String bin = request.getAttribute("binary").toString();
                        if (request.getAttribute("title") != null && request.getAttribute("description") != null
                                && fileBytes != null) {
                            if (!isFileSet) //if not a binary file or file was not changed
                            {
                                fileId = shareId;
                                if (shareId != null && shareId != "")
                                    addRemoveCommunities(shareId, communities, request, response);
                                out.println("File was not set, just updated communities.");
                            } else if (bin.equals("null")) //is a json file, make sure its okay and upload it
                            {
                                fileId = UpdateToShare(fileBytes, fileDS,
                                        request.getAttribute("title").toString(),
                                        request.getAttribute("description").toString(), shareId, communities,
                                        true, request.getAttribute("type").toString(), newUpload, request,
                                        response);
                            } else //is a binary, do normal
                            {
                                fileId = UpdateToShare(fileBytes, fileDS,
                                        request.getAttribute("title").toString(),
                                        request.getAttribute("description").toString(), shareId, communities,
                                        false, request.getAttribute("type").toString(), newUpload, request,
                                        response);
                            }

                            if (fileId.contains("Failed")) {
                                out.println(fileId);
                            } else {
                                fileUrl = SHARE_ROOT + fileId;
                                if (newUpload)
                                    out.println(
                                            "You have successfully added a file to the share, its location is: "
                                                    + fileUrl);
                                else
                                    out.println(
                                            "You have successfully updated a file on the share, its location is: "
                                                    + fileUrl);
                            }
                        } else {
                            fileUrl = null;
                            out.println("Error: Not enough information provided for file Upload");
                        }

                        ///////////////////////////////// End File Manip  /////////////////////////////////

                        out.println("</div>");
                    }
                } else {
                }

                out.write("\n");
                out.write("\t\n");
                out.write("\t<script>\n");
                out.write("\tfunction clearCommList()\n");
                out.write("\t\t{\n");
                out.write("\t\t\tmult_comms = document.getElementById('communities');\n");
                out.write("\t\t\tfor ( var i = 0, l = mult_comms.options.length, o; i < l; i++ )\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t  o = mult_comms.options[i];\n");
                out.write("\t\t\t  o.selected = false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t}\n");
                out.write("\t\tfunction highlightComms(commList)\n");
                out.write("\t\t{\n");
                out.write("\t\t\tmult_comms = document.getElementById('communities');\n");
                out.write("\t\t\tfor ( var i = 0, l = mult_comms.options.length, o; i < l; i++ )\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t  o = mult_comms.options[i];\n");
                out.write("\t\t\t  if(commList.indexOf(o.value) == -1)\n");
                out.write("\t\t\t\to.selected = false;\n");
                out.write("\t\t\t  else  \n");
                out.write("\t\t\t  \to.selected = true;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t}\n");
                out.write("\tfunction populate()\n");
                out.write("\t{\n");
                out.write("\t\tvar typerow = document.getElementById('typerow');\n");
                out.write("\t\tvar type = document.getElementById('type');\n");
                out.write("\t\tvar title = document.getElementById('title');\n");
                out.write("\t\tvar description = document.getElementById('description');\n");
                out.write("\t\tvar file = document.getElementById('file');\n");
                out.write("\t\tvar created = document.getElementById('created');\n");
                out.write("\t\tvar DBId = document.getElementById('DBId');\n");
                out.write("\t\tvar deleteId = document.getElementById('deleteId');\n");
                out.write("\t\tvar deleteButton = document.getElementById('deleteButton');\n");
                out.write("\t\tvar share_url = document.getElementById('share_url');\n");
                out.write("\t\tvar owner_text = document.getElementById('owner_text');\n");
                out.write("\t\tvar owner = document.getElementById('owner');\n");
                out.write("\t\tvar url_row = document.getElementById('url_row');\n");
                out.write("\t\tvar dropdown = document.getElementById(\"upload_info\");\n");
                out.write("\t\tvar list = dropdown.options[dropdown.selectedIndex].value;\n");
                out.write("\t\tvar binary = document.getElementById(\"binary\");\n");
                out.write("\t\t\n");
                out.write("\t\tif (list == \"new\")\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttitle.value = \"\";\n");
                out.write("\t\t\tdescription.value = \"\";\n");
                out.write("\t\t\ttype.value = \"binary\";\n");
                out.write("\t\t\tcreated.value = \"\";\n");
                out.write("\t\t\tDBId.value = \"\";\n");
                out.write("\t\t\tdeleteId.value = \"\";\n");
                out.write("\t\t\tshare_url.value = \"\";\n");
                out.write("\t\t\towner.value = \"\";\n");
                out.write("\t\t\ttyperow.className = \"hide\";\n");
                out.write("\t\t\turl_row.className = \"hide\";\n");
                out.write("\t\t\towner.className = \"hide\";\n");
                out.write("\t\t\towner_text.className = \"hide\";\n");
                out.write("\t\t\tdeleteButton.className = \"hide\";\n");
                out.write("\t\t\tclearCommList();\n");
                out.write("\t\t\tbinary.value = \"\";\n");
                out.write("\t\t\treturn;\n");
                out.write("\t\t}\n");
                out.write("\t\t\n");
                out.write("\t\tif ( list == \"newJSON\")\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttitle.value = \"\";\n");
                out.write("\t\t\tdescription.value = \"\";\n");
                out.write("\t\t\ttype.value = \"\";\n");
                out.write("\t\t\tcreated.value = \"\";\n");
                out.write("\t\t\tDBId.value = \"\";\n");
                out.write("\t\t\tdeleteId.value = \"\";\n");
                out.write("\t\t\tshare_url.value = \"\";\n");
                out.write("\t\t\towner.value = \"\";\n");
                out.write("\t\t\ttyperow.className = \"show\";\n");
                out.write("\t\t\turl_row.className = \"hide\";\n");
                out.write("\t\t\towner.className = \"hide\";\n");
                out.write("\t\t\towner_text.className = \"hide\";\n");
                out.write("\t\t\tdeleteButton.className = \"hide\";\n");
                out.write("\t\t\tclearCommList();\n");
                out.write("\t\t\tbinary.value = \"null\";\n");
                out.write("\t\t\treturn;\n");
                out.write("\t\t}\n");
                out.write("\t\t\n");
                out.write("\t\t//_id, created, title, description\n");
                out.write("\t\tsplit = list.split(\"$$$\");\n");
                out.write("\t\t\n");
                out.write("\t\tres_id = split[0];\n");
                out.write("\t\tres_created = split[1];\n");
                out.write("\t\tres_title = split[2];\n");
                out.write("\t\tres_description = split[3];\n");
                out.write("\t\tres_url = split[4];\n");
                out.write("\t\tcommunities = split[5];\n");
                out.write("\t\tres_owner = split[6];\n");
                out.write("\t\tres_binary = split[7];\t\t\n");
                out.write("\t\tres_type = split[8];\t\t\t\n");
                out.write("\t\t\n");
                out.write("\t\tif ( res_binary == \"null\" )\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttyperow.className = \"show\";\n");
                out.write("\t\t}\n");
                out.write("\t\telse\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttyperow.className = \"hide\";\n");
                out.write("\t\t}\n");
                out.write("\t\ttitle.value = res_title;\n");
                out.write("\t\tdescription.value = res_description;\n");
                out.write("\t\tcreated.value = res_created;\n");
                out.write("\t\tDBId.value = res_id;\n");
                out.write("\t\tdeleteId.value = res_id;\n");
                out.write("\t\tshare_url.value = res_url;\n");
                out.write("\t\towner.value = res_owner;\t\t\n");
                out.write("\t\tdeleteButton.className = \"show\";\n");
                out.write("\t\towner.className = \"show\";\n");
                out.write("\t\towner_text.className = \"show\";\n");
                out.write("\t\turl_row.className = \"show\";\n");
                out.write("\t\thighlightComms(communities);\t\t\n");
                out.write("\t\tbinary.value = res_binary;\n");
                out.write("\t\ttype.value = res_type;\n");
                out.write("\t}\n");
                out.write("\t\tfunction validate_fields()\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttitle = document.getElementById('title').value;\n");
                out.write("\t\t\tdescription = document.getElementById('description').value;\n");
                out.write("\t\t\tfile = document.getElementById('file').value;\n");
                out.write("\t\t\tbinary = document.getElementById(\"binary\").value;\n");
                out.write("\t\t\ttype = document.getElementById(\"type\").value;\n");
                out.write("\t\t\t//share_url = document.getElementById('share_url').value;\n");
                out.write("\t\t\t//file_url = document.getElementById('file_url').value;\n");
                out.write("\t\t\t//file_check = document.getElementById('file_check').checked;\n");
                out.write("\t\t\t\n");
                out.write("\t\t\tif (title == \"\")\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t\talert('Please provide a title.');\n");
                out.write("\t\t\t\treturn false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t\tif (description == \"\")\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t\talert('Please provide a description.');\n");
                out.write("\t\t\t\treturn false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t\tif ( binary == \"null\" && type == \"\")\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t\talert('Please provide a type.');\n");
                out.write("\t\t\t\treturn false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t\t\n");
                out.write("\t\t\t\n");
                out.write("\t\t}\n");
                out.write("\t\tfunction confirmDelete()\n");
                out.write("\t\t{\n");
                out.write(
                        "\t\t\tvar agree=confirm(\"Are you sure you wish to Delete this file from the File Share?\");\n");
                out.write("\t\t\tif (agree)\n");
                out.write("\t\t\t\treturn true ;\n");
                out.write("\t\t\telse\n");
                out.write("\t\t\t\treturn false ;\n");
                out.write("\t\t}\n");
                out.write("\t\tfunction showResults()\n");
                out.write("\t\t{\n");
                out.write("\t\t\tvar title = document.getElementById('DBId').value;\n");
                out.write("\t\t\tvar url = getEndPointUrl() + \"share/get/\" + title;\n");
                out.write("\t\t\twindow.open(url, '_blank');\n");
                out.write("\t\t\twindow.focus();\t\t\t\n");
                out.write("\t\t}\n");
                out.write("\t\t// -->\n");
                out.write("\t\t</script>\n");
                out.write("\t</script>\n");
                out.write(
                        "\t\t<div id=\"uploader_outter_div\" name=\"uploader_outter_div\" align=\"center\" style=\"width:100%\" >\n");
                out.write(
                        "\t    \t<div id=\"uploader_div\" name=\"uploader_div\" style=\"border-style:solid; border-color:#999999; border-radius: 10px; width:475px; margin:auto\">\n");
                out.write("\t        \t<h2>File Uploader</h2>\n");
                out.write("\t        \t<form id=\"search_form\" name=\"search_form\" method=\"get\">\n");
                out.write("\t        \t\t<div align=\"center\"\">\n");
                out.write("\t        \t\t<label for=\"ext\">Filter On</label>\n");
                out.write("\t\t\t\t\t  <select name=\"ext\" id=\"ext\" onchange=\"this.form.submit();\">\n");
                out.write("\t\t\t\t\t    ");

                out.print(populateMediaTypes(request, response));

                out.write("\n");
                out.write("\t\t\t\t\t  </select>\n");
                out.write("\t\t\t\t\t </div>\n");
                out.write("\t\t\t\t\t ");

                if (showAll)
                    out.print("<input type=\"hidden\" name=\"sudo\" id=\"sudo\" value=\"true\" />");

                out.write("\t        \t\t\n");
                out.write("\t        \t</form>\n");
                out.write(
                        "\t        \t<form id=\"delete_form\" name=\"delete_form\" method=\"post\" enctype=\"multipart/form-data\" onsubmit=\"javascript:return confirmDelete()\" >\n");
                out.write(
                        "\t        \t\t<select id=\"upload_info\" onchange=\"populate()\" name=\"upload_info\"><option value=\"new\">Upload New File</option><option value=\"newJSON\">Upload New JSON</option> ");

                out.print(populatePreviousUploads(request, response));

                out.write("</select>\n");
                out.write(
                        "\t        \t\t<input type=\"submit\" name=\"deleteButton\" id=\"deleteButton\" class=\"hidden\" value=\"Delete\" />\n");
                out.write("\t        \t\t<input type=\"hidden\" name=\"deleteId\" id=\"deleteId\" />\n");
                out.write("\t        \t\t<input type=\"hidden\" name=\"deleteFile\" id=\"deleteFile\" />\n");
                out.write("\t\t\t\t\t ");

                if (showAll)
                    out.print("<input type=\"hidden\" name=\"sudo\" id=\"sudo\" value=\"true\" />");

                out.write("\t        \t\t\n");
                out.write("\t        \t</form>\n");
                out.write(
                        "\t            <form id=\"upload_form\" name=\"upload_form\" method=\"post\" enctype=\"multipart/form-data\" onsubmit=\"javascript:return validate_fields();\" >\n");
                out.write(
                        "\t                <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"padding-left:10px; padding-right:10px\">\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td colspan=\"2\" align=\"center\"></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td>Title:</td>\n");
                out.write(
                        "\t                    <td><input type=\"text\" name=\"title\" id=\"title\" size=\"39\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td>Description:</td>\n");
                out.write(
                        "\t                    <td><textarea rows=\"4\" cols=\"30\" name=\"description\" id=\"description\" ></textarea></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr id=\"typerow\">\n");
                out.write("\t                    <td>Type:</td>\n");
                out.write(
                        "\t                    <td><input type=\"text\" name=\"type\" id=\"type\" size=\"39\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                  \t<td>Communities:</td>\n");
                out.write("\t                  \t<td>");

                out.print(communityList);

                out.write("</td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                  \t<td id=\"owner_text\">Owner:</td>\n");
                out.write("\t                  \t<td>\n");
                out.write(
                        "\t                    <input type=\"text\" name=\"owner\" id=\"owner\" readonly=\"readonly\" size=\"25\" />\n");
                out.write("\t                  \t</td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td>File:</td>\n");
                out.write("\t                    <td><input type=\"file\" name=\"file\" id=\"file\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr id=\"url_row\" class=\"hide\">\n");
                out.write("\t                  \t<td>Share URL:</td>\n");
                out.write(
                        "\t                  \t<td><input type=\"text\" name=\"share_url\" id=\"share_url\" readonly=\"readonly\" size=\"38\"/>\n");
                out.write(
                        "\t                  \t<input type=\"button\" onclick=\"showResults()\" value=\"View\"/>\n");
                out.write("\t                  \t</td>\n");
                out.write("\t                \t<td></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write(
                        "\t                    <td colspan=\"2\" style=\"text-align:right\"><input type=\"submit\" value=\"Submit\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                </table>\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"created\" id=\"created\" />\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"DBId\" id=\"DBId\" />\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"fileUrl\" id=\"fileUrl\" />\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"binary\" id=\"binary\" />\n");
                out.write("\t\t\t\t\t ");

                if (showAll)
                    out.print("<input type=\"hidden\" name=\"sudo\" id=\"sudo\" value=\"true\" />");

                out.write("\t        \t\t\n");
                out.write("\t\t\t\t</form>\n");
                out.write("\t        </div>\n");
                out.write("\t        <form id=\"logout_form\" name=\"logout_form\" method=\"post\">\n");
                out.write(
                        "\t        \t<input type=\"submit\" name=\"logout\" id = \"logout\" value=\"Log Out\" />\n");
                out.write("\t        </form>\n");
                out.write("\t    </div>\n");
                out.write("\t    </p>\n");
                out.write("\t\n");

            }
        } else if (isLoggedIn == false) {
            //localCookie =(request.getParameter("local") != null);
            //System.out.println("LocalCookie = " + localCookie.toString());
            String errorMsg = "";
            if (request.getParameter("logintext") != null || request.getParameter("passwordtext") != null) {
                if (logMeIn(request.getParameter("logintext"), request.getParameter("passwordtext"), request,
                        response)) {
                    showAll = (request.getParameter("sudo") != null);
                    out.println("<meta http-equiv=\"refresh\" content=\"0\">");
                    out.println("Login Success");
                } else {
                    errorMsg = "Log in Failed, Please Try again";
                }

            }

            out.write("\n");
            out.write("\n");
            out.write("<script>\n");
            out.write("\tfunction validate_fields()\n");
            out.write("\t{\n");
            out.write("\t\tuname = document.getElementById('logintext').value;\n");
            out.write("\t\tpword = document.getElementById('passwordtext').value;\n");
            out.write("\t\t\n");
            out.write("\t\tif (uname == \"\")\n");
            out.write("\t\t{\n");
            out.write("\t\t\talert('Please provide your username.');\n");
            out.write("\t\t\treturn false;\n");
            out.write("\t\t}\n");
            out.write("\t\tif (pword == \"\")\n");
            out.write("\t\t{\n");
            out.write("\t\t\talert('Please provide your password.');\n");
            out.write("\t\t\treturn false;\n");
            out.write("\t\t}\n");
            out.write("\t}\n");
            out.write("\n");
            out.write("\n");
            out.write("</script>\n");
            out.write(
                    "\t<div id=\"login_outter_div\" name=\"login_outter_div\" align=\"center\" style=\"width:100%\" >\n");
            out.write(
                    "    \t<div id=\"login_div\" name=\"login_div\" style=\"border-style:solid; border-color:#999999; border-radius: 10px; width:450px; margin:auto\">\n");
            out.write("        \t<h2>Login</h2>\n");
            out.write(
                    "            <form id=\"login_form\" name=\"login_form\" method=\"post\" onsubmit=\"javascript:return validate_fields();\" >\n");
            out.write(
                    "                <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"padding-left:10px\">\n");
            out.write("                  <tr>\n");
            out.write("                    <td>User Name</td>\n");
            out.write("                    <td>&nbsp;</td>\n");
            out.write("                    <td>Password</td>\n");
            out.write("                  </tr>\n");
            out.write("                  <tr>\n");
            out.write(
                    "                    <td><input type=\"text\" name=\"logintext\" id=\"logintext\" width=\"190px\" /></td>\n");
            out.write("                    <td>&nbsp;</td>\n");
            out.write(
                    "                    <td><input type=\"password\" name=\"passwordtext\" id=\"passwordtext\" width=\"190px\" /></td>\n");
            out.write("                  </tr>\n");
            out.write("                  <tr>\n");
            out.write(
                    "                    <td colspan=\"3\" align=\"right\"><input name=\"Login\" type=\"submit\" value=\"Login\" /></td>\n");
            out.write("                  </tr>\n");
            out.write("                </table>\n");
            out.write("\t\t\t</form>\n");
            out.write("        </div>\n");
            out.write("    </div>\n");
            out.write("\t<div style=\"color: red; text-align: center;\"> ");
            out.print(errorMsg);
            out.write(" </div>\n");

        }

        out.write("\n");
        out.write("    \n");
        out.write("    \n");
        out.write("</body>\n");
        out.write("</html>");
    } catch (Throwable t) {
        if (!(t instanceof SkipPageException)) {
            out = _jspx_out;
            if (out != null && out.getBufferSize() != 0)
                try {
                    out.clearBuffer();
                } catch (java.io.IOException e) {
                }
            if (_jspx_page_context != null)
                _jspx_page_context.handlePageException(t);
        }
    } finally {
        _jspxFactory.releasePageContext(_jspx_page_context);
    }
}

From source file:org.signserver.web.GenericProcessServlet.java

/**
 * Handles http post./*  w  w  w  . j a v a 2  s.c  o m*/
 *
 * @param req servlet request
 * @param res servlet response
 *
 * @throws IOException input/output error
 * @throws ServletException error
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    LOG.debug(">doPost()");

    int workerId = 1;
    byte[] data = null;
    String fileName = null;
    String pdfPassword = null;
    boolean workerRequest = false;

    if (LOG.isDebugEnabled()) {
        LOG.debug("Received a request with length: " + req.getContentLength());
    }

    final String workerNameOverride = (String) req.getAttribute(WORKERNAME_PROPERTY_OVERRIDE);

    if (workerNameOverride != null) {
        workerId = getWorkerSession().getWorkerId(workerNameOverride);
        workerRequest = true;
    }

    final long maxUploadSize = getMaxUploadSize();

    ProcessType processType = ProcessType.signDocument;
    final MetaDataHolder metadataHolder = new MetaDataHolder();

    if (ServletFileUpload.isMultipartContent(req)) {
        final DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(Integer.MAX_VALUE); // Don't write to disk

        final ServletFileUpload upload = new ServletFileUpload(factory);

        // Limit the maximum size of input
        upload.setSizeMax(maxUploadSize);

        try {
            final List items = upload.parseRequest(req);
            final Iterator iter = items.iterator();
            FileItem fileItem = null;
            String encoding = null;
            while (iter.hasNext()) {
                final Object o = iter.next();
                if (o instanceof FileItem) {
                    final FileItem item = (FileItem) o;

                    if (item.isFormField()) {
                        if (!workerRequest) {
                            if (WORKERNAME_PROPERTY_NAME.equals(item.getFieldName())) {
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("Found a signerName in the request: " + item.getString());
                                }
                                workerId = getWorkerSession().getWorkerId(item.getString());
                            } else if (WORKERID_PROPERTY_NAME.equals(item.getFieldName())) {
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("Found a signerId in the request: " + item.getString());
                                }
                                try {
                                    workerId = Integer.parseInt(item.getString());
                                } catch (NumberFormatException ignored) {
                                }
                            }
                        }

                        final String itemFieldName = item.getFieldName();

                        if (PDFPASSWORD_PROPERTY_NAME.equals(itemFieldName)) {
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Found a pdfPassword in the request.");
                            }
                            pdfPassword = item.getString("ISO-8859-1");
                        } else if (PROCESS_TYPE_PROPERTY_NAME.equals(itemFieldName)) {
                            final String processTypeAttribute = item.getString("ISO-8859-1");

                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Found process type in the request: " + processTypeAttribute);
                            }

                            if (processTypeAttribute != null) {
                                try {
                                    processType = ProcessType.valueOf(processTypeAttribute);
                                } catch (IllegalArgumentException e) {
                                    sendBadRequest(res, "Illegal process type: " + processTypeAttribute);
                                    return;
                                }
                            } else {
                                processType = ProcessType.signDocument;
                            }
                        } else if (ENCODING_PROPERTY_NAME.equals(itemFieldName)) {
                            encoding = item.getString("ISO-8859-1");
                        } else if (isFieldMatchingMetaData(itemFieldName)) {
                            try {
                                metadataHolder.handleMetaDataProperty(itemFieldName,
                                        item.getString("ISO-8859-1"));
                            } catch (IOException e) {
                                sendBadRequest(res, "Malformed properties given using REQUEST_METADATA.");
                                return;
                            }
                        }
                    } else {
                        // We only care for one upload at a time right now
                        if (fileItem == null) {
                            fileItem = item;
                        }
                    }
                }
            }

            if (fileItem == null) {
                sendBadRequest(res, "Missing file content in upload");
                return;
            } else {
                fileName = fileItem.getName();
                data = fileItem.get(); // Note: Reads entiry file to memory

                if (encoding != null && !encoding.isEmpty()) {
                    if (ENCODING_BASE64.equalsIgnoreCase(encoding)) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Decoding base64 data");
                        }
                        data = Base64.decode(data);
                    } else {
                        sendBadRequest(res, "Unknown encoding for the 'data' field: " + encoding);
                        return;
                    }
                }
            }
        } catch (FileUploadBase.SizeLimitExceededException ex) {
            LOG.error(HTTP_MAX_UPLOAD_SIZE + " exceeded: " + ex.getLocalizedMessage());
            res.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                    "Maximum content length is " + maxUploadSize + " bytes");
            return;
        } catch (FileUploadException ex) {
            throw new ServletException("Upload failed", ex);
        }
    } else {
        if (!workerRequest) {
            String name = req.getParameter(WORKERNAME_PROPERTY_NAME);
            if (name != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found a signerName in the request: " + name);
                }
                workerId = getWorkerSession().getWorkerId(name);
            }
            String id = req.getParameter(WORKERID_PROPERTY_NAME);
            if (id != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found a signerId in the request: " + id);
                }
                workerId = Integer.parseInt(id);
            }
        }

        final Enumeration<String> params = req.getParameterNames();

        while (params.hasMoreElements()) {
            final String property = params.nextElement();
            if (PDFPASSWORD_PROPERTY_NAME.equals(property)) {
                pdfPassword = (String) req.getParameter(PDFPASSWORD_PROPERTY_NAME);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found a pdfPassword in the request.");
                }
            } else if (isFieldMatchingMetaData(property)) {
                try {
                    metadataHolder.handleMetaDataProperty(property, req.getParameter(property));
                } catch (IOException e) {
                    sendBadRequest(res, "Malformed properties given using REQUEST_METADATA.");
                    return;
                }
            }
        }

        final String processTypeAttribute = (String) req.getParameter(PROCESS_TYPE_PROPERTY_NAME);

        if (processTypeAttribute != null) {
            try {
                processType = ProcessType.valueOf(processTypeAttribute);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found process type in the request: " + processType.name());
                }
            } catch (IllegalArgumentException e) {
                sendBadRequest(res, "Illegal process type: " + processTypeAttribute);
                return;
            }
        } else {
            processType = ProcessType.signDocument;
        }

        if (METHOD_GET.equalsIgnoreCase(req.getMethod())
                || (req.getContentType() != null && req.getContentType().contains(FORM_URL_ENCODED))) {
            LOG.debug("Request is FORM_URL_ENCODED");

            if (req.getParameter(DATA_PROPERTY_NAME) == null) {
                sendBadRequest(res, "Missing field 'data' in request");
                return;
            }
            data = req.getParameter(DATA_PROPERTY_NAME).getBytes();

            String encoding = req.getParameter(ENCODING_PROPERTY_NAME);
            if (encoding != null && !encoding.isEmpty()) {
                if (ENCODING_BASE64.equalsIgnoreCase(encoding)) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Decoding base64 data");
                    }
                    data = Base64.decode(data);
                } else {
                    sendBadRequest(res, "Unknown encoding for the 'data' field: " + encoding);
                    return;
                }
            }
        } else {
            // Pass-through the content to be handled by worker if
            // unknown content-type
            if (LOG.isDebugEnabled()) {
                LOG.debug("Request Content-type: " + req.getContentType());
            }

            // Get an input stream and read the bytes from the stream
            InputStream in = req.getInputStream();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            int len;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf)) > 0) {
                os.write(buf, 0, len);
            }
            in.close();
            os.close();
            data = os.toByteArray();
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Request of type: " + processType.name());
    }

    // Limit the maximum size of input
    if (data.length > maxUploadSize) {
        LOG.error("Content length exceeds " + maxUploadSize + ", not processed: " + req.getContentLength());
        res.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                "Maximum content length is " + maxUploadSize + " bytes");
    } else {
        processRequest(req, res, workerId, data, fileName, pdfPassword, processType, metadataHolder);
    }

    LOG.debug("<doPost()");
}

From source file:com.rapid.server.Rapid.java

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

    // fake a delay for testing slow servers
    //try { Thread.sleep(3000); } catch (InterruptedException e) {}

    // this byte buffer is used for reading the post data 
    byte[] byteBuffer = new byte[1024];

    // read bytes from request body into our own byte array (this means we can deal with images) 
    InputStream input = request.getInputStream();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    for (int length = 0; (length = input.read(byteBuffer)) > -1;)
        outputStream.write(byteBuffer, 0, length);
    byte[] bodyBytes = outputStream.toByteArray();

    // get a logger
    Logger logger = getLogger();/*  w w  w .j a va  2  s .co m*/

    // log
    logger.debug("Rapid POST request : " + request.getQueryString() + " bytes=" + bodyBytes.length);

    // create a Rapid request            
    RapidRequest rapidRequest = new RapidRequest(this, request);

    try {

        // this is the only variant where an application isn't specified and secured first
        if ("getApps".equals(rapidRequest.getActionName())) {

            // create an empty array which we will populate
            JSONArray jsonApps = new JSONArray();

            // get all available applications
            List<Application> apps = getApplications().sort();

            // if there were some
            if (apps != null) {

                // fail silently if there was an issue
                try {

                    // assume we weren't passed any json            
                    JSONObject jsonData = getJSONObject(bodyBytes);

                    // assume the request wasn't for testing on Rapid Mobile
                    boolean forTesting = false;

                    // if we got some data, look for a test = true entry - this is sent from Rapid Mobile
                    if (jsonData != null)
                        forTesting = jsonData.optBoolean("test");

                    // loop the apps
                    for (Application app : apps) {

                        // if Rapid app must not be for testing / from Rapid Mobile
                        if (!"rapid".equals(app.getId()) || !forTesting) {

                            // get the relevant security adapter
                            SecurityAdapter security = app.getSecurityAdapter();

                            // make a rapidRequest for this application
                            RapidRequest getAppsRequest = new RapidRequest(this, request, app);

                            // check the user password
                            if (security.checkUserPassword(getAppsRequest, rapidRequest.getUserName(),
                                    rapidRequest.getUserPassword())) {

                                // assume can add
                                boolean canAdd = true;

                                if ("rapid".equals(app.getId())) {
                                    // must have RapidAdmin or RapidSuper to see Rapid app
                                    canAdd = security.checkUserRole(rapidRequest, Rapid.ADMIN_ROLE)
                                            || security.checkUserRole(rapidRequest, Rapid.SUPER_ROLE);
                                }

                                if (canAdd) {
                                    // create a json object for the details of this application
                                    JSONObject jsonApp = new JSONObject();
                                    // add details
                                    jsonApp.put("id", app.getId());
                                    jsonApp.put("version", app.getVersion());
                                    jsonApp.put("title", app.getTitle());
                                    jsonApp.put("noRetainPassword", app.getNoRetainPassword());
                                    // add app to our main array
                                    jsonApps.put(jsonApp);

                                    // check if we are testing
                                    if (forTesting) {

                                        // if the user has Rapid Design for this application, (or Rpaid Super if this is the rapid app)
                                        if (security.checkUserRole(rapidRequest, Rapid.DESIGN_ROLE)
                                                && (!app.getId().equals("rapid") || security
                                                        .checkUserRole(rapidRequest, Rapid.SUPER_ROLE))) {

                                            // loop the versions
                                            for (Application version : getApplications()
                                                    .getVersions(app.getId()).sort()) {

                                                // create a json object for the details of this version
                                                jsonApp = new JSONObject();
                                                // add details
                                                jsonApp.put("id", version.getId());
                                                jsonApp.put("version", version.getVersion());
                                                jsonApp.put("status", version.getStatus());
                                                jsonApp.put("title", version.getTitle());
                                                jsonApp.put("noRetainPassword", version.getNoRetainPassword());
                                                jsonApp.put("test", true);
                                                // add app to our main array
                                                jsonApps.put(jsonApp);
                                            }

                                        } // got design role

                                    } // forTesting check

                                } // rapid app extra check

                            } // user check

                        } // rapid app and not for testing check

                    } // apps loop

                } catch (Exception ex) {
                    // only log
                    logger.error("Error geting apps : ", ex);
                }

            } // apps check

            // set response to json
            response.setContentType("application/json");

            // create a writer
            PrintWriter out = response.getWriter();

            // print the results
            out.print(jsonApps.toString());

            // close the writer
            out.close();

            // log response
            logger.debug("Rapid POST response : " + jsonApps.toString());

        } else {

            // get the application
            Application app = rapidRequest.getApplication();

            // check we got one
            if (app == null) {

                // send forbidden response         
                sendMessage(response, 400, "Application not found",
                        "The application you requested can't be found");

                // log
                logger.debug("Rapid POST response (403) : Application not found");

            } else {

                // get the security
                SecurityAdapter security = app.getSecurityAdapter();

                // check the user password
                if (security.checkUserPassword(rapidRequest, rapidRequest.getUserName(),
                        rapidRequest.getUserPassword())) {

                    // if an application action was found in the request                  
                    if (rapidRequest.getAction() != null) {

                        // assume we weren't passed any json            
                        JSONObject jsonData = getJSONObject(bodyBytes);

                        // if we got some data
                        if (jsonData != null) {

                            // fetch the action result
                            JSONObject jsonResult = rapidRequest.getAction().doAction(rapidRequest, jsonData);

                            // set response to json
                            response.setContentType("application/json");

                            // create a writer
                            PrintWriter out = response.getWriter();

                            // print the results
                            out.print(jsonResult.toString());

                            // close the writer
                            out.close();

                            // log response
                            logger.debug("Rapid POST response : " + jsonResult);

                        } // jsonData

                    } else if ("application/x-www-form-urlencoded".equals(request.getContentType())) {

                        // log
                        logger.debug("Form data received");

                        // get the form adapter
                        FormAdapter formAdapter = app.getFormAdapter();

                        // form adapter check
                        if (formAdapter == null) {

                            // send message
                            sendMessage(response, 500, "Not a form", "This Rapid app is not a form");

                            // log
                            logger.debug("Rapid GET response (500) : Not a form");

                        } else {

                            // get the form details to test all is ok
                            UserFormDetails formDetails = formAdapter.getUserFormDetails(rapidRequest);

                            // check we got one
                            if (formDetails == null) {

                                logger.debug("Returning to start - could not retrieve form details");

                                // we've lost the form id so start the form again
                                gotoStartPage(request, response, app, true);

                            } else {

                                // this is a form page's data being submitted
                                String formData = new String(bodyBytes, "UTF-8");

                                // log it!
                                logger.trace("Form data : " + formData);

                                // if there's a submit action
                                if ("submit".equals(request.getParameter("action"))) {

                                    // if submitted already go to start (should never happen)
                                    if (formDetails.getSubmitted()) {

                                        logger.debug(
                                                "Returning to start - submit action but form not submitted");

                                        // go to the start page
                                        gotoStartPage(request, response, app, true);

                                    } else {

                                        try {

                                            // do the submit (this will call the non-abstract submit, manage the form state, and retain the submit message)
                                            formAdapter.doSubmitForm(rapidRequest);

                                            // place holder for first submitted page
                                            String submittedPageId = getFirstPageForFormType(app,
                                                    Page.FORM_PAGE_TYPE_SUBMITTED);

                                            // check we got a submitted page
                                            if (submittedPageId == null) {

                                                // invalidate the form 
                                                formAdapter.setUserFormDetails(rapidRequest, null);

                                                logger.debug(
                                                        "Returning to start - form has been submitted, no submission page");

                                                // go to the start page
                                                gotoStartPage(request, response, app, true);

                                            } else {

                                                // request the first submitted page
                                                response.sendRedirect("~?a=" + app.getId() + "&v="
                                                        + app.getVersion() + "&p=" + submittedPageId);

                                            }

                                        } catch (Exception ex) {

                                            // place holder for first submitted page
                                            String errrorPageId = getFirstPageForFormType(app,
                                                    Page.FORM_PAGE_TYPE_ERROR);

                                            // check we got one
                                            if (errrorPageId == null) {

                                                // just re throw the error
                                                throw ex;

                                            } else {

                                                // request the first error page
                                                response.sendRedirect("~?a=" + app.getId() + "&v="
                                                        + app.getVersion() + "&p=" + errrorPageId);

                                            }

                                        }

                                    } // submit check

                                } else {

                                    // try
                                    try {

                                        // get the page
                                        Page page = rapidRequest.getPage();

                                        // if we got one
                                        if (page == null) {

                                            // send error
                                            sendMessage(response, 403, "Page does not exist",
                                                    "The page you requested does not exist");

                                        } else {

                                            // get the page id
                                            String requestPageId = rapidRequest.getPage().getId();

                                            // if form not submitted
                                            if (!formDetails.getSubmitted()) {

                                                // get the page control values
                                                FormPageControlValues pageControlValues = FormAdapter
                                                        .getPostPageControlValues(rapidRequest, formData,
                                                                formDetails.getId());

                                                // check we got some
                                                if (pageControlValues != null) {

                                                    // loop and print them if trace on
                                                    if (logger.isTraceEnabled()) {
                                                        for (FormControlValue controlValue : pageControlValues) {
                                                            logger.debug(controlValue.getId() + " = "
                                                                    + controlValue.getValue());
                                                        }
                                                    }

                                                    // store the form page control values
                                                    formAdapter.setFormPageControlValues(rapidRequest,
                                                            formDetails.getId(), requestPageId,
                                                            pageControlValues);

                                                }

                                            }

                                            // assume we're not going to go to the summary
                                            boolean requestSummary = false;

                                            // get all of the app pages
                                            PageHeaders pageHeaders = app.getPages().getSortedPages();

                                            // get the position of the next page in sequence
                                            int pageIndex = pageHeaders.indexOf(requestPageId) + 1;

                                            // get the next page
                                            page = app.getPages().getPage(getServletContext(),
                                                    pageHeaders.get(pageIndex).getId());

                                            // check the page visibility
                                            while (!page.isVisible(rapidRequest, app, formDetails)) {
                                                // if we're here the visibility check on the current page failed so increment the index
                                                pageIndex++;
                                                // if there are no more pages go to the summary
                                                if (pageIndex > pageHeaders.size() - 1) {
                                                    // but set the the show summary to true
                                                    requestSummary = true;
                                                    // we're done
                                                    break;
                                                } else {
                                                    // select the next page to check the visibility of
                                                    page = app.getPages().getPage(getServletContext(),
                                                            pageHeaders.get(pageIndex).getId());
                                                    // if not submitted set that we're allowed to this page
                                                    if (!formDetails.getSubmitted())
                                                        formAdapter.setMaxPage(rapidRequest, formDetails,
                                                                page.getId());
                                                } // pages remaining check                           
                                            } // page visible loop      

                                            // if this is the last page
                                            if (requestSummary) {

                                                // mark that this form is complete (if not submitted)
                                                if (!formDetails.getSubmitted())
                                                    formAdapter.setFormComplete(rapidRequest, formDetails);

                                                // send a redirect for the summary (this also avoids ERR_CACH_MISS issues on the back button )
                                                response.sendRedirect("~?a=" + app.getId() + "&v="
                                                        + app.getVersion() + "&action=summary");

                                            } else {

                                                // set that we're allowed to this page
                                                if (!formDetails.getSubmitted())
                                                    formAdapter.setMaxPage(rapidRequest, formDetails,
                                                            page.getId());

                                                // send a redirect for the page (this avoids ERR_CACH_MISS issues on the back button )
                                                response.sendRedirect("~?a=" + app.getId() + "&v="
                                                        + app.getVersion() + "&p=" + page.getId());

                                            } // last page check      

                                        } // page check

                                    } catch (ServerSideValidationException ex) {

                                        // log it!
                                        logger.error(
                                                "Form data failed server side validation : " + ex.getMessage(),
                                                ex);

                                        // send a redirect back to the beginning - there's no reason except for tampering  that this would happen
                                        gotoStartPage(request, response, app, true);

                                    }

                                } // form id check

                            } // submit action check

                        } // form adapter check

                    } else if ("checkVersion".equals(rapidRequest.getActionName())) {

                        // create a json version object
                        JSONObject jsonVersion = new JSONObject();

                        // add the mobile version, followed by the app version
                        jsonVersion.put("version", MOBILE_VERSION + " - " + app.getVersion());

                        // create a writer
                        PrintWriter out = response.getWriter();

                        // print the results
                        out.print(jsonVersion.toString());

                        // close the writer
                        out.close();

                        // log response
                        logger.debug("Rapid POST response : " + jsonVersion.toString());

                    } else if ("uploadImage".equals(rapidRequest.getActionName())) {

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

                        // if we got one
                        if (imageName == null) {

                            // send forbidden response         
                            sendMessage(response, 400, "Name required", "Image name must be provided");

                            // log
                            logger.debug("Rapid POST response (403) : Name must be provided");

                        } else {

                            // check the jpg file signature (from http://en.wikipedia.org/wiki/List_of_file_signatures)
                            if (bodyBytes[0] == (byte) 0xFF && bodyBytes[1] == (byte) 0xD8
                                    && bodyBytes[2] == (byte) 0xFF) {

                                // create the path
                                String imagePath = "uploads/" + app.getId() + "/" + imageName;
                                // create a file
                                File imageFile = new File(getServletContext().getRealPath(imagePath));
                                // create app folder if need be
                                imageFile.getParentFile().mkdir();
                                // create a file output stream to save the data to
                                FileOutputStream fos = new FileOutputStream(imageFile);
                                // write the body bytes to the stream
                                fos.write(bodyBytes);
                                // close the stream
                                fos.close();

                                // log the file creation
                                logger.debug("Saved image file " + imageFile);

                                // create a writer
                                PrintWriter out = response.getWriter();

                                // print the results
                                out.print(imagePath);

                                // close the writer
                                out.close();

                            } else {

                                // send forbidden response         
                                sendMessage(response, 400, "Unrecognised", "Unrecognised file type");

                                // log
                                logger.debug("Rapid POST response (403) : Unrecognised file type");

                            } // signature check

                        } // upload file name check

                    } // action check

                } else {

                    // send forbidden response         
                    sendMessage(response, 403, "No permisssion",
                            "You do not have permssion to use this application");

                    // log
                    logger.debug("Rapid POST response (403) : User not authorised for application");

                } // user check

            } // app check

        } // pre app action check

    } catch (Exception ex) {

        logger.error("Rapid POST error : ", ex);

        sendException(rapidRequest, response, ex);

    }

}

From source file:org.metis.pull.WdsResourceBean.java

/**
 * This method gets called by the WdsRdbMapper bean to handle a HTTP
 * request. This method must be multi-thread capable. Note that since we're
 * not using Views, this method must return null.
 * /*from  w ww.j ava2  s. c o  m*/
 * @param request
 *            the http request that is being serviced
 * @param response
 *            the response that will be sent back to the service consumer
 * @return must return null since we're not using a view
 * @throws Exception
 */
@SuppressWarnings("unchecked")
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    LOG.debug(getBeanName() + ": handleRequestInternal - **** new request ****");

    // dump the request if trace is on
    if (LOG.isTraceEnabled()) {
        LOG.trace(getBeanName() + ":handleRequestInternal - method = " + request.getMethod());
        LOG.trace(getBeanName() + ":handleRequestInternal - uri  = " + request.getRequestURI());
        LOG.trace(getBeanName() + ":handleRequestInternal - protocol  = " + request.getProtocol());
        LOG.trace(getBeanName() + ":handleRequestInternal - secure  = " + request.isSecure());

        // dump all the http headers and their values
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                LOG.trace(getBeanName() + ":handleRequestInternal - " + headerName + " = "
                        + request.getHeader(headerName));
            }
        }

        if (request.getQueryString() != null) {
            LOG.trace(getBeanName() + ":handleRequestInternal - queryString  = " + request.getQueryString());
        }
    }

    long currentTime = System.currentTimeMillis();

    // give the response a Date header with the current time
    response.setDateHeader(DATE_HDR, currentTime);

    // assign the Server header this container's info
    response.setHeader(SERVER_HDR, getServerInfo());

    // determine the HTTP protocol version being used by the client
    // default version will be 0
    int protocolVersion = 0;
    try {
        protocolVersion = Integer
                .parseInt(request.getProtocol().split(FORWARD_SLASH_STR)[1].split(ESC_DOT_STR)[1]);
    } catch (Exception exc) {
        LOG.warn(getBeanName() + ": handleRequestInternal - unable to get http protocol "
                + "version, stack trace follows: ");
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
    }

    LOG.trace(getBeanName() + ":handleRequestInternal - using this " + "protocol version: " + protocolVersion);

    /*
     * Ok, the request first needs to run the security gauntlet
     * 
     * We do not want to send any error messages back to the client that
     * would give it a hint that we're invoking SQL statements. This is a
     * countermeasure for SQL injection probes.
     */

    // see if this RDB is restricting user agents and if so, validate user
    // agent
    if ((getAllowedAgents() != null && !getAllowedAgents().isEmpty())
            || (getNotAllowedAgents() != null && !getNotAllowedAgents().isEmpty())) {

        String userAgent = request.getHeader(USER_AGENT_HDR);

        if (userAgent != null && userAgent.length() > 0) {
            LOG.debug(
                    getBeanName() + ": handleRequestInternal - validating this " + "user agent: " + userAgent);

            // Convert to lower case as allowed agents have been
            // converted to lower case as well
            userAgent = userAgent.toLowerCase();

            boolean allow = false;
            if (getAllowedAgents() != null && !getAllowedAgents().isEmpty()) {
                for (String agent : getAllowedAgents()) {
                    LOG.trace(getBeanName() + ": handleRequestInternal - comparing to this "
                            + "allowed agent : " + agent);
                    if (userAgent.indexOf(agent) >= 0) {
                        LOG.trace(getBeanName() + ": handleRequestInternal - this allowed agent "
                                + "was found: " + agent);
                        allow = true;
                        break;
                    }
                }
            } else {
                allow = true;
                for (String agent : getNotAllowedAgents()) {
                    LOG.trace(getBeanName() + ": handleRequestInternal - comparing to this "
                            + "non-allowed agent : " + agent);
                    if (userAgent.indexOf(agent) >= 0) {
                        LOG.trace(getBeanName() + ": handleRequestInternal - this non-allowed "
                                + "agent was found: " + agent);
                        allow = false;
                        break;
                    }
                }
            }
            if (!allow) {
                response.sendError(SC_UNAUTHORIZED, "ERROR, user agent " + "is not authorized");
                LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user agent is " + "not authorized");
                return null;
            }
        } else {
            response.sendError(SC_UNAUTHORIZED,
                    "ERROR, user agent info " + "was not received and is required!");
            LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user agent header "
                    + "is required but was not provided by the client");
            return null;
        }
    }

    // we do not support chunked transfer encoding, which is a http
    // 1.1 feature.
    if (request.getHeader(TRANSFER_ENCODING_HDR) != null
            && request.getHeader(TRANSFER_ENCODING_HDR).equalsIgnoreCase(CHUNKED)) {
        response.sendError(SC_BAD_REQUEST, "Chunked tranfer encoding is not " + "supported");
        return null;
    }

    /*
     * isSecure returns a boolean indicating whether this request was made
     * using a secure channel, such as HTTPS. so, if the channel must be
     * secure, but it is not, then throw an exception and return an error.
     */
    if (isSecure() && !request.isSecure()) {
        response.sendError(SC_UNAUTHORIZED, "ERROR, channel is not secure");
        LOG.error(getBeanName() + ": handleRequestInternal - ERROR, channel is not secure");
        return null;
    }

    /*
     * getUserPrincipal() returns a java.security.Principal containing the
     * name of the user making this request, else it returns null if the
     * user has not been authenticated. so, if it is mandated that the user
     * be authenticated, but has not been authenticated, then throw an
     * exception and return an error
     */
    if (isAuthenticated() && request.getUserPrincipal() == null) {
        response.sendError(SC_UNAUTHORIZED, "ERROR, user is not authenticated");
        LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user is not authenticated");
        return null;
    }

    /*
     * Check for valid method - the only supported http methods are GET,
     * POST, PUT, and DELETE. Here are some good descriptions regarding the
     * methods and their use with respect to this servlet.
     * 
     * The GET method is used for projecting data from the DB. So it maps to
     * a select statement.
     * 
     * The PUT and POST methods are used for inserting or updating an entity
     * in the DB. So they map to either an update or insert.
     * 
     * The DELETE is used for removing one or more entities from the DB. So
     * it maps to a delete.
     * 
     * The bean must be assigned at least one of the methods to service
     */
    Method method = null;
    try {
        method = Enum.valueOf(Method.class, request.getMethod().toUpperCase());
        LOG.debug(getBeanName() + ": handleRequestInternal - processing this method: " + method.toString());
    } catch (IllegalArgumentException e) {
        LOG.error(getBeanName() + ":handleRequestInternal - This method is not allowed [" + request.getMethod()
                + "]");
        response.setHeader("Allow", allowedMethodsRsp);
        response.sendError(SC_METHOD_NOT_ALLOWED, "This method is not allowed [" + request.getMethod() + "]");
        return null;
    }

    // do some more method validation; i.e., make sure requested method has
    // been assigned a SQL statement
    //
    // TODO: we may be able to remove this block of code
    String s1 = null;
    if (method.isGet() && sqlStmnts4Get == null || method.isPost() && sqlStmnts4Post == null
            || method.isPut() && sqlStmnts4Put == null || method.isDelete() && sqlStmnts4Delete == null) {
        response.setHeader("Allow", allowedMethodsRsp);
        s1 = "HTTP method [" + method + "] is not supported";
        response.sendError(SC_METHOD_NOT_ALLOWED, s1);
        LOG.error(getBeanName() + ":handleRequestInternal - " + s1);
        return null;
    }

    // If the client has specified an 'Accept' header field, then determine
    // if it is willing or capable of accepting JSON or anything (*/*)
    //
    // TODO: what about the client accepting urlencoded strings??
    s1 = request.getHeader(ACCEPT_HDR);
    if (s1 != null && s1.length() > 0) {
        LOG.debug(getBeanName() + ":handleRequestInternal - client-specified media "
                + "type in accept header = " + s1);
        // parse the accept header's content
        String[] mediaTypes = s1.trim().split(COMMA_STR);
        boolean match = false;
        for (String mediaType : mediaTypes) {
            mediaType = mediaType.trim().toLowerCase();
            if (mediaType.startsWith(anyContentType) || mediaType.startsWith(jsonContentType)) {
                match = true;
                break;
            }
        }
        if (!match) {
            LOG.error(getBeanName() + ":handleRequestInternal - client-specified media type of '" + s1
                    + "' does not include '" + "'" + jsonContentType);
            response.sendError(SC_NOT_ACCEPTABLE, "client-specified media " + "type of '" + s1
                    + "' does not include '" + "'" + jsonContentType);
            return null;
        }
    }

    // pick up the corresponding list of SQL statements for this request
    List<SqlStmnt> sqlStmnts = null;
    switch (method) {
    case GET:
        sqlStmnts = getSqlStmnts4Get();
        break;
    case DELETE:
        sqlStmnts = getSqlStmnts4Delete();
        break;
    case PUT:
        sqlStmnts = getSqlStmnts4Put();
        break;
    case POST:
        sqlStmnts = getSqlStmnts4Post();
        break;
    default:
        response.sendError(SC_METHOD_NOT_ALLOWED, "ERROR, unsupported method type: " + method);
        LOG.error(getBeanName() + ": handleRequestInternal - ERROR, encountered unknown " + "method type: "
                + method);
        return null;
    }

    // ~~~~~~ EXTRACT PARAMERTERS, IF ANY ~~~~~~~~~~~

    // GETs with entity bodies are illegal
    if (method.isGet() && request.getContentLength() > 0) {
        response.sendError(SC_BAD_REQUEST,
                "Client has issued a malformed or illegal request; " + "GET cannot include entity body");
        return null;
    }

    // the DELETE method also cannot include an entity body; however, the
    // servlet containers already ignore them. so no need to check for that

    // see if json object arrived
    boolean jsonObjectPresent = (method.isPost() || method.isPut())
            && (request.getContentLength() > 0 && request.getContentType().equalsIgnoreCase(jsonContentType));

    LOG.debug(getBeanName() + ": jsonObjectPresent = " + jsonObjectPresent);

    // see if this is a PUT with entity. we've learned that for PUTs,
    // getParameterMap does not work the same across all servlet containers.
    // so we need take care of this ourselves
    boolean putWithBodyPresent = (method.isPut()) && (request.getContentLength() > 0
            && request.getContentType().equalsIgnoreCase(urlEncodedContentType));

    LOG.debug(getBeanName() + ": putWithBodyPresent = " + putWithBodyPresent);

    // collect incoming parameters and place them in a common bucket
    //
    // ~~~~ ALL PARAMETER KEY NAMES MUST BE FORCED TO LOWER CASE ~~~
    //
    List<Map<String, String>> cParams = new ArrayList<Map<String, String>>();

    // first, get the incoming query or form parameters (if any); we will
    // assume that each key has only one parameter. in other words,
    // we're not dealing with drop-down boxes or things similar
    if (!putWithBodyPresent && !jsonObjectPresent) {
        Map<String, String[]> qParams = request.getParameterMap();
        if (qParams != null && !qParams.isEmpty()) {
            Map<String, String> qMap = new HashMap<String, String>();
            for (String key : qParams.keySet()) {
                qMap.put(key.toLowerCase(), qParams.get(key)[0]);
            }
            if (!qMap.isEmpty()) {
                cParams.add(qMap);
                LOG.debug(getBeanName() + ": query params = " + qMap.toString());
            }
        }
    }

    // a put with entity body arrived, so get the parameters from the
    // body and place them in the common bucket
    else if (putWithBodyPresent) {

        try {
            Map<String, String> putParams = null;
            // parseUrlEncoded will force keys to lower case
            putParams = Utils.parseUrlEncoded(request.getInputStream());
            if (putParams != null && !putParams.isEmpty()) {
                cParams.add(putParams);
            }
        } catch (Exception exc) {
            LOG.error(getBeanName() + ": ERROR, caught this " + "exception while parsing urlencoded string: "
                    + exc.toString());
            LOG.error(getBeanName() + ": exception stack trace follows:");
            dumpStackTrace(exc.getStackTrace());
            if (exc.getCause() != null) {
                LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
                LOG.error(getBeanName() + ": causing exception stack trace follows:");
                dumpStackTrace(exc.getCause().getStackTrace());
            }
            response.sendError(SC_BAD_REQUEST, "urlencoded string parsing error: " + exc.getMessage());
            return null;
        }
    }

    // ok, a json object arrived, so get parameters defined in that object
    // and place them in the common bucket
    else {
        // its a json object, so parse it to extract params from it
        try {
            List<Map<String, String>> jParams = null;
            // parseJson will ensure that all passed-in JSON objects have
            // the same set of identical keys
            jParams = Utils.parseJson(request.getInputStream());
            if (jParams != null && !jParams.isEmpty()) {
                // if we also got query params then ensure they have the
                // same set of keys as the json params. why anyone would
                // ever do this is beyond me, but I'll leave it in for now
                if (!cParams.isEmpty()) {
                    Map<String, String> cMap = cParams.get(0);
                    Map<String, String> jMap = jParams.get(0);
                    for (String key : cMap.keySet()) {
                        if (jMap.get(key) == null) {
                            String eStr = getBeanName() + ": ERROR, json "
                                    + "object key set does not match query " + "param key set";
                            LOG.error(eStr);
                            response.sendError(SC_BAD_REQUEST, eStr);
                            return null;
                        }
                    }
                    // place the passed in query params in the jParams
                    // bucket
                    jParams.add(cMap);
                }
                // assign the jParams bucket to the common bucket
                cParams = jParams;
            }
        } catch (Exception exc) {
            LOG.error(getBeanName() + ": ERROR, caught this " + "exception while parsing json object: "
                    + exc.toString());
            LOG.error(getBeanName() + ": exception stack trace follows:");
            dumpStackTrace(exc.getStackTrace());
            if (exc.getCause() != null) {
                LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
                LOG.error(getBeanName() + ": causing exception stack trace follows:");
                dumpStackTrace(exc.getCause().getStackTrace());
            }
            response.sendError(SC_BAD_REQUEST, "json parsing error: " + exc.getMessage());
            return null;
        }
    }

    // if trace is on, dump the params (if any) to the log
    if (LOG.isDebugEnabled()) {
        if (!cParams.isEmpty()) {
            for (int i = 0; i < cParams.size(); i++) {
                LOG.debug(getBeanName() + ": handleRequestInternal - received these params: "
                        + cParams.get(i).toString());
            }
        } else {
            LOG.debug(getBeanName() + ": handleRequestInternal - did not receive any params");
        }
    }

    // ensure none of the params' values have been black listed
    if (!cParams.isEmpty() && getBlackList().length() > 0) {
        char[] bl = getBlackList().toCharArray();
        for (int i = 0; i < cParams.size(); i++) {
            for (String value : cParams.get(i).values()) {
                if (Utils.isOnBlackList(value, bl)) {
                    response.sendError(SC_BAD_REQUEST,
                            "encountered black listed character in this param " + "value: " + value);
                    LOG.error(getBeanName() + "handleRequestInternal - encountered black listed "
                            + "character in this param value: " + value);
                    return null;
                }

            }
        }
    }

    // find the proper SQL statement based on the incoming parameters' (if
    // any) keys
    SqlStmnt sqlStmnt = null;
    try {
        // getMatch will try and find a match, even if no params were
        // provided.
        // @formatter:off
        sqlStmnt = (cParams.isEmpty()) ? SqlStmnt.getMatch(sqlStmnts, null)
                : SqlStmnt.getMatch(sqlStmnts, cParams.get(0).keySet());
        // @formatter:on

        if (sqlStmnt == null && !cParams.isEmpty()) {
            LOG.error(getBeanName() + ":ERROR, unable to find sql " + "statement with this incoming param set: "
                    + cParams.toString());
            response.sendError(SC_INTERNAL_SERVER_ERROR, "internal server error: mapping error");
            return null;
        } else if (sqlStmnt == null) {
            LOG.warn(getBeanName() + ": warning, unable to find sql "
                    + "statement on first pass, will use extra path info");
        } else {
            LOG.debug(getBeanName() + ": handleRequestInternal - matching sql stmt = " + sqlStmnt.toString());
        }
    } catch (Exception exc) {
        LOG.error(getBeanName() + ":ERROR, caught this exception " + "while mapping sql to params: "
                + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        if (exc.getCause() != null) {
            LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
            LOG.error(getBeanName() + ": causing exception stack trace follows:");
            dumpStackTrace(exc.getCause().getStackTrace());
        }
        response.sendError(SC_INTERNAL_SERVER_ERROR, "mapping error");
        return null;
    }

    // if getMatch could not find a match - perhaps input params were not
    // provided - then use the URI's 'extended path' information as an input
    // param
    if (sqlStmnt == null) {
        LOG.debug(getBeanName() + ": invoking getExtraPathInfo");
        String[] xtraPathInfo = Utils.getExtraPathInfo(request.getPathInfo());
        if (xtraPathInfo != null && xtraPathInfo.length >= 2) {
            LOG.debug(getBeanName() + ": extra path key:value = " + xtraPathInfo[0] + ":" + xtraPathInfo[1]);
        } else {
            LOG.error(getBeanName() + ":ERROR, getExtraPathInfo failed to find info");
            response.sendError(SC_INTERNAL_SERVER_ERROR, "internal server error: mapping error");
            return null;
        }
        // put the xtra path info in the common param bucket and try again
        cParams.clear();
        Map<String, String> xMap = new HashMap<String, String>();
        xMap.put(xtraPathInfo[0], xtraPathInfo[1]);
        cParams.add(xMap);
        // try again with the extra path info
        sqlStmnt = SqlStmnt.getMatch(sqlStmnts, xMap.keySet());
        if (sqlStmnt == null) {
            LOG.error(getBeanName() + ":ERROR, unable to find sql " + "statement with this xtra path info: "
                    + cParams.toString());
            response.sendError(SC_NOT_FOUND, "internal server error: mapping error");
            return null;
        }
    }

    // if we've gotten this far, we've gotten past the security gauntlet and
    // we have a SQL statement to work with.
    SqlResult sqlResult = null;
    try {
        // get the output stream
        OutputStream os = response.getOutputStream();

        // FIRE IN THE DB HOLE :)
        if ((sqlResult = sqlStmnt.execute(cParams)) == null) {
            // execute will have logged the necessary debug/error info
            response.sendError(SC_INTERNAL_SERVER_ERROR);
            return null;
        }

        // execute went through ok, lets see how to respond
        switch (method) {
        case GET:
            // if a resultset was returned, then set the content type,
            // convert it to json, and write it out
            List<Map<String, Object>> listMap = sqlResult.getResultSet();
            if (listMap != null) {
                // tell the client the content type
                response.setContentType(rspJsonContentType);
                String jsonOutput = Utils.generateJson(sqlResult.getResultSet());
                LOG.trace(getBeanName() + ": returning this payload - " + jsonOutput);
                os.write(jsonOutput.getBytes());

                // ensure that only the client can cache the data and tell
                // the client how long the data can remain active
                response.setHeader(CACHE_CNTRL_HDR,
                        (getCacheControl() != null) ? getCacheControl() : DFLT_CACHE_CNTRL_STR);
                response.setHeader(PRAGMA_HDR, PRAGMA_NO_CACHE_STR);
                response.setDateHeader(EXPIRES_HDR, currentTime + (getExpires() * 1000));
            } else {
                LOG.debug(getBeanName() + ": NOT returning json message");
            }
            response.setStatus(SC_OK);
            break;
        case DELETE:
            // a DELETE should not send back an entity body
            response.setStatus(SC_NO_CONTENT);
            break;
        case PUT:
            /*
             * PUTs are idempotent; therefore, they must provide ALL the
             * properties that pertain to the resource/entity that they are
             * creating or updating. Updates cannot be partial updates; they
             * must be full updates. A PUT is issued by a client that knows
             * the identifier (in our case, primary key) of the
             * resource/entity. Therefore, we do not have to send back a
             * Location header in response to a PUT that has created a
             * resource.
             */
            if (sqlStmnt.isInsert()) {
                response.setStatus(SC_CREATED);
            } else {
                response.setStatus(SC_OK);
            }
            break;
        case POST:
            /*
             * A POST is not idempotent; therefore, it can be used to
             * perform a 'partial' update, as well as a full create. When
             * creating a resource via POST, the client does not know the
             * primary key, and it assumes it will be auto-generated;
             * therefore, a Location header with auto-generated key must be
             * returned to client.
             */
            if (sqlStmnt.isInsert()) {
                response.setStatus(SC_CREATED);
                // we need to return the new key, but only if it was not a
                // batch insert. the new key should be returned via the
                // location header

                // check if a key holder exists; if not, then table was not
                // configured with auto-generated key.
                String locationPath = request.getRequestURL().toString();
                if (sqlResult.getKeyHolder() != null) {
                    // key holder exists, check and see if a key is
                    // present
                    if (sqlResult.getKeyHolder().getKey() != null) {
                        String id = sqlResult.getKeyHolder().getKey().toString();
                        LOG.debug(getBeanName() + ": getKey() returns " + id);
                        locationPath += ("/" + id);
                        LOG.debug(getBeanName() + ": locationPath = " + locationPath);
                        response.setHeader(LOCATION_HDR, locationPath);
                    }
                    // no key, check for multiple keys
                    // TODO: should we send back all keys?
                    else if (sqlResult.getKeyHolder().getKeys() != null) {
                        Map<String, Object> keyMap = sqlResult.getKeyHolder().getKeys();
                        LOG.debug(getBeanName() + ": getKeys() returns " + keyMap);
                    }
                    // maybe map of keys?
                    // TODO: should we send back all keys?
                    else if (sqlResult.getKeyHolder().getKeyList() != null) {
                        for (Map<String, Object> map : sqlResult.getKeyHolder().getKeyList()) {
                            LOG.debug(getBeanName() + ": Map from getKeyList(): " + map);
                        }
                    }
                } else {
                    // if it was not an insert, then it was an update.
                    LOG.debug(getBeanName() + ": key holder was not returned for the insert");
                }
            } else {
                // it was not an insert, so just send back an OK for the
                // update
                response.setStatus(SC_OK);
            }
            break;
        default:
            response.setStatus(SC_OK);
            break;
        }
    } catch (JsonProcessingException exc) {
        LOG.error(getBeanName() + ":ERROR, caught this " + "JsonProcessingException while trying to gen json "
                + "message: " + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        if (exc.getCause() != null) {
            LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
            LOG.error(getBeanName() + ": causing exception stack trace follows:");
            dumpStackTrace(exc.getCause().getStackTrace());
        }
        response.sendError(SC_INTERNAL_SERVER_ERROR, "parsing error");
        return null;
    } catch (Exception exc) {
        LOG.error(getBeanName() + ":ERROR, caught this " + "Exception while trying to gen json " + "message: "
                + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        if (exc.getCause() != null) {
            LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
            LOG.error(getBeanName() + ": causing exception stack trace follows:");
            dumpStackTrace(exc.getCause().getStackTrace());
        }
        response.sendError(SC_INTERNAL_SERVER_ERROR, "parsing error");
        return null;

    } finally {
        if (sqlResult != null) {
            SqlResult.enqueue(sqlResult);
        }
    }

    // must return null, because we're not using views!
    return null;
}

From source file:bookkeepr.jettyhandlers.CandidateHandler.java

public void handle(String path, HttpServletRequest request, HttpServletResponse response, int dispatch)
        throws IOException, ServletException {

    if (path.startsWith("/cand/")) {
        ((Request) request).setHandled(true);

        if (path.startsWith("/cand/lists")) {
            if (request.getMethod().equals("GET")) {
                if (path.startsWith("/cand/lists/from/")) {
                    long targetId = Long.parseLong(path.substring(17), 16);
                    if (dbMan.getType(new DummyIdAble(targetId)) == TypeIdManager
                            .getTypeFromClass(Psrxml.class)) {
                        CandListSelectionRequest req = new CandListSelectionRequest();
                        req.setAcceptPsrxmlIds(new long[] { targetId });
                        XMLWriter.write(response.getOutputStream(), candMan.getCandidateLists(req));

                    } else if (dbMan.getType(new DummyIdAble(targetId)) == TypeIdManager
                            .getTypeFromClass(Processing.class)) {
                        CandListSelectionRequest req = new CandListSelectionRequest();
                        req.setAcceptProcessingIds(new long[] { targetId });
                        XMLWriter.write(response.getOutputStream(), candMan.getCandidateLists(req));

                    } else {
                        response.sendError(400, "Bad GET request for /cand/lists/from/...");
                        return;
                    }//from  w  w w .  jav a 2  s  . co  m
                } else {
                    CandidateListIndex idx = new CandidateListIndex();
                    List<IdAble> list = dbMan
                            .getAllOfType(TypeIdManager.getTypeFromClass(CandidateListStub.class));
                    for (IdAble stub : list) {
                        idx.addCandidateListStub((CandidateListStub) stub);
                    }
                    OutputStream out = response.getOutputStream();
                    String hdr = request.getHeader("Accept-Encoding");
                    if (hdr != null && hdr.contains("gzip")) {
                        // if the host supports gzip encoding, gzip the output for quick transfer speed.
                        out = new GZIPOutputStream(out);
                        response.setHeader("Content-Encoding", "gzip");
                    }
                    XMLWriter.write(out, idx);
                    out.close();
                    return;
                }
            } else if (request.getMethod().equals("POST")) {
                try {
                    XMLAble xmlable = XMLReader.read(request.getInputStream());
                    if (xmlable instanceof CandListSelectionRequest) {
                        CandListSelectionRequest req = (CandListSelectionRequest) xmlable;
                        OutputStream out = response.getOutputStream();
                        String hdr = request.getHeader("Accept-Encoding");
                        if (hdr != null && hdr.contains("gzip")) {
                            // if the host supports gzip encoding, gzip the output for quick transfer speed.
                            out = new GZIPOutputStream(out);
                            response.setHeader("Content-Encoding", "gzip");
                        }
                        XMLWriter.write(out, candMan.getCandidateLists(req));
                        out.close();
                    } else {
                        response.sendError(400, "Bad POST request for /cand/lists");
                        return;
                    }
                } catch (SAXException ex) {
                    Logger.getLogger(CandidateHandler.class.getName()).log(Level.SEVERE, null, ex);
                }

            } else if (request.getMethod().equals("DELETE")) {
                String[] elems = path.substring(1).split("/");
                if (elems.length < 3) {
                    response.sendError(400, "Bad DELETE request for /cand/lists/{clistId}");
                    return;
                }
                final long clistId = Long.parseLong(elems[2], 16);
                CandidateListStub cls = (CandidateListStub) dbMan.getById(clistId);
                if (cls == null) {
                    response.sendError(404, "Bad ClistID requested for deletion (no such candlist)");
                    Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                            "Bad ClistID requested for deletion (no such candlist)");
                    return;
                }
                try {
                    this.candMan.deleteCandidateListAndCands(cls);
                    response.setStatus(202);
                } catch (BookKeeprException ex) {
                    response.sendError(500, "Could not delete candidate list as requested");
                    Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                            "Could not delete candidate list as requested", ex);
                    return;
                }

            } else {
                response.sendError(400, "Bad non-GET/non-POST/non-DELETE request for /cand/lists");
                return;
            }
        } else if (path.startsWith("/cand/viewed")) {
            if (request.getMethod().equals("GET")) {
                ViewedCandidatesIndex idx = new ViewedCandidatesIndex();
                List<IdAble> list = dbMan.getAllOfType(TypeIdManager.getTypeFromClass(ViewedCandidates.class));
                for (IdAble stub : list) {
                    idx.addViewedCandidates((ViewedCandidates) stub);
                }
                OutputStream out = response.getOutputStream();
                String hdr = request.getHeader("Accept-Encoding");
                if (hdr != null && hdr.contains("gzip")) {
                    // if the host supports gzip encoding, gzip the output for quick transfer speed.
                    out = new GZIPOutputStream(out);
                    response.setHeader("Content-Encoding", "gzip");
                }
                XMLWriter.write(out, idx);
                out.close();

                return;
            } else if (request.getMethod().equals("POST")) {
                ViewedCandidates newViewed = null;
                try {
                    XMLAble xmlable = XMLReader.read(request.getInputStream());
                    if (xmlable instanceof ViewedCandidates) {
                        newViewed = (ViewedCandidates) xmlable;
                    } else {
                        response.sendError(400, "Bad Content type in request /cand/viewed");
                        return;
                    }
                } catch (SAXException ex) {
                    Logger.getLogger(CandidateHandler.class.getName()).log(Level.INFO,
                            "Bad XML in client request to POST new viewed cands");
                    response.sendError(400, "Bad XML in request /cand/viewed");
                    return;
                }

                IdAble idable = this.dbMan.getById(newViewed.getId());
                if (idable instanceof ViewedCandidates) {
                    newViewed.append(((ViewedCandidates) idable));
                } else {
                    newViewed.setId(0);
                }

                Session session = new Session();
                this.dbMan.add(newViewed, session);
                try {
                    this.dbMan.save(session);
                } catch (BookKeeprException ex) {
                    Logger.getLogger(CandidateHandler.class.getName()).log(Level.SEVERE,
                            "Error saving viewed cands to database", ex);
                    response.sendError(500, "Error saving viewed cands to database");
                    return;
                }
                OutputStream out = response.getOutputStream();
                String hdr = request.getHeader("Accept-Encoding");
                if (hdr != null && hdr.contains("gzip")) {
                    // if the host supports gzip encoding, gzip the output for quick transfer speed.
                    out = new GZIPOutputStream(out);
                    response.setHeader("Content-Encoding", "gzip");
                }
                XMLWriter.write(out, newViewed);
                out.close();

                return;
            } else {
                response.sendError(400, "Bad non-GET/POST request /cand/viewed");
                return;
            }
        } else if (path.startsWith("/cand/psrcat")) {
            if (request.getMethod().equals("GET")) {
                String[] elems = path.substring(1).split("/");
                if (elems.length > 2) {
                    try {
                        long id = Long.parseLong(elems[2], 16);
                        ClassifiedCandidate cand = (ClassifiedCandidate) dbMan.getById(id);
                        String str = cand.getPsrcatEntry().toString();
                        response.setContentType("text/plain");
                        OutputStream out = response.getOutputStream();
                        String hdr = request.getHeader("Accept-Encoding");
                        if (hdr != null && hdr.contains("gzip")) {
                            // if the host supports gzip encoding, gzip the output for quick transfer speed.
                            out = new GZIPOutputStream(out);
                            response.setHeader("Content-Encoding", "gzip");
                        }
                        PrintWriter wr = new PrintWriter(out);
                        wr.write(str);
                        wr.close();
                        out.close();

                    } catch (ClassCastException ex) {
                        Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                                "Invalid candidate id passed to /cand/psrcat", ex);
                        response.sendError(400, "Bad id in request for /cand/psrcat");
                    }
                } else {
                    response.sendError(400, "Bad request for /cand/psrcat");
                }
            } else {
                response.sendError(400, "Bad non-GET request for /cand/psrcat");

            }
        } else if (path.startsWith("/cand/classified")) {
            if (request.getMethod().equals("GET")) {
                String[] elems = path.substring(1).split("/");
                ClassifiedCandidateIndex idx = new ClassifiedCandidateIndex();
                List<IdAble> list = dbMan
                        .getAllOfType(TypeIdManager.getTypeFromClass(ClassifiedCandidate.class));
                if (elems.length > 2) {

                    int cl = Integer.parseInt(elems[2]);
                    for (IdAble stub : list) {
                        if (((ClassifiedCandidate) stub).getCandClassInt() == cl) {
                            idx.addClassifiedCandidate((ClassifiedCandidate) stub);
                        }
                    }
                } else {

                    for (IdAble stub : list) {
                        idx.addClassifiedCandidate((ClassifiedCandidate) stub);
                    }
                }
                OutputStream out = response.getOutputStream();
                String hdr = request.getHeader("Accept-Encoding");
                if (hdr != null && hdr.contains("gzip")) {
                    // if the host supports gzip encoding, gzip the output for quick transfer speed.
                    out = new GZIPOutputStream(out);
                    response.setHeader("Content-Encoding", "gzip");
                }
                XMLWriter.write(out, idx);
                out.close();

                return;
            } else if (request.getMethod().equals("POST")) {
                // post a CandidateSelectRequest
                ClassifiedCandidateSelectRequest ccsreq = null;
                try {
                    XMLAble xmlable = XMLReader.read(request.getInputStream());
                    if (xmlable instanceof ClassifiedCandidateSelectRequest) {
                        ccsreq = (ClassifiedCandidateSelectRequest) xmlable;
                    } else {
                        response.sendError(400, "Bad item posted to /cand/classified for Searching");
                        return;
                    }
                } catch (SAXException ex) {
                    response.sendError(400, "Bad item posted to /cand/classified for Searching");
                    return;
                }

                // reply with the searched index
                ClassifiedCandidateIndex idx = candMan.searchCandidates(ccsreq);
                OutputStream out = response.getOutputStream();
                String hdr = request.getHeader("Accept-Encoding");
                if (hdr != null && hdr.contains("gzip")) {
                    // if the host supports gzip encoding, gzip the output for quick transfer speed.
                    out = new GZIPOutputStream(out);
                    response.setHeader("Content-Encoding", "gzip");
                }
                XMLWriter.write(out, idx);
                out.close();

            } else {
                response.sendError(400, "Bad non-POST/GET request /cand/classified");
                return;
            }
        } else if (path.startsWith("/cand/newclassified")) {
            if (request.getMethod().equals("POST")) {

                ClassifiedCandidate cand = null;
                try {
                    XMLAble xmlable = XMLReader.read(request.getInputStream());
                    if (xmlable instanceof ClassifiedCandidate) {
                        cand = (ClassifiedCandidate) xmlable;
                    } else {
                        response.sendError(400, "Bad item posted to /cand/newclassified for Classifying");
                        return;
                    }
                } catch (SAXException ex) {
                    response.sendError(400, "Bad item posted to /cand/newclassified for Classifying");
                    return;
                }

                cand.setId(0);

                Session session = new Session();
                dbMan.add(cand, session);
                try {
                    dbMan.save(session);
                } catch (BookKeeprException ex) {
                    Logger.getLogger(CandidateHandler.class.getName()).log(Level.SEVERE,
                            "error saving database when adding new classified cand", ex);
                    response.sendError(500, "error saving database when adding new classified cand");
                }
                OutputStream out = response.getOutputStream();
                String hdr = request.getHeader("Accept-Encoding");
                if (hdr != null && hdr.contains("gzip")) {
                    // if the host supports gzip encoding, gzip the output for quick transfer speed.
                    out = new GZIPOutputStream(out);
                    response.setHeader("Content-Encoding", "gzip");
                }
                XMLWriter.write(out, cand);
                out.close();

                return;
            } else {
                response.sendError(400, "Bad non-POST request /cand/newclassified");
                return;
            }
        } else if (path.startsWith("/cand/add/")) {
            // assume that 'add' is not an ID, since it would have server and type = 0, which is invalid.
            if (request.getMethod().equals("POST")) {
                String[] elems = path.substring(1).split("/");
                if (elems.length < 4) {
                    response.sendError(400, "Bad URL for /cand/add/{psrxmlId}/{procId}");
                    return;
                }

                final long psrxmlId = Long.parseLong(elems[2], 16);
                final long procId = Long.parseLong(elems[3], 16);

                if (dbMan.getById(procId) == null) {
                    response.sendError(400, "Bad URL for /cand/add/{psrxmlId}/{procId}. ProcId "
                            + Long.toHexString(procId) + " does not exist!");
                    return;
                }
                if (dbMan.getById(psrxmlId) == null) {
                    response.sendError(400, "Bad URL for /cand/add/{psrxmlId}/{procId}. PsrxmlId "
                            + Long.toHexString(psrxmlId) + " does not exist!");
                    return;
                }

                synchronized (this) {
                    if (nAddSubmitted > 2) {
                        // too many jobs on. to prevent memory overload, end the session!
                        response.setHeader("Retry-After", "60");
                        response.sendError(503);
                        return;
                    } else {
                        //increment the workload counter
                        nAddSubmitted++;
                    }
                }

                final ArrayList<RawCandidate> rawCands = new ArrayList<RawCandidate>();
                if (request.getContentType().equals("application/x-tar")) {
                    TarInputStream tarin = new TarInputStream(request.getInputStream());
                    while (true) {
                        // loop over all entries in the tar file.
                        TarEntry tarEntry = tarin.getNextEntry();
                        if (tarEntry == null) {
                            break;
                        } else {
                        }
                        InputStream inStream;

                        /*
                         * There is some complication as the XML reader
                         * closes the input stream when it is done, but we
                         * don't want to do that as it closes the entire tar
                         * 
                         * So we define a 'UnclosableInputStream' that ignores
                         * the close() command. 
                         * 
                         * If we have a gzipped xml file, we should pass
                         * through a gzip input stream too.
                         */
                        if (tarEntry.getName().endsWith(".gz")) {
                            inStream = new UncloseableInputStream(new GZIPInputStream(tarin));
                        } else {
                            inStream = new UncloseableInputStream(tarin);
                        }
                        try {
                            // parse the xml document.
                            XMLAble xmlable = (XMLAble) XMLReader.read(inStream);
                            if (xmlable instanceof RawCandidate) {
                                rawCands.add((RawCandidate) xmlable);
                            } else {
                                response.sendError(400, "POSTed tar file MUST only contain raw candidates.");
                                return;
                            }

                        } catch (SAXException ex) {
                            Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING, null, ex);
                            response.sendError(400, "POSTed tar file MUST only contain vaild xml candidates.");
                            return;
                        }

                    }
                    // finaly, we can close the tar stream.
                    tarin.close();
                    Logger.getLogger(CandidateHandler.class.getName()).log(Level.INFO,
                            "Received " + rawCands.size() + " raw candidates for processing from "
                                    + request.getRemoteAddr());

                    final BackgroundedTask bgtask = new BackgroundedTask("AddRawCandidates");

                    bgtask.setTarget(new Runnable() {

                        public void run() {
                            candMan.addRawCandidates(rawCands, psrxmlId, procId);
                            synchronized (CandidateHandler.this) {
                                // decriment the counter for how many workloads are left to do.
                                CandidateHandler.this.nAddSubmitted--;
                            }
                        }
                    });
                    bookkeepr.getBackgroundTaskRunner().offer(bgtask);
                    StringBuffer buf = new StringBuffer();
                    Formatter formatter = new Formatter(buf);
                    formatter.format("%s/%s/%d", bookkeepr.getConfig().getExternalUrl(), "tasks",
                            bgtask.getId());
                    response.setStatus(303);
                    response.addHeader("Location", buf.toString());
                    return;
                } else {
                    response.sendError(400, "Must POST application/x-tar type documents to this URL");
                }
            } else {
                response.sendError(400, "Bad non-POST request /cand/add");
                return;
            }
        } else {
            // see if we are requesting and ID.
            long targetId = 0;
            String[] elems = path.substring(1).split("/");

            // try and make an int from the passed value.
            try {
                if (elems.length < 2) {
                    response.sendError(400, "Bad URL for /cand/{id}");
                    return;
                }
                targetId = Long.parseLong(elems[1], 16);
            } catch (NumberFormatException ex) {
                Logger.getLogger(CandidateHandler.class.getName()).log(Level.INFO,
                        "Recieved request for bad id " + elems[1]);
                response.sendError(400, "Submitted URI was malformed\nMessage was '" + ex.getMessage() + "'");
                return;
            }

            IdAble idable = dbMan.getById(targetId);
            if (idable == null) {
                Logger.getLogger(CandidateHandler.class.getName()).log(Level.INFO,
                        "Recieved request for non-existing ID " + Long.toHexString(targetId));
                response.sendError(400,
                        "Submitted request was for non-existing ID " + Long.toHexString(targetId));
                return;
            }

            if (idable instanceof CandidateListStub) {
                if (request.getMethod().equals("GET")) {
                    int origin = dbMan.getOrigin(idable);
                    if (dbMan.getOriginId() == origin) {
                        // request for a local item...
                        response.setHeader("Content-Encoding", "gzip");
                        outputToInput(
                                new FileInputStream(candMan.getCandidateListFile((CandidateListStub) idable)),
                                response.getOutputStream());

                    } else {
                        HttpClient httpclient = bookkeepr.checkoutHttpClient();

                        try {
                            // request for a remote item...
                            BookkeeprHost host = bookkeepr.getConfig().getBookkeeprHost(origin);
                            String targetpath = host.getUrl() + path;
                            HttpGet httpreq = new HttpGet(targetpath);
                            HttpResponse httpresp = httpclient.execute(httpreq);
                            for (Header head : httpresp.getAllHeaders()) {
                                if (head.getName().equalsIgnoreCase("transfer-encoding")) {
                                    continue;
                                }
                                response.setHeader(head.getName(), head.getValue());
                            }
                            response.setStatus(httpresp.getStatusLine().getStatusCode());
                            httpresp.getEntity().writeTo(response.getOutputStream());

                        } catch (URISyntaxException ex) {
                            Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                                    "Bad uri specified for remote candidate", ex);
                            response.sendError(500, "Bad uri specified for remote candidate");
                        } catch (HttpException ex) {
                            Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                                    "Could not make a httpreqest for remote Candidate", ex);
                            response.sendError(500, "Could not make a httpreqest for remote Candidate");
                        } catch (IOException ex) {
                            Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                                    "Could not make a httpreqest for remote Candidate", ex);
                            response.sendError(500, "Could not make a httpreqest for remote Candidate");
                        }
                        bookkeepr.returnHttpClient(httpclient);

                        //                            if (host != null) {
                        //                                response.setStatus(301);
                        //                                response.addHeader("Location", host.getUrl() + path);
                        //                            } else {
                        //                                response.sendError(500, "Cannot find a bookkeepr server for origin id " + origin);
                        //                            }
                    }
                } else {
                    response.sendError(400, "Bad non-GET request for a candidate list");
                    return;
                }
            } else if (idable instanceof ClassifiedCandidate) {

                // /cand/{id}

                if (request.getMethod().equals("POST")) {
                    //                        int origin = dbMan.getOrigin(idable);
                    //                        if (dbMan.getOriginId() == origin) {
                    RawCandidateMatched stub = null;
                    try {
                        XMLAble xmlable = XMLReader.read(request.getInputStream());
                        if (xmlable instanceof RawCandidateMatched) {
                            stub = (RawCandidateMatched) xmlable;
                        } else {
                            response.sendError(400, "Bad item posted to /cand/... for Classifying");
                            return;
                        }
                    } catch (SAXException ex) {
                        response.sendError(400, "Bad item posted to /cand/... for Classifying");
                        return;
                    }
                    ClassifiedCandidate c = null;
                    try {
                        c = (ClassifiedCandidate) ((ClassifiedCandidate) idable).clone();
                    } catch (CloneNotSupportedException ex) {
                        Logger.getLogger(CandidateHandler.class.getName()).log(Level.SEVERE, null, ex);
                        response.sendError(500,
                                "Server error that cannot happen happened! Classified Candidates are Cloneable!");
                        return;
                    }

                    c.addRawCandidateMatched(stub);

                    Session session = new Session();
                    dbMan.add(c, session);
                    try {
                        dbMan.save(session);
                    } catch (BookKeeprException ex) {
                        Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                                "Error when saving database adding raw to classified cand", ex);
                        response.sendError(500, "Error when saving database adding raw to classified cand");

                    }

                    OutputStream out = response.getOutputStream();
                    String hdr = request.getHeader("Accept-Encoding");
                    if (hdr != null && hdr.contains("gzip")) {
                        // if the host supports gzip encoding, gzip the output for quick transfer speed.
                        out = new GZIPOutputStream(out);
                        response.setHeader("Content-Encoding", "gzip");
                    }
                    XMLWriter.write(out, c);
                    out.close();

                    //                            OutputStream out = response.getOutputStream();
                    //                            String hdr = request.getHeader("Accept-Encoding");
                    //                            if (hdr != null && hdr.contains("gzip")) {
                    //                                // if the host supports gzip encoding, gzip the output for quick transfer speed.
                    //                                out = new GZIPOutputStream(out);
                    //                                response.setHeader("Content-Encoding", "gzip");
                    //                            }
                    //                            XMLWriter.write(out, idx);
                    //                            out.close();
                    //                        } else {
                    //                            // request for a remote item...
                    //                            // currently re-direct to the remote server.. perhaps we should pass through?
                    //                            BookkeeprHost host = bookkeepr.getConfig().getBookkeeprHost(origin);
                    //                            if (host != null) {
                    //                                response.setStatus(301);
                    //                                response.addHeader("Location", host.getUrl() + path);
                    //                            } else {
                    //                                response.sendError(500, "Cannot find a bookkeepr server for origin id " + origin);
                    //                            }
                    //                        }
                } else {
                    response.sendError(400, "Bad non-POST request for a classified candidate");
                    return;
                }
            } else if (idable instanceof RawCandidateStub) {
                if (request.getMethod().equals("GET")) {
                    int origin = dbMan.getOrigin(idable);
                    if (dbMan.getOriginId() == origin) {

                        if (elems.length > 2) {
                            try {
                                int h = 600;
                                int w = 800;
                                String[] parts = elems[2].split("x|\\.png");
                                if (parts.length > 1) {
                                    try {
                                        h = Integer.parseInt(parts[1]);
                                        w = Integer.parseInt(parts[0]);
                                    } catch (NumberFormatException e) {
                                        h = 600;
                                        w = 800;
                                    }
                                }
                                RawCandidate cand = (RawCandidate) XMLReader
                                        .read(new GZIPInputStream(new FileInputStream(
                                                candMan.getRawCandidateFile((RawCandidateStub) idable))));

                                response.setContentType("image/png");
                                BufferedImage img = candMan.makeImageOf(cand, w, h);
                                ImageIO.write(img, "png", response.getOutputStream());
                                return;
                            } catch (SAXException ex) {
                                Logger.getLogger(CandidateHandler.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }

                        // request for a local item...
                        response.setHeader("Content-Encoding", "gzip");
                        outputToInput(
                                new FileInputStream(candMan.getRawCandidateFile((RawCandidateStub) idable)),
                                response.getOutputStream());

                    } else {
                        HttpClient httpclient = bookkeepr.checkoutHttpClient();

                        try {
                            // request for a remote item...
                            BookkeeprHost host = bookkeepr.getConfig().getBookkeeprHost(origin);
                            String targetpath = host.getUrl() + path;
                            HttpGet httpreq = new HttpGet(targetpath);
                            HttpResponse httpresp = httpclient.execute(httpreq);
                            for (Header head : httpresp.getAllHeaders()) {
                                if (head.getName().equalsIgnoreCase("transfer-encoding")) {
                                    continue;
                                }
                                response.setHeader(head.getName(), head.getValue());
                            }
                            response.setStatus(httpresp.getStatusLine().getStatusCode());
                            httpresp.getEntity().writeTo(response.getOutputStream());

                        } catch (URISyntaxException ex) {
                            Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                                    "Bad uri specified for remote candidate", ex);
                            response.sendError(500, "Bad uri specified for remote candidate");
                        } catch (HttpException ex) {
                            Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                                    "Could not make a httpreqest for remote Candidate", ex);
                            response.sendError(500, "Could not make a httpreqest for remote Candidate");
                        } catch (IOException ex) {
                            Logger.getLogger(CandidateHandler.class.getName()).log(Level.WARNING,
                                    "Could not make a httpreqest for remote Candidate", ex);
                            response.sendError(500, "Could not make a httpreqest for remote Candidate");
                        }
                        bookkeepr.returnHttpClient(httpclient);
                    }

                } else {
                    response.sendError(400, "Bad non-GET request for a raw candidate");
                    return;
                }
            } else {
                Logger.getLogger(CandidateHandler.class.getName()).log(Level.INFO,
                        "Recieved request for non-candidate ID " + targetId);
                response.sendError(400, "Submitted request was for non-candidate ID " + targetId);
                return;
            }
        }

    }
}

From source file:com.rapid.server.Designer.java

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

    RapidRequest rapidRequest = new RapidRequest(this, request);

    try {/* w  w w .  j  a va  2  s. c  o m*/

        String output = "";

        // read bytes from request body into our own byte array (this means we can deal with images) 
        InputStream input = request.getInputStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        for (int length = 0; (length = input.read(_byteBuffer)) > -1;)
            outputStream.write(_byteBuffer, 0, length);
        byte[] bodyBytes = outputStream.toByteArray();

        // get the rapid application
        Application rapidApplication = getApplications().get("rapid");

        // check we got one
        if (rapidApplication != null) {

            // get rapid security
            SecurityAdapter rapidSecurity = rapidApplication.getSecurityAdapter();

            // check we got some
            if (rapidSecurity != null) {

                // get user name
                String userName = rapidRequest.getUserName();
                if (userName == null)
                    userName = "";

                // check permission
                if (rapidSecurity.checkUserRole(rapidRequest, Rapid.DESIGN_ROLE)) {

                    Application application = rapidRequest.getApplication();

                    if (application != null) {

                        if ("savePage".equals(rapidRequest.getActionName())) {

                            String bodyString = new String(bodyBytes, "UTF-8");

                            getLogger().debug("Designer POST request : " + request.getQueryString() + " body : "
                                    + bodyString);

                            JSONObject jsonPage = new JSONObject(bodyString);

                            // instantiate a new blank page
                            Page newPage = new Page();

                            // set page properties
                            newPage.setId(jsonPage.optString("id"));
                            newPage.setName(jsonPage.optString("name"));
                            newPage.setTitle(jsonPage.optString("title"));
                            newPage.setFormPageType(jsonPage.optInt("formPageType"));
                            newPage.setLabel(jsonPage.optString("label"));
                            newPage.setDescription(jsonPage.optString("description"));
                            newPage.setSimple(jsonPage.optBoolean("simple"));

                            // look in the JSON for an event array
                            JSONArray jsonEvents = jsonPage.optJSONArray("events");
                            // add the events if we found one
                            if (jsonEvents != null)
                                newPage.setEvents(Control.getEvents(this, jsonEvents));

                            // look in the JSON for a styles array
                            JSONArray jsonStyles = jsonPage.optJSONArray("styles");
                            // if there were styles
                            if (jsonStyles != null)
                                newPage.setStyles(Control.getStyles(this, jsonStyles));

                            // if there are child controls from the page loop them and add to the pages control collection
                            JSONArray jsonControls = jsonPage.optJSONArray("childControls");
                            if (jsonControls != null) {
                                for (int i = 0; i < jsonControls.length(); i++) {
                                    // get the JSON control
                                    JSONObject jsonControl = jsonControls.getJSONObject(i);
                                    // call our function so it can go iterative
                                    newPage.addControl(createControl(jsonControl));
                                }
                            }

                            // if there are roles specified for this page
                            JSONArray jsonUserRoles = jsonPage.optJSONArray("roles");
                            if (jsonUserRoles != null) {
                                List<String> userRoles = new ArrayList<String>();
                                for (int i = 0; i < jsonUserRoles.length(); i++) {
                                    // get the JSON role
                                    String jsonUserRole = jsonUserRoles.getString(i);
                                    // add to collection
                                    userRoles.add(jsonUserRole);
                                }
                                // assign to page
                                newPage.setRoles(userRoles);
                            }

                            // look in the JSON for a sessionVariables array
                            JSONArray jsonSessionVariables = jsonPage.optJSONArray("sessionVariables");
                            // if we found one
                            if (jsonSessionVariables != null) {
                                List<String> sessionVariables = new ArrayList<String>();
                                for (int i = 0; i < jsonSessionVariables.length(); i++) {
                                    sessionVariables.add(jsonSessionVariables.getString(i));
                                }
                                newPage.setSessionVariables(sessionVariables);
                            }

                            // look in the JSON for a pageVisibilityRules array
                            JSONArray jsonVisibilityConditions = jsonPage.optJSONArray("visibilityConditions");
                            // if we found one
                            if (jsonVisibilityConditions != null) {
                                List<Condition> visibilityConditions = new ArrayList<Condition>();
                                for (int i = 0; i < jsonVisibilityConditions.length(); i++) {
                                    visibilityConditions
                                            .add(new Condition(jsonVisibilityConditions.getJSONObject(i)));
                                }
                                newPage.setVisibilityConditions(visibilityConditions);
                            }

                            // look in the JSON for a pageVisibilityRules array is an and or or (default to and)
                            String jsonConditionsType = jsonPage.optString("conditionsType", "and");
                            // set what we got
                            newPage.setConditionsType(jsonConditionsType);

                            // retrieve the html body
                            String htmlBody = jsonPage.optString("htmlBody");
                            // if we got one trim it and retain in page
                            if (htmlBody != null)
                                newPage.setHtmlBody(htmlBody.trim());

                            // look in the JSON for rolehtml
                            JSONArray jsonRolesHtml = jsonPage.optJSONArray("rolesHtml");
                            // if we found some
                            if (jsonRolesHtml != null) {
                                // instantiate the roles html collection
                                ArrayList<Page.RoleHtml> rolesHtml = new ArrayList<Page.RoleHtml>();
                                // loop the entries
                                for (int i = 0; i < jsonRolesHtml.length(); i++) {
                                    // get the entry
                                    JSONObject jsonRoleHtml = jsonRolesHtml.getJSONObject(i);
                                    // retain the html
                                    String html = jsonRoleHtml.optString("html");
                                    // trim it if there is one
                                    if (html != null)
                                        html = html.trim();
                                    // create an array to hold the roles
                                    ArrayList<String> roles = new ArrayList<String>();
                                    // get the roles
                                    JSONArray jsonRoles = jsonRoleHtml.optJSONArray("roles");
                                    // if we got some
                                    if (jsonRoles != null) {
                                        // loop them
                                        for (int j = 0; j < jsonRoles.length(); j++) {
                                            // get the role
                                            String role = jsonRoles.getString(j);
                                            // add it to the roles collections
                                            roles.add(role);
                                        }
                                    }
                                    // create and add a new roleHtml  object
                                    rolesHtml.add(new Page.RoleHtml(roles, html));
                                }
                                // add it to the page
                                newPage.setRolesHtml(rolesHtml);
                            }

                            // fetch a copy of the old page (if there is one)
                            Page oldPage = application.getPages().getPage(getServletContext(), newPage.getId());
                            // if the page's name changed we need to remove it
                            if (oldPage != null) {
                                if (!oldPage.getName().equals(newPage.getName())) {
                                    oldPage.delete(this, rapidRequest, application);
                                }
                            }

                            // save the new page to file
                            newPage.save(this, rapidRequest, application, true);

                            // get any pages collection (we're only sent it if it's been changed)
                            JSONArray jsonPages = jsonPage.optJSONArray("pages");
                            // if we got some
                            if (jsonPages != null) {
                                // make a new map for the page orders
                                Map<String, Integer> pageOrders = new HashMap<String, Integer>();
                                // loop the page orders
                                for (int i = 0; i < jsonPages.length(); i++) {
                                    // add the order to the map
                                    pageOrders.put(jsonPages.getJSONObject(i).getString("id"), i);
                                }
                                // replace the application pageOrders map
                                application.setPageOrders(pageOrders);
                                // save the application and the new orders
                                application.save(this, rapidRequest, true);
                            }
                            boolean jsonPageOrderReset = jsonPage.optBoolean("pageOrderReset");
                            if (jsonPageOrderReset) {
                                // empty the application pageOrders map so everything goes alphabetical
                                application.setPageOrders(null);
                            }

                            // send a positive message
                            output = "{\"message\":\"Saved!\"}";

                            // set the response type to json
                            response.setContentType("application/json");

                        } else if ("testSQL".equals(rapidRequest.getActionName())) {

                            // turn the body bytes into a string
                            String bodyString = new String(bodyBytes, "UTF-8");

                            JSONObject jsonQuery = new JSONObject(bodyString);

                            JSONArray jsonInputs = jsonQuery.optJSONArray("inputs");

                            JSONArray jsonOutputs = jsonQuery.optJSONArray("outputs");

                            Parameters parameters = new Parameters();

                            if (jsonInputs != null) {

                                for (int i = 0; i < jsonInputs.length(); i++)
                                    parameters.addNull();

                            }

                            DatabaseConnection databaseConnection = application.getDatabaseConnections()
                                    .get(jsonQuery.optInt("databaseConnectionIndex", 0));

                            ConnectionAdapter ca = databaseConnection.getConnectionAdapter(getServletContext(),
                                    application);

                            DataFactory df = new DataFactory(ca);

                            int outputs = 0;

                            if (jsonOutputs != null)
                                outputs = jsonOutputs.length();

                            String sql = jsonQuery.getString("SQL");
                            // some jdbc drivers need the line breaks removing before they'll work properly - here's looking at you MS SQL Server!
                            sql = sql.replace("\n", " ");

                            if (outputs == 0) {

                                df.getPreparedStatement(rapidRequest, sql, parameters);

                            } else {

                                ResultSet rs = df.getPreparedResultSet(rapidRequest, sql, parameters);

                                ResultSetMetaData rsmd = rs.getMetaData();

                                int cols = rsmd.getColumnCount();

                                if (outputs > cols)
                                    throw new Exception(outputs + " outputs, but only " + cols + " column"
                                            + (cols > 1 ? "s" : "") + " selected");

                                for (int i = 0; i < outputs; i++) {

                                    JSONObject jsonOutput = jsonOutputs.getJSONObject(i);

                                    String field = jsonOutput.optString("field", "");

                                    if (!"".equals(field)) {

                                        field = field.toLowerCase();

                                        boolean gotOutput = false;

                                        for (int j = 0; j < cols; j++) {

                                            String sqlField = rsmd.getColumnLabel(j + 1).toLowerCase();

                                            if (field.equals(sqlField)) {
                                                gotOutput = true;
                                                break;
                                            }

                                        }

                                        if (!gotOutput) {
                                            rs.close();
                                            df.close();
                                            throw new Exception("Field \"" + field + "\" from output " + (i + 1)
                                                    + " is not present in selected columns");
                                        }

                                    }

                                }

                                // close the recordset
                                rs.close();
                                // close the data factory
                                df.close();

                            }

                            // send a positive message
                            output = "{\"message\":\"OK\"}";

                            // set the response type to json
                            response.setContentType("application/json");

                        } else if ("uploadImage".equals(rapidRequest.getActionName())
                                || "import".equals(rapidRequest.getActionName())) {

                            // get the content type from the request
                            String contentType = request.getContentType();
                            // get the position of the boundary from the content type
                            int boundaryPosition = contentType.indexOf("boundary=");
                            // derive the start of the meaning data by finding the boundary
                            String boundary = contentType.substring(boundaryPosition + 10);
                            // this is the double line break after which the data occurs
                            byte[] pattern = { 0x0D, 0x0A, 0x0D, 0x0A };
                            // find the position of the double line break
                            int dataPosition = Bytes.findPattern(bodyBytes, pattern);
                            // the body header is everything up to the data
                            String header = new String(bodyBytes, 0, dataPosition, "UTF-8");
                            // find the position of the filename in the data header
                            int filenamePosition = header.indexOf("filename=\"");
                            // extract the file name
                            String filename = header.substring(filenamePosition + 10,
                                    header.indexOf("\"", filenamePosition + 10));
                            // find the position of the file type in the data header
                            int fileTypePosition = header.toLowerCase().indexOf("type:");
                            // extract the file type
                            String fileType = header.substring(fileTypePosition + 6);

                            if ("uploadImage".equals(rapidRequest.getActionName())) {

                                // check the file type
                                if (!fileType.equals("image/jpeg") && !fileType.equals("image/gif")
                                        && !fileType.equals("image/png"))
                                    throw new Exception("Unsupported file type");

                                // get the web folder from the application
                                String path = rapidRequest.getApplication().getWebFolder(getServletContext());
                                // create a file output stream to save the data to
                                FileOutputStream fos = new FileOutputStream(path + "/" + filename);
                                // write the file data to the stream
                                fos.write(bodyBytes, dataPosition + pattern.length, bodyBytes.length
                                        - dataPosition - pattern.length - boundary.length() - 9);
                                // close the stream
                                fos.close();

                                // log the file creation
                                getLogger().debug("Saved image file " + path + filename);

                                // create the response with the file name and upload type
                                output = "{\"file\":\"" + filename + "\",\"type\":\""
                                        + rapidRequest.getActionName() + "\"}";

                            } else if ("import".equals(rapidRequest.getActionName())) {

                                // check the file type
                                if (!"application/x-zip-compressed".equals(fileType)
                                        && !"application/zip".equals(fileType))
                                    throw new Exception("Unsupported file type");

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

                                // check we were given one
                                if (appName == null)
                                    throw new Exception("Name must be provided");

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

                                // check we were given one
                                if (appVersion == null)
                                    throw new Exception("Version must be provided");

                                // make the id from the safe and lower case name
                                String appId = Files.safeName(appName).toLowerCase();

                                // make the version from the safe and lower case name
                                appVersion = Files.safeName(appVersion);

                                // get application destination folder
                                File appFolderDest = new File(
                                        Application.getConfigFolder(getServletContext(), appId, appVersion));
                                // get web contents destination folder
                                File webFolderDest = new File(
                                        Application.getWebFolder(getServletContext(), appId, appVersion));

                                // look for an existing application of this name and version
                                Application existingApplication = getApplications().get(appId, appVersion);
                                // if we have an existing application 
                                if (existingApplication != null) {
                                    // back it up first
                                    existingApplication.backup(this, rapidRequest, false);
                                }

                                // get a file for the temp directory
                                File tempDir = new File(getServletContext().getRealPath("/WEB-INF/temp"));
                                // create it if not there
                                if (!tempDir.exists())
                                    tempDir.mkdir();

                                // the path we're saving to is the temp folder
                                String path = getServletContext()
                                        .getRealPath("/WEB-INF/temp/" + appId + ".zip");
                                // create a file output stream to save the data to
                                FileOutputStream fos = new FileOutputStream(path);
                                // write the file data to the stream
                                fos.write(bodyBytes, dataPosition + pattern.length, bodyBytes.length
                                        - dataPosition - pattern.length - boundary.length() - 9);
                                // close the stream
                                fos.close();

                                // log the file creation
                                getLogger().debug("Saved import file " + path);

                                // get a file object for the zip file
                                File zipFile = new File(path);
                                // load it into a zip file object
                                ZipFile zip = new ZipFile(zipFile);
                                // unzip the file
                                zip.unZip();
                                // delete the zip file
                                zipFile.delete();

                                // unzip folder (for deletion)
                                File unZipFolder = new File(
                                        getServletContext().getRealPath("/WEB-INF/temp/" + appId));
                                // get application folders
                                File appFolderSource = new File(
                                        getServletContext().getRealPath("/WEB-INF/temp/" + appId + "/WEB-INF"));
                                // get web content folders
                                File webFolderSource = new File(getServletContext()
                                        .getRealPath("/WEB-INF/temp/" + appId + "/WebContent"));

                                // check we have the right source folders
                                if (webFolderSource.exists() && appFolderSource.exists()) {

                                    // get application.xml file
                                    File appFileSource = new File(appFolderSource + "/application.xml");

                                    if (appFileSource.exists()) {

                                        // delete the appFolder if it exists
                                        if (appFolderDest.exists())
                                            Files.deleteRecurring(appFolderDest);
                                        // delete the webFolder if it exists
                                        if (webFolderDest.exists())
                                            Files.deleteRecurring(webFolderDest);

                                        // copy application content
                                        Files.copyFolder(appFolderSource, appFolderDest);

                                        // copy web content
                                        Files.copyFolder(webFolderSource, webFolderDest);

                                        try {

                                            // load the new application (but don't initialise, nor load pages)
                                            Application appNew = Application.load(getServletContext(),
                                                    new File(appFolderDest + "/application.xml"), false);

                                            // update application name
                                            appNew.setName(appName);

                                            // get the old id
                                            String appOldId = appNew.getId();

                                            // make the new id
                                            appId = Files.safeName(appName).toLowerCase();

                                            // update the id
                                            appNew.setId(appId);

                                            // get the old version
                                            String appOldVersion = appNew.getVersion();

                                            // make the new version
                                            appVersion = Files.safeName(appVersion);

                                            // update the version
                                            appNew.setVersion(appVersion);

                                            // update the created date
                                            appNew.setCreatedDate(new Date());

                                            // set the status to In development
                                            appNew.setStatus(Application.STATUS_DEVELOPMENT);

                                            // a map of actions that might be removed from any of the pages
                                            Map<String, Integer> removedActions = new HashMap<String, Integer>();

                                            // look for page files
                                            File pagesFolder = new File(
                                                    appFolderDest.getAbsolutePath() + "/pages");
                                            // if the folder is there
                                            if (pagesFolder.exists()) {

                                                // create a filter for finding .page.xml files
                                                FilenameFilter xmlFilenameFilter = new FilenameFilter() {
                                                    public boolean accept(File dir, String name) {
                                                        return name.toLowerCase().endsWith(".page.xml");
                                                    }
                                                };

                                                // loop the .page.xml files 
                                                for (File pageFile : pagesFolder.listFiles(xmlFilenameFilter)) {

                                                    BufferedReader reader = new BufferedReader(
                                                            new InputStreamReader(new FileInputStream(pageFile),
                                                                    "UTF-8"));
                                                    String line = null;
                                                    StringBuilder stringBuilder = new StringBuilder();

                                                    while ((line = reader.readLine()) != null) {
                                                        stringBuilder.append(line);
                                                        stringBuilder.append("\n");
                                                    }
                                                    reader.close();

                                                    // retrieve the xml into a string
                                                    String fileString = stringBuilder.toString();

                                                    // prepare a new file string which will update into
                                                    String newFileString = null;

                                                    // if the old app did not have a version (for backwards compatibility)
                                                    if (appOldVersion == null) {

                                                        // replace all properties that appear to have a url, and all created links - note the fix for cleaning up the double encoding
                                                        newFileString = fileString
                                                                .replace("applications/" + appOldId + "/",
                                                                        "applications/" + appId + "/"
                                                                                + appVersion + "/")
                                                                .replace("~?a=" + appOldId + "&amp;",
                                                                        "~?a=" + appId + "&amp;v=" + appVersion
                                                                                + "&amp;")
                                                                .replace("~?a=" + appOldId + "&amp;amp;",
                                                                        "~?a=" + appId + "&amp;v=" + appVersion
                                                                                + "&amp;");

                                                    } else {

                                                        // replace all properties that appear to have a url, and all created links - note the fix for double encoding 
                                                        newFileString = fileString
                                                                .replace(
                                                                        "applications/" + appOldId + "/"
                                                                                + appOldVersion + "/",
                                                                        "applications/" + appId + "/"
                                                                                + appVersion + "/")
                                                                .replace(
                                                                        "~?a=" + appOldId + "&amp;v="
                                                                                + appOldVersion + "&amp;",
                                                                        "~?a=" + appId + "&amp;v=" + appVersion
                                                                                + "&amp;")
                                                                .replace(
                                                                        "~?a=" + appOldId + "&amp;amp;v="
                                                                                + appOldVersion + "&amp;amp;",
                                                                        "~?a=" + appId + "&amp;v=" + appVersion
                                                                                + "&amp;");
                                                    }

                                                    // now open the string into a document
                                                    Document pageDocument = XML.openDocument(newFileString);
                                                    // get an xpath factory
                                                    XPathFactory xPathfactory = XPathFactory.newInstance();
                                                    XPath xpath = xPathfactory.newXPath();
                                                    // an expression for any attributes with a local name of "type"
                                                    XPathExpression expr = xpath
                                                            .compile("//@*[local-name()='type']");
                                                    // get them
                                                    NodeList nl = (NodeList) expr.evaluate(pageDocument,
                                                            XPathConstants.NODESET);
                                                    // get out system actions
                                                    JSONArray jsonActions = getJsonActions();
                                                    // if we found any elements with a type attribute and we have system actions
                                                    if (nl.getLength() > 0 && jsonActions.length() > 0) {
                                                        // a list of action types
                                                        List<String> types = new ArrayList<String>();
                                                        // loop the json actions
                                                        for (int i = 0; i < jsonActions.length(); i++)
                                                            types.add(jsonActions.getJSONObject(i)
                                                                    .optString("type").toLowerCase());
                                                        // loop the action attributes we found
                                                        for (int i = 0; i < nl.getLength(); i++) {
                                                            // get this attribute
                                                            Attr a = (Attr) nl.item(i);
                                                            // get the value of the type 
                                                            String type = a.getTextContent().toLowerCase();
                                                            // get the element the attribute is in
                                                            Node n = a.getOwnerElement();
                                                            // if we don't know about this action type
                                                            if (!types.contains(type)) {
                                                                // get the parent node
                                                                Node p = n.getParentNode();
                                                                // remove this node
                                                                p.removeChild(n);
                                                                // if we have removed this type already
                                                                if (removedActions.containsKey(type)) {
                                                                    // increment the entry for this type
                                                                    removedActions.put(type,
                                                                            removedActions.get(type) + 1);
                                                                } else {
                                                                    // add an entry for this type
                                                                    removedActions.put(type, 1);
                                                                }
                                                            } // got type check                                                                                                                                             
                                                        } // attribute loop

                                                    } // attribute and system action check

                                                    // use the transformer to write to disk
                                                    TransformerFactory transformerFactory = TransformerFactory
                                                            .newInstance();
                                                    Transformer transformer = transformerFactory
                                                            .newTransformer();
                                                    DOMSource source = new DOMSource(pageDocument);
                                                    StreamResult result = new StreamResult(pageFile);
                                                    transformer.transform(source, result);

                                                } // page xml file loop

                                            } // pages folder check

                                            // now initialise with the new id but don't make the resource files (this reloads the pages and sets up the security adapter)
                                            appNew.initialise(getServletContext(), false);

                                            // get the security for this application
                                            SecurityAdapter security = appNew.getSecurityAdapter();

                                            // if we have one
                                            if (security != null) {

                                                // assume we don't have the user
                                                boolean gotUser = false;
                                                // get the current users record from the adapter
                                                User user = security.getUser(rapidRequest);
                                                // check the current user is present in the app's security adapter
                                                if (user != null) {
                                                    // now check the current user password is correct too
                                                    if (security.checkUserPassword(rapidRequest, userName,
                                                            rapidRequest.getUserPassword())) {
                                                        // we have the right user with the right password
                                                        gotUser = true;
                                                    } else {
                                                        // remove this user as the password does not match
                                                        security.deleteUser(rapidRequest);
                                                    }
                                                }

                                                // if we don't have the user
                                                if (!gotUser) {
                                                    // get the current user from the Rapid application
                                                    User rapidUser = rapidSecurity.getUser(rapidRequest);
                                                    // create a new user based on the Rapid user
                                                    user = new User(userName, rapidUser.getDescription(),
                                                            rapidUser.getPassword());
                                                    // add the new user 
                                                    security.addUser(rapidRequest, user);
                                                }

                                                // add Admin and Design roles for the new user if required
                                                if (!security.checkUserRole(rapidRequest,
                                                        com.rapid.server.Rapid.ADMIN_ROLE))
                                                    security.addUserRole(rapidRequest,
                                                            com.rapid.server.Rapid.ADMIN_ROLE);

                                                if (!security.checkUserRole(rapidRequest,
                                                        com.rapid.server.Rapid.DESIGN_ROLE))
                                                    security.addUserRole(rapidRequest,
                                                            com.rapid.server.Rapid.DESIGN_ROLE);
                                            }

                                            // if any items were removed
                                            if (removedActions.keySet().size() > 0) {
                                                // a description of what was removed
                                                String removed = "";
                                                // loop the entries
                                                for (String type : removedActions.keySet()) {
                                                    int count = removedActions.get(type);
                                                    removed += "removed " + count + " " + type + " action"
                                                            + (count == 1 ? "" : "s") + " on import\n";
                                                }
                                                // get the current description
                                                String description = appNew.getDescription();
                                                // if null set to empty string
                                                if (description == null)
                                                    description = "";
                                                // add a line break if need be
                                                if (description.length() > 0)
                                                    description += "\n";
                                                // add the removed
                                                description += removed;
                                                // set it back
                                                appNew.setDescription(description);
                                            }

                                            // reload the pages (actually clears down the pages collection and reloads the headers)
                                            appNew.getPages().loadpages(getServletContext());

                                            // save application (this will also initialise and rebuild the resources)
                                            appNew.save(this, rapidRequest, false);

                                            // add application to the collection
                                            getApplications().put(appNew);

                                            // delete unzip folder
                                            Files.deleteRecurring(unZipFolder);

                                            // send a positive message
                                            output = "{\"id\":\"" + appNew.getId() + "\",\"version\":\""
                                                    + appNew.getVersion() + "\"}";

                                        } catch (Exception ex) {

                                            // delete the appFolder if it exists
                                            if (appFolderDest.exists())
                                                Files.deleteRecurring(appFolderDest);
                                            // if the parent is empty delete it too
                                            if (appFolderDest.getParentFile().list().length <= 1)
                                                Files.deleteRecurring(appFolderDest.getParentFile());

                                            // delete the webFolder if it exists
                                            if (webFolderDest.exists())
                                                Files.deleteRecurring(webFolderDest);
                                            // if the parent is empty delete it too
                                            if (webFolderDest.getParentFile().list().length <= 1)
                                                Files.deleteRecurring(webFolderDest.getParentFile());

                                            // rethrow exception
                                            throw ex;

                                        }

                                    } else {

                                        // delete unzip folder
                                        Files.deleteRecurring(unZipFolder);

                                        // throw excpetion
                                        throw new Exception("Must be a valid Rapid " + Rapid.VERSION + " file");

                                    }

                                } else {

                                    // delete unzip folder
                                    Files.deleteRecurring(unZipFolder);

                                    // throw excpetion
                                    throw new Exception("Must be a valid Rapid file");

                                }

                            }

                        }

                        getLogger().debug("Designer POST response : " + output);

                        PrintWriter out = response.getWriter();
                        out.print(output);
                        out.close();

                    } // got an application

                } // got rapid design role

            } // got rapid security

        } // got rapid application

    } catch (Exception ex) {

        getLogger().error("Designer POST error : ", ex);

        sendException(rapidRequest, response, ex);

    }

}