Example usage for javax.servlet.http HttpServletRequest getCharacterEncoding

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

Introduction

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

Prototype

public String getCharacterEncoding();

Source Link

Document

Returns the name of the character encoding used in the body of this request.

Usage

From source file:net.paoding.rose.web.RequestPath.java

public RequestPath(HttpServletRequest request) {
    // method/*w  w  w. j a  v a2s  .  c  o  m*/
    setMethod(parseMethod(request));

    // ctxpath
    setCtxpath(request.getContextPath());
    String invocationCtxpath = null; // includeinvocationCtxPathincludectxpath
    // dispather, uri, ctxpath
    String uri;
    if (WebUtils.isIncludeRequest(request)) {
        setDispatcher(Dispatcher.INCLUDE);
        uri = (String) request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE);
        invocationCtxpath = ((String) request.getAttribute(WebUtils.INCLUDE_CONTEXT_PATH_ATTRIBUTE));
        setRosePath((String) request.getAttribute(WebUtils.INCLUDE_SERVLET_PATH_ATTRIBUTE));
    } else {
        uri = request.getRequestURI();
        this.setRosePath(request.getServletPath());
        if (request.getAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE) == null) {
            this.setDispatcher(Dispatcher.REQUEST);
        } else {
            this.setDispatcher(Dispatcher.FORWARD);
        }
    }
    if (uri.startsWith("http://") || uri.startsWith("https://")) {
        int start = uri.indexOf('/', 9);
        if (start == -1) {
            uri = "";
        } else {
            uri = uri.substring(start);
        }
    }
    if (uri.indexOf('%') != -1) {
        try {
            String encoding = request.getCharacterEncoding();
            if (encoding == null || encoding.length() == 0) {
                encoding = "UTF-8";
            }
            uri = URLDecoder.decode(uri, encoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    this.setUri(uri);
    // requestPathctxpathincludeinvocationCtxpath

    if (getCtxpath().length() <= 1) {
        setRosePath(getUri());
    } else {
        setRosePath(
                getUri().substring((invocationCtxpath == null ? getCtxpath() : invocationCtxpath).length()));
    }
}

From source file:org.spiffyui.server.AuthServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);

    String auth = null;/*from  w  w  w  .j  ava2  s .  c o  m*/

    /*
     * We are manually reading the request as bytes and
     * then converting it to characters.  This is extra
     * work and we should be able to just call getReader
     * insted of getInputStream.  However, the JBoss
     * implementation of the reader here has a bug that
     * sometiems shows up where the index of the reader
     * is wrong so we can work around it using the input
     * stream directly.
     *
     * https://jira.jboss.org/browse/JBAS-7817
     */

    InputStream in = request.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    int read;
    byte[] buf = new byte[1024];

    try {
        while ((read = in.read(buf)) > 0) {
            out.write(buf, 0, read);
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }
    if (request.getCharacterEncoding() != null) {
        auth = out.toString(request.getCharacterEncoding());
    } else {
        /*
         * There are some cases where the requested character encoding is null.
         * This happens with some application servers and with IE7.  We need to
         * use some encoding in that case so we just use UTF-8.
         */
        auth = out.toString("UTF-8");
    }

    try {
        JSONObject authObj = new JSONObject(auth);
        if (request.getMethod().equals("POST")) {
            doLogin(request, response, authObj.getString(RESTAuthConstants.USERNAME_TOKEN),
                    authObj.getString(RESTAuthConstants.PASSWORD_TOKEN),
                    authObj.getString(RESTAuthConstants.AUTH_URL_TOKEN),
                    authObj.getString(RESTAuthConstants.AUTH_LOGOUT_URL_TOKEN));
            return;
        } else if (request.getMethod().equals("DELETE")) {
            doLogout(request, response, authObj.getString(RESTAuthConstants.USER_TOKEN),
                    authObj.getString(RESTAuthConstants.AUTH_URL_TOKEN));
            return;
        }
    } catch (JSONException e) {
        LOGGER.throwing(AuthServlet.class.getName(), "service", e);
        returnError(response, e.getMessage(), RESTAuthConstants.INVALID_JSON);
    }
}

From source file:org.apache.shindig.protocol.JsonRpcServlet.java

protected String getPostContent(HttpServletRequest request, Map<String, FormDataItem> formItems)
        throws ContentTypes.InvalidContentTypeException, IOException {
    String content = null;/*  www  . j  ava2 s . c  o m*/

    ContentTypes.checkContentTypes(ALLOWED_CONTENT_TYPES, request.getContentType());

    if (formParser.isMultipartContent(request)) {
        for (FormDataItem item : formParser.parse(request)) {
            if (item.isFormField() && REQUEST_PARAM.equals(item.getFieldName()) && content == null) {
                // As per spec, in case of a multipart/form-data content, there will be one form field
                // with field name as "request". It will contain the json request. Any further form
                // field or file item will not be parsed out, but will be exposed via getFormItem
                // method of RequestItem.
                if (!StringUtils.isEmpty(item.getContentType())) {
                    ContentTypes.checkContentTypes(ContentTypes.ALLOWED_JSON_CONTENT_TYPES,
                            item.getContentType());
                }
                content = item.getAsString();
            } else {
                formItems.put(item.getFieldName(), item);
            }
        }
    } else {
        content = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
    }
    return content;
}

From source file:com.jdon.jivejdon.presentation.servlet.upload.ExtendedMultiPartRequestHandler.java

/**
 * Parses the input stream and partitions the parsed items into a set of
 * form fields and a set of file items. In the process, the parsed items are
 * translated from Commons FileUpload <code>FileItem</code> instances to
 * Struts <code>FormFile</code> instances.
 * //www . j  a va2s  . c  o m
 * @param request
 *            The multipart request to be processed.
 * 
 * @throws ServletException
 *             if an unrecoverable error occurs.
 */
public void handleRequest(HttpServletRequest request) throws ServletException {

    // Get the app config for the current request.
    ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY);

    // ----------------------------------------------------------
    // Changed this section of code, that is it.
    // -----------------------------------------------------------
    log.debug("Handling the request..");
    UploadListener listener = new UploadListener(request, 1);
    log.debug("uploading file with optional monitoring..");
    // Create a factory for disk-based file items
    FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
    log.debug("got the factory now get the ServletFileUpload");
    ServletFileUpload upload = new ServletFileUpload(factory);
    log.debug("Should have the ServletFileUpload by now.");
    // The following line is to support an "EncodingFilter"
    // see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=23255
    upload.setHeaderEncoding(request.getCharacterEncoding());
    // Set the maximum size before a FileUploadException will be thrown.
    upload.setSizeMax(getSizeMax(ac));
    // ----------------------------------------------------------------
    // Create the hash tables to be populated.
    elementsText = new Hashtable();
    elementsFile = new Hashtable();
    elementsAll = new Hashtable();

    // Parse the request into file items.
    List items = null;
    try {
        items = upload.parseRequest(request);
    } catch (DiskFileUpload.SizeLimitExceededException e) {
        // Special handling for uploads that are too big.
        request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE);
        return;
    } catch (FileUploadException e) {
        log.error("Failed to parse multipart request", e);
        throw new ServletException(e);
    }

    // Partition the items into form fields and files.
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
            addTextParameter(request, item);
        } else {
            addFileParameter(item);
        }
    }
}

From source file:org.openmrs.module.sync.web.controller.ImportListController.java

@Override
protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response,
        Object obj, BindException errors) throws Exception {

    log.info("***********************************************************\n");
    log.info("Inside SynchronizationImportListController");

    // just fail fast if in the midst of refreshing the context, as this was causing issues, see SYNC-318
    if (Context.isRefreshingContext()) {
        return null;
    }//from   w ww .j  a v a2 s. c o m

    // There are 3 ways to come to this point, so we'll handle all of them:
    // 1) uploading a file (results in a file attachment as response)
    // 2) posting data to page (results in pure XML output)
    // 3) remote connection (with username + password, also posting data) (results in pure XML)
    // none of these result in user-friendly - so no comfy, user-friendly stuff needed here

    //outputing statistics: debug only!
    log.info("HttpServletRequest INFO:");
    log.info("ContentType: " + request.getContentType());
    log.info("CharacterEncoding: " + request.getCharacterEncoding());
    log.info("ContentLength: " + request.getContentLength());
    log.info("checksum: " + request.getParameter("checksum"));
    log.info("syncData: " + request.getParameter("syncData"));
    log.info("syncDataResponse: " + request.getParameter("syncDataResponse"));

    long checksum = 0;
    Integer serverId = 0;
    boolean isResponse = false;
    boolean isUpload = false;
    boolean useCompression = false;

    String contents = "";
    String username = "";
    String password = "";

    //file-based upload, and multi-part form submission
    if (request instanceof MultipartHttpServletRequest) {
        log.info("Processing contents of syncDataFile multipart request parameter");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        serverId = ServletRequestUtils.getIntParameter(multipartRequest, "serverId", 0);
        isResponse = ServletRequestUtils.getBooleanParameter(multipartRequest, "isResponse", false);
        useCompression = ServletRequestUtils.getBooleanParameter(multipartRequest, "compressed", false);
        isUpload = ServletRequestUtils.getBooleanParameter(multipartRequest, "upload", false);
        username = ServletRequestUtils.getStringParameter(multipartRequest, "username", "");
        password = ServletRequestUtils.getStringParameter(multipartRequest, "password", "");

        log.info("Request class: " + request.getClass());
        log.info("serverId: " + serverId);
        log.info("upload = " + isUpload);
        log.info("compressed = " + useCompression);
        log.info("response = " + isResponse);
        log.info("username = " + username);

        log.info("Request content length: " + request.getContentLength());
        MultipartFile multipartFile = multipartRequest.getFile("syncDataFile");
        if (multipartFile != null && !multipartFile.isEmpty()) {
            InputStream inputStream = null;
            try {
                // Decompress content in file
                ConnectionResponse syncResponse = new ConnectionResponse(
                        new ByteArrayInputStream(multipartFile.getBytes()), useCompression);

                log.info("Content to decompress: " + multipartFile.getBytes());
                log.info("Content received: " + syncResponse.getResponsePayload());
                log.info("Decompression Checksum: " + syncResponse.getChecksum());

                contents = syncResponse.getResponsePayload();
                checksum = syncResponse.getChecksum();

                log.info("Final content: " + contents);

            } catch (Exception e) {
                log.warn("Unable to read in sync data file", e);
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
        }
    } else {
        log.debug("seems we DO NOT have a file object");
    }

    // prepare to process the input: contents now contains decompressed request ready to be processed
    SyncTransmissionResponse str = new SyncTransmissionResponse();
    str.setErrorMessage(SyncConstants.ERROR_TX_NOT_UNDERSTOOD);
    str.setFileName(SyncConstants.FILENAME_TX_NOT_UNDERSTOOD);
    str.setUuid(SyncConstants.UUID_UNKNOWN);
    str.setSyncSourceUuid(SyncConstants.UUID_UNKNOWN);
    str.setSyncTargetUuid(SyncConstants.UUID_UNKNOWN);
    str.setState(SyncTransmissionState.TRANSMISSION_NOT_UNDERSTOOD);
    str.setTimestamp(new Date()); //set the timestamp of the response

    if (log.isInfoEnabled()) {
        log.info("CONTENT IN IMPORT CONTROLLER: " + contents);
    }

    //if no content, nothing to process just send back response
    if (contents == null || contents.length() < 0) {
        log.info("returning from ingest: nothing to process.");
        this.sendResponse(str, isUpload, response);
        return null;
    }

    // if this is option 3 (posting from remote server), we need to authenticate
    if (!Context.isAuthenticated()) {
        try {
            Context.authenticate(username, password);
        } catch (Exception e) {
        }
    }
    // Could not authenticate user: send back error
    if (!Context.isAuthenticated()) {
        str.setErrorMessage(SyncConstants.ERROR_AUTH_FAILED);
        str.setFileName(SyncConstants.FILENAME_AUTH_FAILED);
        str.setState(SyncTransmissionState.AUTH_FAILED);

        this.sendResponse(str, isUpload, response);
        return null;
    }

    //Fill-in the server uuid for the response: since request was authenticated we can start letting callers
    //know about us
    str.setSyncTargetUuid(Context.getService(SyncService.class).getServerUuid());

    //Checksum check before doing anything at all: on unreliable networks we can get seemingly
    //valid HTTP POST but content is messed up, defend against it with custom checksums
    long checksumReceived = ServletRequestUtils.getLongParameter(request, "checksum", -1);
    log.info("checksum value received in POST: " + checksumReceived);
    log.info("checksum value of payload: " + checksum);
    log.info("SIZE of payload: " + contents.length());
    if (checksumReceived > 0 && (checksumReceived != checksum)) {
        log.error("ERROR: FAILED CHECKSUM!");
        str.setState(SyncTransmissionState.TRANSMISSION_NOT_UNDERSTOOD);

        this.sendResponse(str, isUpload, response);
        return null;
    }

    //Test message. Test message was sent (i.e. using 'test connection' button on server screen)
    //just send empty acknowledgment
    if (SyncConstants.TEST_MESSAGE.equals(contents)) {
        str.setErrorMessage("");
        str.setState(SyncTransmissionState.OK);
        str.setUuid("");
        str.setFileName(SyncConstants.FILENAME_TEST);

        this.sendResponse(str, isUpload, response);
        return null;
    }

    if (SyncConstants.CLONE_MESSAGE.equals(contents)) {
        try {
            log.info("CLONE MESSAGE RECEIVED, TRYING TO CLONE THE DB");
            File file = Context.getService(SyncService.class).generateDataFile();
            StringWriter writer = new StringWriter();
            IOUtils.copy(new FileInputStream(file), writer);
            this.sendCloneResponse(writer.toString(), response, false);

            boolean clonedDBLog = Boolean.parseBoolean(Context.getAdministrationService()
                    .getGlobalProperty(SyncConstants.PROPERTY_SYNC_CLONED_DATABASE_LOG_ENABLED, "true"));

            if (!clonedDBLog) {
                file.delete();
            }
        } catch (Exception ex) {
            log.warn(ex.toString());
            ex.printStackTrace();
        }
        return null;
    }

    /*************************************************************************************************************************
     * This is a real transmission: - user was properly authenticated - checksums match - it is
     * not a test transmission Start processing! 1. Deserialize what was sent; it can be either
     * SyncTransmssion, or SyncTransmissionResponse 2. If it is a response,
     *************************************************************************************************************************/
    SyncTransmission st = null;

    if (!isResponse) {
        //this is not 'response' to something we sent out; thus the contents should contain plan SyncTransmission 
        try {
            log.info("xml to sync transmission with contents: " + contents);
            st = SyncDeserializer.xmlToSyncTransmission(contents);
        } catch (Exception e) {
            log.error("Unable to deserialize the following: " + contents, e);
            str.setErrorMessage("Unable to deserialize transmission contents into SyncTansmission.");
            str.setState(SyncTransmissionState.TRANSMISSION_NOT_UNDERSTOOD);
            this.sendResponse(str, isUpload, response);
            return null;
        }
    } else {
        log.info("Processing a response, not a transmission");
        SyncTransmissionResponse priorResponse = null;

        try {
            // this is the confirmation of receipt of previous transmission
            priorResponse = SyncDeserializer.xmlToSyncTransmissionResponse(contents);
            log.info("This is a response from a previous transmission.  Uuid is: " + priorResponse.getUuid());
        } catch (Exception e) {
            log.error("Unable to deserialize the following: " + contents, e);
            str.setErrorMessage("Unable to deserialize transmission contents into SyncTransmissionResponse.");
            str.setState(SyncTransmissionState.TRANSMISSION_NOT_UNDERSTOOD);
            this.sendResponse(str, isUpload, response);
            return null;
        }

        // figure out where this came from:
        // for responses, the target ID contains the server that generated the response
        String sourceUuid = priorResponse.getSyncTargetUuid();
        log.info("SyncTransmissionResponse has a sourceUuid of " + sourceUuid);
        RemoteServer origin = Context.getService(SyncService.class).getRemoteServer(sourceUuid);
        if (origin == null) {
            log.error("Source server not registered locally. Unable to find source server by uuid: "
                    + sourceUuid);
            str.setErrorMessage(
                    "Source server not registered locally. Unable to find source server by uuid " + sourceUuid);
            str.setState(SyncTransmissionState.INVALID_SERVER);
            this.sendResponse(str, isUpload, response);
            return null;
        } else {
            log.info("Found source server by uuid: " + sourceUuid + " = " + origin.getNickname());
            log.info("Source server is " + origin.getNickname());
        }

        if (priorResponse == null) {
        }

        // process response that was sent to us; the sync response normally contains:
        //a) results of the records that we sent out
        //b) new records from 'source' to be applied against this server
        if (priorResponse.getSyncImportRecords() == null) {
            log.debug("No records to process in response");
        } else {
            // now process each incoming syncImportRecord, this is just status update
            for (SyncImportRecord importRecord : priorResponse.getSyncImportRecords()) {
                Context.getService(SyncIngestService.class).processSyncImportRecord(importRecord, origin);
            }
        }

        // now pull out the data that originated on the 'source' server and try to process it
        st = priorResponse.getSyncTransmission();

    }

    // now process the syncTransmission if one was received                    
    if (st != null) {
        str = SyncUtilTransmission.processSyncTransmission(st,
                SyncUtil.getGlobalPropetyValueAsInteger(SyncConstants.PROPERTY_NAME_MAX_RECORDS_WEB));
    } else
        log.info("st was null");

    //send response
    this.sendResponse(str, isUpload, response);

    // never a situation where we want to actually use the model/view - either file download or http request
    return null;
}

From source file:org.deegree.enterprise.servlet.SimpleProxyServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *///w  ww . jav  a  2 s  .  c  o  m
@Override
protected void doPost(HttpServletRequest origReq, HttpServletResponse response)
        throws ServletException, IOException {
    // wrap request to enable access of the requests InputStream more
    // than one time
    ServletRequestWrapper request = new ServletRequestWrapper(origReq);
    OutputStream os = null;
    try {
        if (LOG.getLevel() == ILogger.LOG_DEBUG) {
            // because this is an expensive operation it just will
            // performed if debug level is set too DEBUG
            InputStream reqIs = request.getInputStream();
            StringBuffer sb = new StringBuffer(10000);
            int c = 0;
            while ((c = reqIs.read()) > -1) {
                sb.append((char) c);
            }
            reqIs.close();
            LOG.logDebug("Request: " + sb);
        }
        OGCWebServiceRequest req = OGCRequestFactory.create(request);

        String hostAddr = host.get(req.getServiceName());
        LOG.logDebug("forward URL: " + hostAddr);
        if (hostAddr == null) {
            throw new Exception(Messages.getMessage("PROXY_SERVLET_UNDEFINED_HOST", req.getServiceName()));
        }

        // determine charset for setting request content type
        // use system charset if no charset can be determined
        // from incoming request
        String charset = origReq.getCharacterEncoding();
        LOG.logDebug("request character encoding: ", charset);
        if (charset == null) {
            charset = CharsetUtils.getSystemCharset();
            LOG.logDebug("use sytem character encoding: ", charset);
        }

        HttpClient client = new HttpClient();
        client = WebUtils.enableProxyUsage(client, new URL(hostAddr));
        PostMethod post = new PostMethod(hostAddr);
        post.setRequestHeader("Content-type", "text/xml; charset=" + charset);
        post.setRequestEntity(new InputStreamRequestEntity(request.getInputStream()));
        client.executeMethod(post);

        LOG.logDebug("Content-type: ", post.getResponseHeader("Content-type"));

        os = response.getOutputStream();
        os.write(post.getResponseBody());
    } catch (Exception e) {
        e.printStackTrace();
        response.setContentType("text/plain; charset=" + CharsetUtils.getSystemCharset());
        os.write(StringTools.stackTraceToString(e).getBytes());
    } finally {
        try {
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.basinmc.irc.bridge.github.GitHubServerHandler.java

/**
 * {@inheritDoc}//  w  w  w.  j  ava2 s  . c  om
 */
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    // only handle requests to /
    if (!target.equals("/webhook")) {
        return;
    }

    // verify whether the call comes directly from GitHub using the X-GitHub-Event,
    // X-Hub-Signature and X-GitHub-Delivery headers
    String eventType = request.getHeader("X-GitHub-Event");
    String signature = request.getHeader("X-Hub-Signature");
    String deliveryId = request.getHeader("X-GitHub-Delivery");

    if (eventType == null || eventType.isEmpty()
            || (this.secret != null && (signature == null || signature.isEmpty())) || deliveryId == null
            || deliveryId.isEmpty()) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        baseRequest.setHandled(true);
        return;
    }

    if (signature != null) {
        // strip sha1=
        // TODO: Decide upon signature method based on this parameter
        signature = signature.substring(5);
    }

    logger.info("Processing GitHub request " + deliveryId + ".");

    // decode the data passed in the request body
    String data;
    try (InputStream inputStream = request.getInputStream()) {
        data = new String(ByteStreams.toByteArray(inputStream),
                Charset.forName(request.getCharacterEncoding()));
    }

    // verify the signature supplied to us (as long as a secret key was configured)
    try {
        if (!verifySignature(data, signature)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            baseRequest.setHandled(true);
            return;
        }
    } catch (IllegalStateException ex) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        baseRequest.setHandled(true);
        return;
    }

    // find correct event message
    eventType = eventType.replace('_', '.');

    // de-serialize and handle event data
    Map<String, Object> context = new HashMap<>();
    context.put("color", COLOR_MAP);
    context.put("event", reader.readValue(data));

    String message = this.getMessage(eventType, context);

    if (message != null) {
        this.bridge.sendMessage(message);
    }

    // answer with 204 at all times
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    baseRequest.setHandled(true);
}

From source file:com.orange.mmp.api.ws.jsonrpc.MMPJsonRpcServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

    ExecutionContext executionContext = ExecutionContext.newInstance(request);
    executionContext.setName("JSON-RCP Request");

    executionContext.executionStart();//  ww  w .j  av  a 2 s . c om
    String requestInfo = "";
    try {

        // Use protected method in case someone wants to override it
        JSONRPCBridge json_bridge = findBridge(request);

        // Encode using UTF-8, although We are actually ASCII clean as
        // all unicode data is JSON escaped using backslash u. This is
        // less data efficient for foreign character sets but it is
        // needed to support naughty browsers such as Konqueror and Safari
        // which do not honour the charset set in the response
        response.setContentType("application/json");
        response.setCharacterEncoding(Constants.DEFAULT_ENCODING);
        OutputStream out = response.getOutputStream();

        // Decode using the charset in the request if it exists otherwise
        // use UTF-8 as this is what all browser implementations use.
        // The JSON-RPC-Java JavaScript client is ASCII clean so it
        // although here we can correctly handle data from other clients
        // that do not escape non ASCII data
        String charset = request.getCharacterEncoding();
        if (charset == null) {
            charset = Constants.DEFAULT_ENCODING;
        }

        String receiveString = null;

        // Test HTTP GET
        if (request.getQueryString() != null) {
            String id = request.getParameter(HTTP_PARAM_ID);
            if (id != null) {
                executionContext.setApiName(id);

                StringBuilder receiveStringBuilder = new StringBuilder("{\"id\":").append(id)
                        .append(",\"method\":\"");
                String method = request.getParameter(HTTP_PARAM_METHOD);
                // Get params
                if (method != null) {
                    executionContext.setMethodName(method);

                    receiveStringBuilder.append(method);
                    String param = request.getParameter(HTTP_PARAM_PARAM);
                    // There is parameters
                    if (param != null) {
                        receiveStringBuilder.append("\",\"params\":").append(param).append("}");
                    }
                    // Empty params
                    else {
                        receiveStringBuilder.append("\",\"params\":[]}");
                    }
                }
                // Default method (list API)
                else {
                    receiveStringBuilder.append("system.listMethods\",\"params\":[]}");
                }

                // Set JSON-RPC call string
                receiveString = receiveStringBuilder.toString();

                //Trace request
                executionContext.setName("JSON-RCP Request: " + receiveString);
            }
        }

        // Test HTTP POST
        if (receiveString == null) {
            BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), charset));

            // Read the request
            CharArrayWriter data = new CharArrayWriter();
            char buf[] = new char[4096];
            int ret;
            while ((ret = in.read(buf, 0, 4096)) != -1) {
                data.write(buf, 0, ret);
            }

            receiveString = data.toString();
            requestInfo = receiveString;
        }

        // Process the request
        JSONObject json_req;
        JSONRPCResult json_res;
        try {
            json_req = new JSONObject(receiveString);
            json_res = json_bridge.call(new Object[] { request, response }, json_req);
        } catch (JSONException e) {
            json_res = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, JSONRPCResult.MSG_ERR_PARSE);
        }

        String sendString = json_res.toString();

        // Write the response
        byte[] bout = sendString.getBytes(Constants.DEFAULT_ENCODING);

        // if the request header says that the browser can take gzip compressed
        // output, then gzip the output
        // but only if the response is large enough to warrant it and if the
        // resultant compressed output is
        // actually smaller.
        String ae = request.getHeader("accept-encoding");
        if (ae != null && ae.indexOf("gzip") != -1) {
            byte[] gzippedOut = gzip(bout);

            // if gzip didn't actually help, abort
            if (bout.length > gzippedOut.length) {
                bout = gzippedOut;
                response.addHeader("Content-Encoding", "gzip");
            }
        }

        response.setIntHeader("Content-Length", bout.length);

        out.write(bout);

    } catch (Throwable error) {
        //Catch exception
        throw new IOExceptionWithCause("Error during request processing", error);
    } finally {
        executionContext.executionStop();
        printMonitoredRequest(requestInfo);
        executionContext.close();
    }
}

From source file:org.infoscoop.gadgets.servlet.JsonRpcServlet.java

protected String getPostContent(HttpServletRequest request, Map<String, FormDataItem> formItems)
        throws ContentTypes.InvalidContentTypeException, IOException {
    String content = null;// w ww .  j  av a  2  s  . c  om

    ContentTypes.checkContentTypes(ALLOWED_CONTENT_TYPES, request.getContentType());

    if (formParser.isMultipartContent(request)) {
        for (FormDataItem item : formParser.parse(request)) {
            if (item.isFormField() && REQUEST_PARAM.equals(item.getFieldName()) && content == null) {
                // As per spec, in case of a multipart/form-data content, there will be one form field
                // with field name as "request". It will contain the json request. Any further form
                // field or file item will not be parsed out, but will be exposed via getFormItem
                // method of RequestItem.
                if (!Strings.isNullOrEmpty(item.getContentType())) {
                    ContentTypes.checkContentTypes(ContentTypes.ALLOWED_JSON_CONTENT_TYPES,
                            item.getContentType());
                }
                content = item.getAsString();
            } else {
                formItems.put(item.getFieldName(), item);
            }
        }
    } else {
        content = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
    }
    return content;
}

From source file:org.exist.http.SOAPServer.java

/**
 * HTTP GET/*from   w w w  .ja va  2 s.  c o m*/
 * Processes requests for description documents - WSDL, Human Readable and Human Readable for a specific function
 * 
 * TODO: I think simple webservices can also be called using GET, so we may need to cater for that as well
 * but first it would be best to write the doPost() method, split the code out into functions and also use it for this.
 */
public void doGet(DBBroker broker, HttpServletRequest request, HttpServletResponse response, String path)
        throws BadRequestException, PermissionDeniedException, NotFoundException, IOException {
    //set the encoding
    if (request.getCharacterEncoding() == null) {
        request.setCharacterEncoding(formEncoding);
    }

    /* Process the request */
    try {
        //Get a Description of the XQWS
        final XQWSDescription description = getXQWSDescription(broker, path, request);

        //Get the approriate description for the user
        byte[] result = null;
        if (request.getParameter("WSDL") != null || request.getParameter("wsdl") != null) {
            //WSDL document literal
            result = description.getWSDL();

            //set output content type for wsdl
            response.setContentType(MimeType.XML_TYPE.getName());
        } else if (request.getParameter("WSDLRPC") != null || request.getParameter("wsdlrpc") != null) {
            //WSDL RPC
            result = description.getWSDL(false);

            //set output content type for wsdl
            response.setContentType(MimeType.XML_TYPE.getName());
        } else if (request.getParameter("function") != null) {
            //Specific Function Description
            result = description.getFunctionDescription(request.getParameter("function"));
        } else {
            //Human Readable Description
            result = description.getHumanDescription();
        }

        //send the description to the http servlet response
        final ServletOutputStream os = response.getOutputStream();
        final BufferedOutputStream bos = new BufferedOutputStream(os);
        bos.write(result);
        bos.close();
        os.close();
    } catch (final XPathException xpe) {
        LOG.debug(xpe.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        writeResponse(response, formatXPathException(null, path, xpe), "text/html", ENCODING);
    } catch (final SAXException saxe) {
        LOG.debug(saxe.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        writeResponse(response,
                formatXPathException(null, path, new XPathException(
                        "SAX exception while transforming node: " + saxe.getMessage(), saxe)),
                "text/html", ENCODING);
    } catch (final TransformerConfigurationException tce) {
        LOG.debug(tce.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        writeResponse(response,
                formatXPathException(null, path,
                        new XPathException("SAX exception while transforming node: " + tce.getMessage(), tce)),
                "text/html", ENCODING);
    }
}