Example usage for javax.servlet.http HttpServletRequest getReader

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

Introduction

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

Prototype

public BufferedReader getReader() throws IOException;

Source Link

Document

Retrieves the body of the request as character data using a BufferedReader.

Usage

From source file:org.apache.syncope.client.enduser.resources.UserSelfUpdateResource.java

@Override
protected ResourceResponse newResourceResponse(final IResource.Attributes attributes) {
    ResourceResponse response = new AbstractResource.ResourceResponse();
    response.setContentType(MediaType.TEXT_PLAIN);
    try {/*from  w w w. j av a  2s.c  o  m*/
        HttpServletRequest request = (HttpServletRequest) attributes.getRequest().getContainerRequest();
        if (!xsrfCheck(request)) {
            LOG.error("XSRF TOKEN does not match");
            response.setError(Response.Status.BAD_REQUEST.getStatusCode(), "XSRF TOKEN does not match");
            return response;
        }

        if (!captchaCheck(request.getHeader("captcha"),
                request.getSession().getAttribute(SyncopeEnduserConstants.CAPTCHA_SESSION_KEY))) {

            throw new IllegalArgumentException("Entered captcha is not matching");
        }

        UserTO userTO = MAPPER.readValue(request.getReader().readLine(), UserTO.class);
        Map<String, CustomAttributesInfo> customForm = SyncopeEnduserApplication.get().getCustomForm();

        // check if request is compliant with customization form rules
        if (UserRequestValidator.compliant(userTO, customForm, false)) {
            // 1. membership attributes management
            Set<AttrTO> membAttrs = new HashSet<>();
            userTO.getPlainAttrs().stream().filter(
                    attr -> (attr.getSchema().contains(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR)))
                    .forEachOrdered((attr) -> {
                        String[] simpleAttrs = attr.getSchema()
                                .split(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR);
                        MembershipTO membership = userTO.getMemberships().stream()
                                .filter(item -> simpleAttrs[0].equals(item.getGroupName())).findFirst()
                                .orElse(null);
                        if (membership == null) {
                            membership = new MembershipTO.Builder().group(null, simpleAttrs[0]).build();
                            userTO.getMemberships().add(membership);
                        }
                        AttrTO clone = SerializationUtils.clone(attr);
                        clone.setSchema(simpleAttrs[1]);
                        membership.getPlainAttrs().add(clone);
                        membAttrs.add(attr);
                    });
            userTO.getPlainAttrs().removeAll(membAttrs);

            // 2. millis -> Date conversion for PLAIN attributes of USER and its MEMBERSHIPS
            SyncopeEnduserSession.get().getDatePlainSchemas().stream().map(plainSchema -> {
                millisToDate(userTO.getPlainAttrs(), plainSchema);
                return plainSchema;
            }).forEachOrdered(plainSchema -> {
                userTO.getMemberships().forEach(membership -> {
                    millisToDate(membership.getPlainAttrs(), plainSchema);
                });
            });

            membAttrs.clear();
            userTO.getDerAttrs().stream().filter(
                    attr -> (attr.getSchema().contains(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR)))
                    .forEachOrdered(attr -> {
                        String[] simpleAttrs = attr.getSchema()
                                .split(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR);
                        MembershipTO membership = userTO.getMemberships().stream()
                                .filter(item -> simpleAttrs[0].equals(item.getGroupName())).findFirst()
                                .orElse(null);
                        if (membership == null) {
                            membership = new MembershipTO.Builder().group(null, simpleAttrs[0]).build();
                            userTO.getMemberships().add(membership);
                        }
                        AttrTO clone = SerializationUtils.clone(attr);
                        clone.setSchema(simpleAttrs[1]);
                        membership.getDerAttrs().add(clone);
                        membAttrs.add(attr);
                    });
            userTO.getDerAttrs().removeAll(membAttrs);

            membAttrs.clear();
            userTO.getVirAttrs().stream().filter(
                    attr -> (attr.getSchema().contains(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR)))
                    .forEachOrdered((attr) -> {
                        String[] simpleAttrs = attr.getSchema()
                                .split(SyncopeEnduserConstants.MEMBERSHIP_ATTR_SEPARATOR);
                        MembershipTO membership = userTO.getMemberships().stream()
                                .filter(item -> simpleAttrs[0].equals(item.getGroupName())).findFirst()
                                .orElse(null);
                        if (membership == null) {
                            membership = new MembershipTO.Builder().group(null, simpleAttrs[0]).build();
                            userTO.getMemberships().add(membership);

                        }
                        AttrTO clone = SerializationUtils.clone(attr);
                        clone.setSchema(simpleAttrs[1]);
                        membership.getVirAttrs().add(clone);
                        membAttrs.add(attr);
                    });
            userTO.getVirAttrs().removeAll(membAttrs);

            // get old user object from session
            UserTO selfTO = SyncopeEnduserSession.get().getSelfTO();
            // align "userTO" and "selfTO" objects
            if (customForm != null && !customForm.isEmpty()) {
                completeUserObject(userTO, selfTO);
            }
            // create diff patch
            UserPatch userPatch = AnyOperations.diff(userTO, selfTO, false);
            // update user by patch
            Response res = SyncopeEnduserSession.get().getService(userTO.getETagValue(), UserSelfService.class)
                    .update(userPatch);

            buildResponse(response, res.getStatus(),
                    res.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)
                            ? "User [" + userTO.getUsername() + "] successfully updated"
                            : "ErrorMessage{{ " + res.getStatusInfo().getReasonPhrase() + " }}");
        } else {
            LOG.warn("Incoming update request [{}] is not compliant with form customization rules."
                    + " Update NOT allowed", userTO.getUsername());
            buildResponse(response, Response.Status.OK.getStatusCode(),
                    "User: " + userTO.getUsername() + " successfully created");
        }
    } catch (final Exception e) {
        LOG.error("Error while updating user", e);
        response.setError(Response.Status.BAD_REQUEST.getStatusCode(),
                new StringBuilder().append("ErrorMessage{{ ").append(e.getMessage()).append(" }}").toString());
    }
    return response;
}

From source file:com.googlecode.noweco.calendar.CaldavServlet.java

public void doReport(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    Unmarshaller unMarshaller = createUnmarshaller();
    Marshaller marshaller = createMarshaller();
    Object xmlRequest = null;/*from w w w .  j av  a  2s  . c  o  m*/
    try {
        xmlRequest = unMarshaller.unmarshal(req.getReader());
    } catch (JAXBException e) {
        throw new CalendarException("Unable to parse request", e);
    }
    if (LOGGER.isTraceEnabled()) {
        try {
            StringWriter writer = new StringWriter();
            marshaller.marshal(xmlRequest, writer);
            LOGGER.trace("receive :\n{}", writer.toString());
        } catch (JAXBException e) {
            // ignore
        }
    }

    Multistatus multistatus = new Multistatus();

    if (xmlRequest instanceof CalendarMultiget) {
        CalendarMultiget calendarMultiget = (CalendarMultiget) xmlRequest;
        Prop reqProp = calendarMultiget.getProp();

        int status = propFind(multistatus, reqProp, req.getHeader("Depth"), calendarMultiget.getHref());
        if (status != HttpServletResponse.SC_OK) {
            resp.sendError(status);
            return;
        }
    } else if (xmlRequest instanceof SyncCollection) {
        SyncCollection syncCollection = (SyncCollection) xmlRequest;
        Prop reqProp = syncCollection.getProp();
        String requestURI = req.getRequestURI();
        MemoryFile locate = MemoryFileUtils.locate(ROOT, requestURI);
        for (MemoryFile memoryFile : locate.getChildren()) {
            int status = propFind(multistatus, reqProp, "0", memoryFile.getURI());
            if (status != HttpServletResponse.SC_OK) {
                resp.sendError(status);
                return;
            }
        }
        SyncToken syncToken = new SyncToken();
        syncToken.getContent().add("<string mal formee>");
        multistatus.setSyncToken(syncToken);
    } else if (xmlRequest instanceof PrincipalSearchPropertySet) {
        // PrincipalSearchPropertySet principalSearchPropertySet = (PrincipalSearchPropertySet) xmlRequest;
        resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
        return;
    } else {
        LOGGER.error("doReport not supported request " + xmlRequest.getClass());
        resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
        return;
    }

    resp.setStatus(SC_MULTI_STATUS);
    resp.setContentType("text/xml;charset=\"UTF-8\"");
    PrintWriter httpWriter = resp.getWriter();
    try {
        Writer writer;
        if (LOGGER.isTraceEnabled()) {
            writer = new StringWriter();
        } else {
            writer = httpWriter;
        }
        marshaller.marshal(multistatus, writer);
        if (LOGGER.isTraceEnabled()) {
            String string = writer.toString();
            LOGGER.trace("send :\n{}", string);
            httpWriter.write(string);
        }
    } catch (JAXBException e) {
        throw new CalendarException("Unable to format response", e);
    }
    httpWriter.close();
}

From source file:it.eng.spagobi.profiling.services.ManageAttributesAction.java

@Override
public void doService() {
    logger.debug("IN");
    ISbiAttributeDAO attrDao;/*from  www .  j  ava2  s.co m*/
    UserProfile profile = (UserProfile) this.getUserProfile();
    try {
        attrDao = DAOFactory.getSbiAttributeDAO();
        attrDao.setUserProfile(getUserProfile());
    } catch (EMFUserError e1) {
        logger.error(e1.getMessage(), e1);
        throw new SpagoBIServiceException(SERVICE_NAME, "Error occurred");
    }
    HttpServletRequest httpRequest = getHttpRequest();

    Locale locale = getLocale();

    String serviceType = this.getAttributeAsString(MESSAGE_DET);
    logger.debug("Service type " + serviceType);

    if (serviceType != null && serviceType.contains(ATTR_LIST)) {
        String name = null;
        String description = null;
        String idStr = null;

        try {
            BufferedReader b = httpRequest.getReader();
            if (b != null) {
                String respJsonObject = b.readLine();
                if (respJsonObject != null) {
                    JSONObject responseJSON = deserialize(respJsonObject);
                    JSONObject samples = responseJSON.getJSONObject(SAMPLES);
                    if (!samples.isNull(ID)) {
                        idStr = samples.getString(ID);
                    }

                    //checks if it is empty attribute to start insert
                    boolean isNewAttr = this.getAttributeAsBoolean(IS_NEW_ATTR);

                    if (!isNewAttr) {
                        if (!samples.isNull(NAME)) {

                            name = samples.getString(NAME);
                            HashMap<String, String> logParam = new HashMap();
                            logParam.put("NAME", name);
                            if (GenericValidator.isBlankOrNull(name)
                                    || !GenericValidator.matchRegexp(name, ALPHANUMERIC_STRING_REGEXP_NOSPACE)
                                    || !GenericValidator.maxLength(name, nameMaxLenght)) {
                                logger.error(
                                        "Either the field name is blank or it exceeds maxlength or it is not alfanumeric");
                                EMFValidationError e = new EMFValidationError(EMFErrorSeverity.ERROR,
                                        description, "9000", "");
                                getHttpResponse().setStatus(404);
                                JSONObject attributesResponseSuccessJSON = new JSONObject();
                                attributesResponseSuccessJSON.put("success", false);
                                attributesResponseSuccessJSON.put("message",
                                        "Either the field name is blank or it exceeds maxlength or it is not alfanumeric");
                                attributesResponseSuccessJSON.put("data", "[]");

                                writeBackToClient(new JSONSuccess(attributesResponseSuccessJSON));

                                AuditLogUtilities.updateAudit(getHttpRequest(), profile, "PROF_ATTRIBUTES.ADD",
                                        logParam, "OK");
                                return;

                            }
                        }
                        if (!samples.isNull(DESCRIPTION)) {
                            description = samples.getString(DESCRIPTION);

                            if (GenericValidator.isBlankOrNull(description)
                                    || !GenericValidator.matchRegexp(description,
                                            ALPHANUMERIC_STRING_REGEXP_NOSPACE)
                                    || !GenericValidator.maxLength(description, descriptionMaxLenght)) {
                                logger.error(
                                        "Either the field description is blank or it exceeds maxlength or it is not alfanumeric");

                                EMFValidationError e = new EMFValidationError(EMFErrorSeverity.ERROR,
                                        description, "9000", "");
                                getHttpResponse().setStatus(404);
                                JSONObject attributesResponseSuccessJSON = new JSONObject();
                                attributesResponseSuccessJSON.put("success", false);
                                attributesResponseSuccessJSON.put("message",
                                        "Either the field description is blank or it exceeds maxlength or it is not alfanumeric");
                                attributesResponseSuccessJSON.put("data", "[]");
                                writeBackToClient(new JSONSuccess(attributesResponseSuccessJSON));
                                HashMap<String, String> logParam = new HashMap();
                                logParam.put("NAME", name);
                                AuditLogUtilities.updateAudit(getHttpRequest(), profile, "PROF_ATTRIBUTES.ADD",
                                        logParam, "OK");
                                return;
                            }
                        }

                        SbiAttribute attribute = new SbiAttribute();
                        if (description != null) {
                            attribute.setDescription(description);
                        }
                        if (name != null) {
                            attribute.setAttributeName(name);
                        }
                        boolean isNewAttrForRes = true;
                        if (idStr != null && !idStr.equals("")) {
                            Integer attributeId = new Integer(idStr);
                            attribute.setAttributeId(attributeId.intValue());
                            isNewAttrForRes = false;
                        }
                        Integer attrID = attrDao.saveOrUpdateSbiAttribute(attribute);
                        logger.debug("Attribute updated");

                        ArrayList<SbiAttribute> attributes = new ArrayList<SbiAttribute>();
                        attribute.setAttributeId(attrID);
                        attributes.add(attribute);

                        getAttributesListAdded(locale, attributes, isNewAttrForRes, attrID);
                        HashMap<String, String> logParam = new HashMap();
                        logParam.put("NAME", attribute.getAttributeName());
                        AuditLogUtilities.updateAudit(getHttpRequest(), profile,
                                "PROF_ATTRIBUTES." + ((isNewAttrForRes) ? "ADD" : "MODIFY"), logParam, "OK");
                    }

                    //else the List of attributes will be sent to the client
                } else {
                    getAttributesList(locale, attrDao);
                }
            } else {
                getAttributesList(locale, attrDao);
            }

        } catch (Throwable e) {
            try {
                AuditLogUtilities.updateAudit(getHttpRequest(), profile, "PROF_ATTRIBUTES.ADD", null, "OK");
            } catch (Exception e3) {
                // TODO Auto-generated catch block
                e3.printStackTrace();
            }
            logger.error(e.getMessage(), e);
            getHttpResponse().setStatus(404);
            try {
                JSONObject attributesResponseSuccessJSON = new JSONObject();
                attributesResponseSuccessJSON.put("success", true);
                attributesResponseSuccessJSON.put("message", "Exception occurred while saving attribute");
                attributesResponseSuccessJSON.put("data", "[]");
                writeBackToClient(new JSONSuccess(attributesResponseSuccessJSON));
            } catch (IOException e1) {
                logger.error(e1.getMessage(), e1);
            } catch (JSONException e2) {
                logger.error(e2.getMessage(), e2);
            }
            throw new SpagoBIServiceException(SERVICE_NAME, "Exception occurred while retrieving attributes",
                    e);
        }
    } else if (serviceType != null && serviceType.equalsIgnoreCase(ATTR_DELETE)) {

        String idStr = null;
        try {
            BufferedReader b = httpRequest.getReader();
            if (b != null) {
                String respJsonObject = b.readLine();
                if (respJsonObject != null) {
                    JSONObject responseJSON = deserialize(respJsonObject);
                    idStr = responseJSON.getString(SAMPLES);
                }
            }

        } catch (IOException e1) {
            logger.error("IO Exception", e1);
            e1.printStackTrace();
        } catch (SerializationException e) {
            logger.error("Deserialization Exception", e);
            e.printStackTrace();
        } catch (JSONException e) {
            logger.error("JSONException", e);
            e.printStackTrace();
        }
        if (idStr != null && !idStr.equals("")) {
            HashMap<String, String> logParam = new HashMap();
            logParam.put("ATTRIBUTE ID", idStr);
            Integer id = new Integer(idStr);
            try {
                attrDao.deleteSbiAttributeById(id);
                logger.debug("Attribute deleted");
                JSONObject attributesResponseSuccessJSON = new JSONObject();
                attributesResponseSuccessJSON.put("success", true);
                attributesResponseSuccessJSON.put("message", "");
                attributesResponseSuccessJSON.put("data", "[]");
                writeBackToClient(new JSONSuccess(attributesResponseSuccessJSON));
                AuditLogUtilities.updateAudit(getHttpRequest(), profile, "PROF_ATTRIBUTES.DELETE", logParam,
                        "OK");
            } catch (Throwable e) {
                logger.error("Exception occurred while deleting attribute", e);
                getHttpResponse().setStatus(404);
                try {
                    JSONObject attributesResponseSuccessJSON = new JSONObject();
                    attributesResponseSuccessJSON.put("success", false);
                    attributesResponseSuccessJSON.put("message", "Exception occurred while deleting attribute");
                    attributesResponseSuccessJSON.put("data", "[]");
                    writeBackToClient(new JSONSuccess(attributesResponseSuccessJSON));
                    try {
                        AuditLogUtilities.updateAudit(getHttpRequest(), profile, "PROF_ATTRIBUTES.DELETE",
                                logParam, "KO");
                    } catch (Exception e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                } catch (IOException e1) {
                    logger.error(e1.getMessage(), e1);
                } catch (JSONException e2) {
                    // TODO Auto-generated catch block
                    logger.error(e2.getMessage(), e2);
                }
                /*               throw new SpagoBIServiceException(SERVICE_NAME,
                                     "Exception occurred while deleting attribute",
                                     e);*/
            }
        }
    }
    logger.debug("OUT");

}

From source file:com.impala.servlet.Balance.java

/**
 * //from   w w  w .  ja v  a  2  s .  c  o m
 * @param request
 * @return
 * @throws IOException
 */
private String moneytransfer(HttpServletRequest request) throws IOException, JSONException {

    // joined json string
    String join = "";
    JsonElement root = null;
    JsonElement root2 = null;
    JsonElement root3 = null;

    String responseobject = "";

    String nickname = "KENDYIPL";

    // These represent parameters received over the network
    String referenceid = "", customermsisdn = "", amount = "", batchref = "", username = "", password = "",
            narrative = "";
    //referenceid, customermsisdn, nickname,amount, batchref, username, password, narrative

    // Get all parameters, the keys of the parameters are specified
    List<String> lines = IOUtils.readLines(request.getReader());

    // used to format/join incoming JSon string
    join = StringUtils.join(lines.toArray(), "");

    //###############################################################################
    // instantiate the JSon
    //Note
    //The = sign is encoded to \u003d. Hence you need to use disableHtmlEscaping().
    //###############################################################################

    Gson g = new GsonBuilder().disableHtmlEscaping().create();
    //Gson g = new Gson();
    Map<String, String> expected = new HashMap<>();

    try {
        // parse the JSon string
        //referenceid, customermsisdn, nickname,amount, batchref, username, password, narrative

        root = new JsonParser().parse(join);

        password = root.getAsJsonObject().get("password").getAsString();

        username = root.getAsJsonObject().get("username").getAsString();

    } catch (Exception e) {

        expected.put("command_status", "COMMANDSTATUS_INVALID_PARAMETERS");
        String jsonResult = g.toJson(expected);
        System.out.println(e);

        return jsonResult;
    }

    // check for the presence of all required parameters
    if (StringUtils.isBlank(nickname) || StringUtils.isBlank(password) || StringUtils.isBlank(username)) {

        expected.put("username", username);

        expected.put("status_code", statuscode);
        expected.put("status_description", Statusdescription);
        String jsonResult = g.toJson(expected);

        return jsonResult;
    }

    //assign the remit url from properties.config

    String processtransaction = airtelbalance.AirtelBalance(nickname, username, password);
    //capture the switch respoinse.

    System.out.println(processtransaction);

    //pass the returned json string
    JsonElement roots = new JsonParser().parse(processtransaction);

    //exctract a specific json element from the object(status_code)
    Double balance = roots.getAsJsonObject().get("CheckBalanceResult").getAsDouble();

    //add 

    expected.put("username", username);

    expected.put("balance", balance.toString());

    String jsonResult = g.toJson(expected);

    return jsonResult;

}

From source file:org.openhab.io.hueemulation.internal.HueEmulationServlet.java

/**
 * Hue API call to configure a user//  w w  w  . j  av a 2s. c  om
 *
 * @param req
 * @param resp
 * @throws IOException
 */
public void apiConfig(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    if (!req.getMethod().equals(METHOD_POST)) {
        apiServerError(req, resp, HueErrorResponse.METHOD_NOT_AVAILABLE, "Only POST allowed for this resource");
        return;
    }
    PrintWriter out = resp.getWriter();

    HueCreateUser user = gson.fromJson(req.getReader(), HueCreateUser.class);
    logger.debug("Create user: {}", user.devicetype);
    if (user.username == null || user.username.length() == 0) {
        user.username = UUID.randomUUID().toString();
    }
    addUser(user.username);
    String response = String.format(NEW_CLIENT_RESP, user.username);
    out.write(response);
    out.close();
}

From source file:org.b3log.solo.processor.api.MetaWeblogAPI.java

/**
 * MetaWeblog requests processing./*from w ww.jav a 2 s . co m*/
 *
 * @param context the specified http request context
 */
@RequestProcessing(value = "/apis/metaweblog", method = HttpMethod.POST)
public void metaWeblog(final RequestContext context) {
    final TextXmlRenderer renderer = new TextXmlRenderer();
    context.setRenderer(renderer);

    String responseContent;
    try {
        final HttpServletRequest request = context.getRequest();
        String xml;
        try {
            final ServletInputStream inputStream = request.getInputStream();
            xml = IOUtils.toString(inputStream, "UTF-8");
        } catch (final Exception e) {
            xml = IOUtils.toString(request.getReader());
        }

        final JSONObject requestJSONObject = XML.toJSONObject(xml);

        final JSONObject methodCall = requestJSONObject.getJSONObject(METHOD_CALL);
        final String methodName = methodCall.getString(METHOD_NAME);

        LOGGER.log(Level.INFO, "MetaWeblog[methodName={0}]", methodName);

        final JSONArray params = methodCall.getJSONObject("params").getJSONArray("param");

        if (METHOD_DELETE_POST.equals(methodName)) {
            params.remove(0); // Removes the first argument "appkey"
        }

        final String userEmail = params.getJSONObject(INDEX_USER_EMAIL).getJSONObject("value")
                .optString("string");
        final JSONObject user = userQueryService.getUserByEmailOrUserName(userEmail);
        if (null == user) {
            throw new Exception("No user [email=" + userEmail + "]");
        }
        final String userId = user.optString(Keys.OBJECT_ID);

        final String userPwd = params.getJSONObject(INDEX_USER_PWD).getJSONObject("value").get("string")
                .toString();
        if (!user.getString(User.USER_PASSWORD).equals(DigestUtils.md5Hex(userPwd))) {
            throw new Exception("Wrong password");
        }

        if (METHOD_GET_USERS_BLOGS.equals(methodName)) {
            responseContent = getUsersBlogs();
        } else if (METHOD_GET_CATEGORIES.equals(methodName)) {
            responseContent = getCategories();
        } else if (METHOD_GET_RECENT_POSTS.equals(methodName)) {
            final int numOfPosts = params.getJSONObject(INDEX_NUM_OF_POSTS).getJSONObject("value")
                    .getInt("int");
            responseContent = getRecentPosts(numOfPosts);
        } else if (METHOD_NEW_POST.equals(methodName)) {
            final JSONObject article = parsetPost(methodCall);
            article.put(Article.ARTICLE_AUTHOR_ID, userId);
            addArticle(article);

            final StringBuilder stringBuilder = new StringBuilder(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse>")
                            .append("<params><param><value><string>").append(article.getString(Keys.OBJECT_ID))
                            .append("</string></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else if (METHOD_GET_POST.equals(methodName)) {
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value")
                    .optString("string");
            responseContent = getPost(postId);
        } else if (METHOD_EDIT_POST.equals(methodName)) {
            final JSONObject article = parsetPost(methodCall);
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value")
                    .optString("string");
            article.put(Keys.OBJECT_ID, postId);
            article.put(Article.ARTICLE_AUTHOR_ID, userId);
            final JSONObject updateArticleRequest = new JSONObject();
            updateArticleRequest.put(Article.ARTICLE, article);
            articleMgmtService.updateArticle(updateArticleRequest);

            final StringBuilder stringBuilder = new StringBuilder(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse>")
                            .append("<params><param><value><string>").append(postId)
                            .append("</string></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else if (METHOD_DELETE_POST.equals(methodName)) {
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value")
                    .optString("string");
            articleMgmtService.removeArticle(postId);

            final StringBuilder stringBuilder = new StringBuilder(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse>")
                            .append("<params><param><value><boolean>").append(true)
                            .append("</boolean></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else {
            throw new UnsupportedOperationException("Unsupported method[name=" + methodName + "]");
        }
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);

        final StringBuilder stringBuilder = new StringBuilder(
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse>").append("<fault><value><struct>")
                        .append("<member><name>faultCode</name><value><int>500</int></value></member>")
                        .append("<member><name>faultString</name><value><string>").append(e.getMessage())
                        .append("</string></value></member></struct></value></fault></methodResponse>");

        responseContent = stringBuilder.toString();
    }

    renderer.setContent(responseContent);
}

From source file:grails.web.servlet.mvc.GrailsParameterMap.java

/**
 * Creates a GrailsParameterMap populating from the given request object
 * @param request The request object/* w ww.j  a v a  2  s  .com*/
 */
public GrailsParameterMap(HttpServletRequest request) {
    this.request = request;
    final Map requestMap = new LinkedHashMap(request.getParameterMap());
    if (requestMap.isEmpty() && ("PUT".equals(request.getMethod()) || "PATCH".equals(request.getMethod()))
            && request.getAttribute(REQUEST_BODY_PARSED) == null) {
        // attempt manual parse of request body. This is here because some containers don't parse the request body automatically for PUT request
        String contentType = request.getContentType();
        if ("application/x-www-form-urlencoded".equals(contentType)) {
            try {
                Reader reader = request.getReader();
                if (reader != null) {
                    String contents = IOUtils.toString(reader);
                    request.setAttribute(REQUEST_BODY_PARSED, true);
                    requestMap.putAll(WebUtils.fromQueryString(contents));
                }
            } catch (Exception e) {
                LOG.error("Error processing form encoded " + request.getMethod() + " request", e);
            }
        }
    }

    if (request instanceof MultipartHttpServletRequest) {
        Map<String, MultipartFile> fileMap = ((MultipartHttpServletRequest) request).getFileMap();
        for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
            requestMap.put(entry.getKey(), entry.getValue());
        }
    }

    updateNestedKeys(requestMap);
}

From source file:org.codehaus.groovy.grails.web.servlet.mvc.GrailsParameterMap.java

/**
 * Creates a GrailsParameterMap populating from the given request object
 * @param request The request object//www  . j  a  v a 2s . co  m
 */
public GrailsParameterMap(HttpServletRequest request) {
    this.request = request;
    final Map requestMap = new LinkedHashMap(request.getParameterMap());
    if (requestMap.isEmpty() && "PUT".equals(request.getMethod())
            && request.getAttribute(REQUEST_BODY_PARSED) == null) {
        // attempt manual parse of request body. This is here because some containers don't parse the request body automatically for PUT request
        String contentType = request.getContentType();
        if ("application/x-www-form-urlencoded".equals(contentType)) {
            try {
                String contents = IOUtils.toString(request.getReader());
                request.setAttribute(REQUEST_BODY_PARSED, true);
                requestMap.putAll(WebUtils.fromQueryString(contents));
            } catch (Exception e) {
                LOG.error("Error processing form encoded PUT request", e);
            }
        }
    }

    if (request instanceof MultipartHttpServletRequest) {
        Map<String, MultipartFile> fileMap = ((MultipartHttpServletRequest) request).getFileMap();
        for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
            requestMap.put(entry.getKey(), entry.getValue());
        }
    }

    updateNestedKeys(requestMap);
}

From source file:com.senseidb.servlet.AbstractSenseiClientServlet.java

private void handleStoreGetRequest(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    long time = System.currentTimeMillis();
    int numHits = 0, totalDocs = 0;
    String query = null;/*from w w  w. j av  a2 s.c om*/

    SenseiRequest senseiReq = null;
    try {
        JSONArray ids = null;
        if ("post".equalsIgnoreCase(req.getMethod())) {
            BufferedReader reader = req.getReader();
            ids = new JSONArray(readContent(reader));
        } else {
            String jsonString = req.getParameter("json");
            if (jsonString != null)
                ids = new JSONArray(jsonString);
        }

        query = "get=" + String.valueOf(ids);

        String[] vals = RequestConverter2.getStrings(ids);
        if (vals != null && vals.length != 0) {
            senseiReq = new SenseiRequest();
            senseiReq.setFetchStoredValue(true);
            senseiReq.setCount(vals.length);
            BrowseSelection sel = new BrowseSelection(SenseiFacetHandlerBuilder.UID_FACET_NAME);
            sel.setValues(vals);
            senseiReq.addSelection(sel);
        }

        SenseiResult res = null;
        if (senseiReq != null)
            res = _senseiBroker.browse(senseiReq);

        if (res != null) {
            numHits = res.getNumHits();
            totalDocs = res.getTotalDocs();
        }

        JSONObject ret = new JSONObject();
        JSONObject obj = null;
        if (res != null && res.getSenseiHits() != null) {
            for (SenseiHit hit : res.getSenseiHits()) {
                try {
                    obj = new JSONObject(hit.getSrcData());
                    ret.put(String.valueOf(hit.getUID()), obj);
                } catch (Exception ex) {
                    logger.warn(ex.getMessage(), ex);
                }
            }
        }
        OutputStream ostream = resp.getOutputStream();
        ostream.write(ret.toString().getBytes("UTF-8"));
        ostream.flush();
    } catch (Exception e) {
        throw new ServletException(e.getMessage(), e);
    } finally {
        if (queryLogger.isInfoEnabled() && query != null) {
            queryLogger.info(String.format("hits(%d/%d) took %dms: %s", numHits, totalDocs,
                    System.currentTimeMillis() - time, query));
        }
    }
}