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:org.ow2.petals.binding.restproxy.in.AbstractRESTService.java

/**
 * @param path//ww w  . j  ava  2s . com
 * @param request
 * @return
 */
private Map<String, Object> createProperties(final String path, final HttpServletRequest request) {
    Map<String, Object> result = new HashMap<String, Object>();

    result.put(org.ow2.petals.messaging.framework.message.Constants.HTTP_URL, path);

    Enumeration<?> headers = request.getHeaderNames();
    if (headers != null) {
        while (headers.hasMoreElements()) {
            Object object = headers.nextElement();
            String key = object.toString();
            result.put(org.ow2.petals.messaging.framework.message.Constants.HEADER + "." + key,
                    request.getHeader(key));
        }
    }

    result.put(org.ow2.petals.messaging.framework.message.Constants.CONTENT_LENGTH, request.getContentLength());
    String contentType = HTTPUtils.getContentType(request.getContentType());
    result.put(org.ow2.petals.messaging.framework.message.Constants.CONTENT_TYPE, contentType);
    final String charsetEncoding = request.getCharacterEncoding();
    result.put(org.ow2.petals.messaging.framework.message.Constants.CHARSET_ENCODING, charsetEncoding);
    result.put(org.ow2.petals.messaging.framework.message.Constants.HTTP_METHOD, request.getMethod());

    // get form data which is not XML!
    Enumeration<?> e = request.getParameterNames();
    while (e.hasMoreElements()) {
        String paramName = (String) e.nextElement();
        String[] values = request.getParameterValues(paramName.toString());
        int i = 0;
        for (String string : values) {
            result.put(org.ow2.petals.messaging.framework.message.Constants.PARAMETERS + "." + (i++) + "."
                    + paramName, string);
        }
    }

    for (String key : result.keySet()) {
        this.logger.debug("From HTTPRequest : Property '" + key + "' = '" + result.get(key) + "'");
    }
    return result;
}

From source file:org.apache.openaz.xacml.rest.XACMLPdpServlet.java

/**
 * PUT - The PAP engine sends configuration information using HTTP PUT request. One parameter is expected:
 * config=[policy|pip|all] policy - Expect a properties file that contains updated lists of the root and
 * referenced policies that the PDP should be using for PEP requests. Specifically should AT LEAST contain
 * the following properties: xacml.rootPolicies xacml.referencedPolicies In addition, any relevant
 * information needed by the PDP to load or retrieve the policies to store in its cache. EXAMPLE:
 * xacml.rootPolicies=PolicyA.1, PolicyB.1
 * PolicyA.1.url=http://localhost:9090/PAP?id=b2d7b86d-d8f1-4adf-ba9d-b68b2a90bee1&version=1
 * PolicyB.1.url=http://localhost:9090/PAP/id=be962404-27f6-41d8-9521-5acb7f0238be&version=1
 * xacml.referencedPolicies=RefPolicyC.1, RefPolicyD.1
 * RefPolicyC.1.url=http://localhost:9090/PAP?id=foobar&version=1
 * RefPolicyD.1.url=http://localhost:9090/PAP/id=example&version=1 pip - Expect a properties file that
 * contain PIP engine configuration properties. Specifically should AT LEAST the following property:
 * xacml.pip.engines In addition, any relevant information needed by the PDP to load and configure the
 * PIPs. EXAMPLE: xacml.pip.engines=foo,bar foo.classname=com.foo foo.sample=abc foo.example=xyz ......
 * bar.classname=com.bar ...... all - Expect ALL new configuration properties for the PDP
 *
 * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
 *///ww  w. j  a  v a 2s .  co  m
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //
    // Dump our request out
    //
    if (logger.isDebugEnabled()) {
        XACMLRest.dumpRequest(request);
    }
    //
    // What is being PUT?
    //
    String cache = request.getParameter("cache");
    //
    // Should be a list of policy and pip configurations in Java properties format
    //
    if (cache != null && request.getContentType().equals("text/x-java-properties")) {
        if (request.getContentLength() > Integer
                .parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", "32767"))) {
            String message = "Content-Length larger than server will accept.";
            logger.info(message);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
            return;
        }
        this.doPutConfig(cache, request, response);
    } else {
        String message = "Invalid cache: '" + cache + "' or content-type: '" + request.getContentType() + "'";
        logger.error(message);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
        return;
    }
}

From source file:jeeves.server.sources.http.JeevesServlet.java

private void execute(HttpServletRequest req, HttpServletResponse res) throws IOException {
    String ip = req.getRemoteAddr();
    // if we do have the optional x-forwarded-for request header then
    // use whatever is in it to record ip address of client
    String forwardedFor = req.getHeader("x-forwarded-for");
    if (forwardedFor != null)
        ip = forwardedFor;/* w w  w .  ja v  a  2 s  .  c om*/

    Log.info(Log.REQUEST, "==========================================================");
    Log.info(Log.REQUEST, "HTML Request (from " + ip + ") : " + req.getRequestURI());
    if (Log.isDebugEnabled(Log.REQUEST)) {
        Log.debug(Log.REQUEST, "Method       : " + req.getMethod());
        Log.debug(Log.REQUEST, "Content type : " + req.getContentType());
        //      Log.debug(Log.REQUEST, "Context path : "+ req.getContextPath());
        //      Log.debug(Log.REQUEST, "Char encoding: "+ req.getCharacterEncoding());
        Log.debug(Log.REQUEST, "Accept       : " + req.getHeader("Accept"));
        //      Log.debug(Log.REQUEST, "Server name  : "+ req.getServerName());
        //      Log.debug(Log.REQUEST, "Server port  : "+ req.getServerPort());
    }
    //      for (Enumeration e = req.getHeaderNames(); e.hasMoreElements();) {
    //         String theHeader = (String)e.nextElement();
    //        if(Log.isDebugEnabled(Log.REQUEST)) {
    //         Log.debug(Log.REQUEST, "Got header: "+theHeader);   
    //         Log.debug(Log.REQUEST, "With value: "+req.getHeader(theHeader));
    //        }
    //      }
    HttpSession httpSession = req.getSession();
    if (Log.isDebugEnabled(Log.REQUEST))
        Log.debug(Log.REQUEST, "Session id is " + httpSession.getId());
    UserSession session = (UserSession) httpSession.getAttribute("session");

    //------------------------------------------------------------------------
    //--- create a new session if doesn't exist

    if (session == null) {
        //--- create session

        session = new UserSession();
        httpSession.setAttribute("session", session);
        if (Log.isDebugEnabled(Log.REQUEST))
            Log.debug(Log.REQUEST, "Session created for client : " + ip);
    }

    session.setProperty("realSession", httpSession);
    //------------------------------------------------------------------------
    //--- build service request

    ServiceRequest srvReq = null;

    //--- create request

    try {
        srvReq = ServiceRequestFactory.create(req, res, jeeves.getUploadDir(), jeeves.getMaxUploadSize());
    } catch (FileUploadTooBigEx e) {
        StringBuffer sb = new StringBuffer();
        sb.append("Opgeladen bestand overschrijdt de maximaal toegelaten grootte van "
                + jeeves.getMaxUploadSize() + " Mb\n");
        sb.append("Error : " + e.getClass().getName() + "\n");
        res.sendError(400, sb.toString());

        // now stick the stack trace on the end and log the whole lot
        sb.append("Stack :\n");
        sb.append(Util.getStackTrace(e));
        Log.error(Log.REQUEST, sb.toString());
        return;
    } catch (FileTypeNotAllowedEx e) {
        StringBuffer sb = new StringBuffer();
        sb.append("Bestand heeft niet het juiste type\n");
        sb.append("Error : " + e.getClass().getName() + "\n");
        res.sendError(400, sb.toString());

        // now stick the stack trace on the end and log the whole lot
        sb.append("Stack :\n");
        sb.append(Util.getStackTrace(e));
        Log.error(Log.REQUEST, sb.toString());
        return;
    } catch (Exception e) {
        StringBuffer sb = new StringBuffer();

        sb.append("Cannot build ServiceRequest\n");
        sb.append("Cause : " + e.getMessage() + "\n");
        sb.append("Error : " + e.getClass().getName() + "\n");
        res.sendError(400, sb.toString());

        // now stick the stack trace on the end and log the whole lot
        sb.append("Stack :\n");
        sb.append(Util.getStackTrace(e));
        Log.error(Log.REQUEST, sb.toString());
        return;
    }

    if ("user.agiv.login".equals(srvReq.getService())) {
        if (srvReq.getParams() != null && srvReq.getParams().getChild("wa") != null
                && srvReq.getParams().getChild("wa").getTextTrim().equals("wsignoutcleanup1.0")) {
            srvReq.setService("user.agiv.logout");
        } else {
            Principal p = req.getUserPrincipal();
            if (p != null
                    && p instanceof FederationPrincipal/* && SecurityTokenThreadLocal.getToken()==null*/) {
                FederationPrincipal fp = (FederationPrincipal) p;
                /*
                                  for (Claim c: fp.getClaims()) {
                                      System.out.println(c.getClaimType().toString() + ":" + (c.getValue()!=null ? c.getValue().toString() : ""));               
                                  }
                */
                Map<String, String> roleProfileMapping = new HashMap<String, String>();
                String profile = null;
                roleProfileMapping.put("Authenticated", "RegisteredUser");
                roleProfileMapping.put(nodeType + " Metadata Admin", "Administrator");
                roleProfileMapping.put(nodeType + " Metadata Editor", "Editor");
                roleProfileMapping.put(nodeType + " Metadata Hoofdeditor", "Hoofdeditor");
                List<String> roleListToCheck = Arrays.asList(nodeType + " Metadata Admin",
                        nodeType + " Metadata Hoofdeditor", nodeType + " Metadata Editor", "Authenticated");
                for (String item : roleListToCheck) {
                    if (req.isUserInRole(item)) {
                        profile = roleProfileMapping.get(item);
                        break;
                    }
                }
                String contactid = Util.getClaimValue(fp, "contactid");
                session.authenticate(contactid, contactid/* + "_" + Util.getClaimValue(fp,"name")*/,
                        Util.getClaimValue(fp, "givenname"), Util.getClaimValue(fp, "surname"),
                        profile != null ? profile : "RegisteredUser", Util.getClaimValue(fp, "emailaddress"));
                List<Map<String, String>> groups = new ArrayList<Map<String, String>>();
                Map<String, String> group = new HashMap<String, String>();
                String parentorganisationid = Util.getClaimValue(fp, "parentorganisationid");
                String parentorganisationdisplayname = Util.getClaimValue(fp, "parentorganisationdisplayname");
                group.put("name",
                        StringUtils.isBlank(parentorganisationid) ? Util.getClaimValue(fp, "organisationid")
                                : parentorganisationid);
                group.put("description",
                        StringUtils.isBlank(parentorganisationdisplayname)
                                ? (StringUtils.isBlank(parentorganisationid)
                                        ? Util.getClaimValue(fp, "organisationdisplayname")
                                        : parentorganisationid)
                                : parentorganisationdisplayname);
                groups.add(group);
                session.setProperty("groups", groups);
            } else {
                System.out.println("Principal is not instance of FederationPrincipal");
            }
        }
    }

    //--- execute request

    jeeves.dispatch(srvReq, session);
}

From source file:org.dspace.app.webui.servlet.admin.EditCommunitiesServlet.java

protected void doDSPost(Context context, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException, AuthorizeException {
    // First, see if we have a multipart request (uploading a logo)
    String contentType = request.getContentType();

    if ((contentType != null) && (contentType.indexOf("multipart/form-data") != -1)) {
        // This is a multipart request, so it's a file upload
        processUploadLogo(context, request, response);

        return;//from  w  w  w . ja v a2s .c o  m
    }

    /*
     * Respond to submitted forms. Each form includes an "action" parameter
     * indicating what needs to be done (from the constants above.)
     */
    int action = UIUtil.getIntParameter(request, "action");

    /*
     * Most of the forms supply one or more of these values. Since we just
     * get null if we try and find something with ID -1, we'll just try and
     * find both here to save hassle later on
     */
    Community community = Community.find(context, UIUtil.getIntParameter(request, "community_id"));
    Community parentCommunity = Community.find(context, UIUtil.getIntParameter(request, "parent_community_id"));
    Collection collection = Collection.find(context, UIUtil.getIntParameter(request, "collection_id"));

    // Just about every JSP will need the values we received
    request.setAttribute("community", community);
    request.setAttribute("parent", parentCommunity);
    request.setAttribute("collection", collection);

    /*
     * First we check for a "cancel" button - if it's been pressed, we
     * simply return to the main control page
     */
    if (request.getParameter("submit_cancel") != null) {
        showControls(context, request, response);

        return;
    }

    // Now proceed according to "action" parameter
    switch (action) {
    case START_EDIT_COMMUNITY:
        storeAuthorizeAttributeCommunityEdit(context, request, community);

        // Display the relevant "edit community" page
        JSPManager.showJSP(request, response, "/tools/edit-community.jsp");

        break;

    case START_DELETE_COMMUNITY:

        // Show "confirm delete" page
        JSPManager.showJSP(request, response, "/tools/confirm-delete-community.jsp");

        break;

    case START_CREATE_COMMUNITY:
        // no authorize attribute will be given to the jsp so a "clean" creation form
        // will be always supplied, advanced setting on policies and admin group creation
        // will be possible after to have completed the community creation

        // Display edit community page with empty fields + create button
        JSPManager.showJSP(request, response, "/tools/edit-community.jsp");

        break;

    case START_EDIT_COLLECTION:

        HarvestedCollection hc = HarvestedCollection.find(context,
                UIUtil.getIntParameter(request, "collection_id"));
        request.setAttribute("harvestInstance", hc);

        storeAuthorizeAttributeCollectionEdit(context, request, collection);

        // Display the relevant "edit collection" page
        JSPManager.showJSP(request, response, "/tools/edit-collection.jsp");

        break;

    case START_DELETE_COLLECTION:

        // Show "confirm delete" page
        JSPManager.showJSP(request, response, "/tools/confirm-delete-collection.jsp");

        break;

    case START_CREATE_COLLECTION:

        // Forward to collection creation wizard
        response.sendRedirect(response.encodeRedirectURL(
                request.getContextPath() + "/tools/collection-wizard?community_id=" + community.getID()));

        break;

    case CONFIRM_EDIT_COMMUNITY:

        // Edit or creation of a community confirmed
        processConfirmEditCommunity(context, request, response, community);

        break;

    case CONFIRM_DELETE_COMMUNITY:

        // remember the parent community, if any
        Community parent = community.getParentCommunity();

        // Delete the community
        community.delete();

        // if community was top-level, redirect to community-list page
        if (parent == null) {
            response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/community-list"));
        } else
        // redirect to parent community page
        {
            response.sendRedirect(
                    response.encodeRedirectURL(request.getContextPath() + "/handle/" + parent.getHandle()));
        }

        // Show main control page
        //showControls(context, request, response);
        // Commit changes to DB
        context.complete();

        break;

    case CONFIRM_EDIT_COLLECTION:

        // Edit or creation of a collection confirmed
        processConfirmEditCollection(context, request, response, community, collection);

        break;

    case CONFIRM_DELETE_COLLECTION:

        // Delete the collection
        community.removeCollection(collection);
        // remove the collection object from the request, so that the user
        // will be redirected on the community home page
        request.removeAttribute("collection");
        // Show main control page
        showControls(context, request, response);

        // Commit changes to DB
        context.complete();

        break;

    default:

        // Erm... weird action value received.
        log.warn(LogManager.getHeader(context, "integrity_error", UIUtil.getRequestLogInfo(request)));
        JSPManager.showIntegrityError(request, response);
    }
}

From source file:org.opendaylight.iotdm.onem2m.protocols.http.Onem2mHttpProvider.java

public void handle(IotDMPluginRequest request, IotDMPluginResponse response) {
    HttpServletRequest httpRequest = ((IotDMPluginHttpRequest) request).getHttpRequest();
    HttpServletResponse httpResponse = ((IotDMPluginHttpResponse) response).getHttpResponse();

    Onem2mRequestPrimitiveClientBuilder clientBuilder = new Onem2mRequestPrimitiveClientBuilder();
    String headerValue;//from  w w w.j  ava 2s  .c o m

    clientBuilder.setProtocol(Onem2m.Protocol.HTTP);

    Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS);

    String contentType = httpRequest.getContentType();
    if (contentType == null)
        contentType = "json";
    contentType = contentType.toLowerCase();
    if (contentType.contains("json")) {
        clientBuilder.setContentFormat(Onem2m.ContentFormat.JSON);
    } else if (contentType.contains("xml")) {
        clientBuilder.setContentFormat(Onem2m.ContentFormat.XML);
    } else {
        httpResponse.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        try {
            httpResponse.getWriter().println("Unsupported media type: " + contentType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/json;charset=utf-8");

        Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_ERROR);
        return;
    }

    clientBuilder.setTo(Onem2m.translateUriToOnem2m(httpRequest.getRequestURI()));

    // pull fields out of the headers
    headerValue = httpRequest.getHeader(Onem2m.HttpHeaders.X_M2M_ORIGIN);
    if (headerValue != null) {
        clientBuilder.setFrom(headerValue);
    }
    headerValue = httpRequest.getHeader(Onem2m.HttpHeaders.X_M2M_RI);
    if (headerValue != null) {
        clientBuilder.setRequestIdentifier(headerValue);
    }
    headerValue = httpRequest.getHeader(Onem2m.HttpHeaders.X_M2M_NM);
    if (headerValue != null) {
        clientBuilder.setName(headerValue);
    }
    headerValue = httpRequest.getHeader(Onem2m.HttpHeaders.X_M2M_GID);
    if (headerValue != null) {
        clientBuilder.setGroupRequestIdentifier(headerValue);
    }
    headerValue = httpRequest.getHeader(Onem2m.HttpHeaders.X_M2M_RTU);
    if (headerValue != null) {
        clientBuilder.setResponseType(headerValue);
    }
    headerValue = httpRequest.getHeader(Onem2m.HttpHeaders.X_M2M_OT);
    if (headerValue != null) {
        clientBuilder.setOriginatingTimestamp(headerValue);
    }

    // the contentType string can have ty=val attached to it so we should handle this case
    Boolean resourceTypePresent = false;
    String contentTypeResourceString = parseContentTypeForResourceType(contentType);
    if (contentTypeResourceString != null) {
        resourceTypePresent = clientBuilder.parseQueryStringIntoPrimitives(contentTypeResourceString);
    }
    String method = httpRequest.getMethod().toLowerCase();
    // look in query string if didnt find it in contentType header
    if (!resourceTypePresent) {
        resourceTypePresent = clientBuilder.parseQueryStringIntoPrimitives(httpRequest.getQueryString());
    } else {
        clientBuilder.parseQueryStringIntoPrimitives(httpRequest.getQueryString());
    }
    if (resourceTypePresent && !method.contentEquals("post")) {
        httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        try {
            httpResponse.getWriter().println("Specifying resource type not permitted.");
        } catch (IOException e) {
            e.printStackTrace();
        }
        Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_ERROR);
        return;
    }

    // take the entire payload text and put it in the CONTENT field; it is the representation of the resource
    String cn = request.getPayLoad();
    if (cn != null && !cn.contentEquals("")) {
        clientBuilder.setPrimitiveContent(cn);
    }

    switch (method) {
    case "get":
        clientBuilder.setOperationRetrieve();
        Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_RETRIEVE);
        break;
    case "post":
        if (resourceTypePresent) {
            clientBuilder.setOperationCreate();
            Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_CREATE);
        } else {
            clientBuilder.setOperationNotify();
            Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_NOTIFY);
        }
        break;
    case "put":
        clientBuilder.setOperationUpdate();
        Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_UPDATE);
        break;
    case "delete":
        clientBuilder.setOperationDelete();
        Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_DELETE);
        break;
    default:
        httpResponse.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
        try {
            httpResponse.getWriter().println("Unsupported method type: " + method);
        } catch (IOException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/json;charset=utf-8");
        //baseRequest.setHandled(true);
        Onem2mStats.getInstance().inc(Onem2mStats.HTTP_REQUESTS_ERROR);
        return;
    }

    // invoke the service request
    Onem2mRequestPrimitiveClient onem2mRequest = clientBuilder.build();
    ResponsePrimitive onem2mResponse = Onem2m.serviceOnenm2mRequest(onem2mRequest, onem2mService);

    // now place the fields from the onem2m result response back in the http fields, and send
    try {
        sendHttpResponseFromOnem2mResponse(httpResponse, onem2mResponse);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.aliasi.demo.framework.DemoServlet.java

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

    InputStream in = null;/*from w  ww  .  ja  va  2s . com*/
    OutputStream out = null;

    try {
        response.setContentType(mDemo.responseType());
        out = response.getOutputStream();

        @SuppressWarnings("unchecked") // bad inherited API from commons
        Properties properties = mapToProperties((Map<String, String[]>) request.getParameterMap());

        String reqContentType = request.getContentType();

        if (reqContentType == null || reqContentType.startsWith("text/plain")) {

            properties.setProperty("inputType", "text/plain");
            String reqCharset = request.getCharacterEncoding();
            if (reqCharset != null)
                properties.setProperty("inputCharset", reqCharset);
            in = request.getInputStream();

        } else if (reqContentType.startsWith("application/x-www-form-urlencoded")) {

            String codedText = request.getParameter("inputText");
            byte[] bytes = codedText.getBytes("ISO-8859-1");
            in = new ByteArrayInputStream(bytes);

        } else if (ServletFileUpload.isMultipartContent(new ServletRequestContext(request))) {

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload uploader = new ServletFileUpload(factory);
            @SuppressWarnings("unchecked") // bad commons API
            List<FileItem> items = (List<FileItem>) uploader.parseRequest(request);
            Iterator<FileItem> it = items.iterator();
            while (it.hasNext()) {
                log("found item");
                FileItem item = it.next();
                if (item.isFormField()) {
                    String key = item.getFieldName();
                    String val = item.getString();
                    properties.setProperty(key, val);
                } else {
                    byte[] bytes = item.get();
                    in = new ByteArrayInputStream(bytes);
                }
            }

        } else {
            System.out.println("unexpected content type");
            String msg = "Unexpected request content" + reqContentType;
            throw new ServletException(msg);
        }
        mDemo.process(in, out, properties);
    } catch (FileUploadException e) {
        throw new ServletException(e);
    } finally {
        Streams.closeQuietly(in);
        Streams.closeQuietly(out);
    }
}

From source file:prototypes.ws.proxy.soap.proxy.ProxyServlet.java

private HttpURLConnection prepareBackendConnection(URL targetUrl, HttpServletRequest request,
        Map<String, List<String>> headers) throws IOException {
    HttpURLConnection httpConn = null;
    httpConn = (HttpURLConnection) targetUrl.openConnection();
    // timeouts//from   www.j  a  va  2s .  c  o m
    httpConn.setConnectTimeout(proxyConfig.getConnectTimeout());
    httpConn.setReadTimeout(proxyConfig.getReadTimeout());

    // type of connection
    httpConn.setDoOutput(true);
    LOGGER.debug("Request method : {}", request.getMethod());
    httpConn.setRequestMethod(request.getMethod());

    // Headers
    List<String> originalHeadersToIgnore = new ArrayList<String>(REQ_HEADERS_TO_IGNORE);
    useAuth(request, originalHeadersToIgnore, httpConn);
    Requests.setRequestHeaders(httpConn, headers, originalHeadersToIgnore);
    httpConn.setRequestProperty("X-Forwarded-For", request.getRemoteAddr());

    // some more headers
    String reqContentType = (!Strings.isNullOrEmpty(request.getContentType())) ? request.getContentType()
            : (!Strings.isNullOrEmpty(request.getHeader("Content-Type")) ? request.getHeader("Content-Type")
                    : "text/xml");
    httpConn.setRequestProperty("Content-Type", reqContentType);

    return httpConn;
}

From source file:it.greenvulcano.gvesb.adapter.http.mapping.RESTHttpServletMapping.java

/**
 * @param req/*from   w w  w  .j av  a 2  s. c o m*/
 * @param request
 * @throws GVException
 */
private void parseRequest(HttpServletRequest req, String methodName, PatternResolver pr, GVBuffer request)
        throws GVException {
    try {
        Map<String, String[]> params = req.getParameterMap();
        Iterator<String> i = params.keySet().iterator();
        while (i.hasNext()) {
            String n = i.next();
            String v = params.get(n)[0];

            request.setProperty(n, ((v != null) && !"".equals(v)) ? v : "NULL");
        }

        String ct = Optional.ofNullable(req.getContentType()).orElse("");
        request.setProperty("HTTP_REQ_CONTENT_TYPE", ct.isEmpty() ? ct : "NULL");
        String acc = req.getHeader("Accept");
        request.setProperty("HTTP_REQ_ACCEPT", (acc != null) ? acc : "NULL");

        if (methodName.equals("POST") || methodName.equals("PUT")) {
            if (!ct.startsWith(AdapterHttpConstants.URLENCODED_MIMETYPE_NAME)) {
                Object requestContent = IOUtils.toByteArray(req.getInputStream());
                if (ct.startsWith(AdapterHttpConstants.APPXML_MIMETYPE_NAME)
                        || ct.startsWith(AdapterHttpConstants.APPJSON_MIMETYPE_NAME)
                        || ct.startsWith("text/")) {
                    /* GESTIRE ENCODING!!! */
                    requestContent = new String((byte[]) requestContent);
                }
                request.setObject(requestContent);
            }
        }

        if (pr.isExtractHdr()) {
            XMLUtils parser = null;
            try {
                parser = XMLUtils.getParserInstance();
                Document doc = parser.newDocument("Hdr");
                Element root = doc.getDocumentElement();

                Enumeration<?> hn = req.getHeaderNames();
                while (hn.hasMoreElements()) {
                    Element h = parser.insertElement(root, "h");
                    String name = (String) hn.nextElement();
                    String val = req.getHeader(name);
                    parser.setAttribute(h, "n", name);
                    parser.setAttribute(h, "v", val);
                }
                request.setProperty("HTTP_REQ_HEADERS", parser.serializeDOM(doc, true, false));
            } finally {
                XMLUtils.releaseParserInstance(parser);
            }
        }

    } catch (Exception exc) {
        throw new AdapterHttpExecutionException("RESTHttpServletMapping - Error parsing request data", exc);
    }
}

From source file:org.n52.wps.server.feed.FeedServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    /*/*w ww.j a  v  a  2s . com*/
     * how can the new remote repository be posted?!
     * 1. complete xml snippet
     * 2. what else?!
     */

    RemoteRepository newRemoteRepo = null;

    OutputStream out = res.getOutputStream();
    try {
        InputStream is = req.getInputStream();
        if (req.getParameterMap().containsKey("request")) {
            is = new ByteArrayInputStream(req.getParameter("request").getBytes("UTF-8"));
        }

        // WORKAROUND cut the parameter name "request" of the stream
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringWriter sw = new StringWriter();
        int k;
        while ((k = br.read()) != -1) {
            sw.write(k);
        }
        LOGGER.debug(sw.toString());
        String s;
        String reqContentType = req.getContentType();
        if (sw.toString().startsWith("request=")) {
            if (reqContentType.equalsIgnoreCase("text/plain")) {
                s = sw.toString().substring(8);
            } else {
                s = URLDecoder.decode(sw.toString().substring(8), "UTF-8");
            }
            LOGGER.debug(s);
        } else {
            s = sw.toString();
        }

        newRemoteRepo = RemoteRepositoryDocument.Factory.parse(s).getRemoteRepository();

        addNewRemoteRepository(newRemoteRepo);

        res.setStatus(HttpServletResponse.SC_OK);

    } catch (Exception e) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error occured");
    }
    out.flush();
    out.close();

}

From source file:net.bull.javamelody.TestMonitoringFilter.java

/** Test.
 * @throws ServletException e/*from  w w w.  j ava2 s.com*/
 * @throws IOException e */
@Test
public void testDoFilterWithGWT() throws ServletException, IOException {
    final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
    final String textGwtRpc = "text/x-gwt-rpc";
    expect(request.getContentType()).andReturn(textGwtRpc).anyTimes();
    expect(request.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6|7|8|9|10")).anyTimes();
    doFilter(request);

    final HttpServletRequest request2a = createNiceMock(HttpServletRequest.class);
    expect(request2a.getContentType()).andReturn("not/x-gwt-rpc").anyTimes();
    expect(request2a.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6|7|8|9|10")).anyTimes();
    doFilter(request2a);

    final HttpServletRequest request2b = createNiceMock(HttpServletRequest.class);
    expect(request2b.getContentType()).andReturn(textGwtRpc).anyTimes();
    expect(request2b.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6")).anyTimes();
    expect(request2b.getReader()).andReturn(new BufferedReader(new StringReader("1|2|3|4|5|6"))).anyTimes();
    replay(request2b);
    final PayloadNameRequestWrapper wrapper2b = new PayloadNameRequestWrapper(request2b);
    wrapper2b.getInputStream().read();
    wrapper2b.getReader().read();
    verify(request2b);

    final HttpServletRequest request2 = createNiceMock(HttpServletRequest.class);
    expect(request2.getContentType()).andReturn(textGwtRpc).anyTimes();
    expect(request2.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6||8|9|10")).anyTimes();
    expect(request2.getReader()).andReturn(new BufferedReader(new StringReader("1|2|3|4|5|6"))).anyTimes();
    replay(request2);
    final PayloadNameRequestWrapper wrapper2 = new PayloadNameRequestWrapper(request2);
    wrapper2.getInputStream().read();
    wrapper2.getReader().read();
    verify(request2);

    final HttpServletRequest request3 = createNiceMock(HttpServletRequest.class);
    expect(request3.getContentType()).andReturn(textGwtRpc).anyTimes();
    expect(request3.getCharacterEncoding()).andReturn("utf-8").anyTimes();
    expect(request3.getInputStream()).andReturn(createInputStreamForString("1|2|3|4|5|6||8|9|10")).anyTimes();
    expect(request3.getReader()).andReturn(new BufferedReader(new StringReader("1|2|3|4|5|6"))).anyTimes();
    replay(request3);
    final PayloadNameRequestWrapper wrapper3 = new PayloadNameRequestWrapper(request3);
    wrapper3.getInputStream().read();
    wrapper3.getInputStream().read();
    wrapper3.getReader().read();
    wrapper3.getReader().read();
    verify(request3);
}