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.nunux.poc.portal.ProxyServlet.java

/**
 * Performs an HTTP POST request/*  w  w w . ja  v  a2  s  . c om*/
 *
 * @param httpServletRequest The {@link HttpServletRequest} object passed in
 * by the servlet engine representing the client request to be proxied
 * @param httpServletResponse The {@link HttpServletResponse} object by
 * which we can send a proxied response to the client
 */
@Override
public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, ServletException {
    // Create a standard POST request
    String contentType = httpServletRequest.getContentType();
    String destinationUrl = this.getProxyURL(httpServletRequest);
    debug("POST Request URL: " + httpServletRequest.getRequestURL(), "    Content Type: " + contentType,
            " Destination URL: " + destinationUrl);
    PostMethod postMethodProxyRequest = new PostMethod(destinationUrl);
    // Forward the request headers
    setProxyRequestHeaders(httpServletRequest, postMethodProxyRequest);
    setProxyRequestCookies(httpServletRequest, postMethodProxyRequest);
    // Check if this is a mulitpart (file upload) POST
    if (ServletFileUpload.isMultipartContent(httpServletRequest)) {
        this.handleMultipartPost(postMethodProxyRequest, httpServletRequest);
    } else {
        if (contentType == null || PostMethod.FORM_URL_ENCODED_CONTENT_TYPE.equals(contentType)) {
            this.handleStandardPost(postMethodProxyRequest, httpServletRequest);
        } else {
            this.handleContentPost(postMethodProxyRequest, httpServletRequest);
        }
    }
    // Execute the proxy request
    this.executeProxyRequest(postMethodProxyRequest, httpServletRequest, httpServletResponse);
}

From source file:net.sf.ginp.GinpServlet.java

/**
 *  Central Processor of HTTP Methods. This method gets the model for the
 *  users session, extracts the Command Parameters and preforms the command
 *  specified in the request. It then redirects or if cookies are used
 *  forwards the response to the JSP govened by the new state. If a
 *  significant error occurs it should be throwned up to here so that a
 *  debug page can be displayed. If a user sees a debug page then that is
 *  bad so lets try to find out about it and so we can fix it.
 *
 *@param  req                   HTTP Request
 *@param  res                   HTTP Response
 *@exception  IOException       Description of the Exception
 *//*from   w w w.j a v a2 s. c o  m*/
public final void doHttpMethod(final HttpServletRequest req, final HttpServletResponse res) throws IOException {
    // Set the Character Encoding. Do this first before access ing the req
    // and res objects, otherwise they take the system default.
    try {
        req.setCharacterEncoding(Configuration.getCharacterEncoding());

        //res.setCharacterEncoding(Configuration.getCharacterEncoding());
        res.setContentType("text/html; charset=\"" + Configuration.getCharacterEncoding() + "\"");
        setNoCache(res);

        // Debug
        log.debug("req.getContentType(): " + req.getContentType());
        log.debug("Request Charactor Encoding:" + req.getCharacterEncoding());
    } catch (java.io.UnsupportedEncodingException e) {
        log.error("Error setting Character Encoding. Check Configuration", e);
    }

    try {
        //Retrieve the model for this web app
        GinpModel model = ModelUtil.getModel(req);

        //This controller modifies the model via commands
        executeCommand(req, model);

        // The updated model is now available in the request,
        // go to the view page
        String url = model.getCurrentPage();

        // debug to log
        if (log.isDebugEnabled()) {
            log.debug("doHttpMethod url=" + url + " " + model.getDebugInfo());
        }

        // Forward to New URL
        forwardToPage(req, res, url);

        // debug to log
        if (log.isDebugEnabled()) {
            log.debug("DONE");
        }
    } catch (Exception ex) {
        log.error("doHttpMethod", ex);
        handleError(req, res, ex);
    }
}

From source file:org.nuxeo.ecm.platform.ui.web.auth.oauth.NuxeoOAuthFilter.java

protected boolean isOAuthSignedRequest(HttpServletRequest httpRequest) {

    String authHeader = httpRequest.getHeader("Authorization");
    if (authHeader != null && authHeader.contains("OAuth")) {
        return true;
    }/*from ww w  . j  a  v a  2  s. co m*/

    if ("GET".equals(httpRequest.getMethod()) && httpRequest.getParameter("oauth_signature") != null) {
        return true;
    } else if ("POST".equals(httpRequest.getMethod())
            && "application/x-www-form-urlencoded".equals(httpRequest.getContentType())
            && httpRequest.getParameter("oauth_signature") != null) {
        return true;
    }

    return false;
}

From source file:com.fuseim.webapp.ProxyServlet.java

protected HttpRequest newProxyRequestWithEntity(String method, String proxyRequestUri,
        HttpServletRequest servletRequest) throws IOException {
    HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);

    String contentType = servletRequest.getContentType();

    boolean isFormPost = (contentType != null && contentType.contains("application/x-www-form-urlencoded")
            && "POST".equalsIgnoreCase(servletRequest.getMethod()));

    if (isFormPost) {
        List<NameValuePair> params = new ArrayList<>();

        List<NameValuePair> queryParams = Collections.emptyList();
        String queryString = servletRequest.getQueryString();
        if (queryString != null) {
            URLEncodedUtils.parse(queryString, Consts.UTF_8);
        }/*  w  w  w . j  av a2s. c om*/
        Map<String, String[]> form = servletRequest.getParameterMap();

        OUTER_LOOP: for (Iterator<String> nameIterator = form.keySet().iterator(); nameIterator.hasNext();) {
            String name = nameIterator.next();
            for (NameValuePair queryParam : queryParams) {
                if (name.equals(queryParam.getName())) {
                    continue OUTER_LOOP;
                }
            }
            String[] value = form.get(name);
            if (value.length != 1) {
                throw new RuntimeException("expecting one value in post form");
            }
            params.add(new BasicNameValuePair(name, value[0]));
        }
        eProxyRequest.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    } else {
        eProxyRequest.setEntity(
                new InputStreamEntity(servletRequest.getInputStream(), getContentLength(servletRequest)));
    }
    return eProxyRequest;
}

From source file:prodocServ.Oper.java

/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request/*w ww.j av  a  2  s.  c  o m*/
 * @param response servlet response
 * @throws ServletException
 * @throws IOException
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/xml;charset=UTF-8");
    response.setStatus(HttpServletResponse.SC_OK);
    try {
        if (!FWStartted) {
            StartFW();
            FWStartted = true;
        }
        if (PDLog.isDebug())
            PDLog.Debug("##########################################################################");
        if (Connected(request) && request.getContentType().contains("multipart")) {
            InsFile(request, response);
            return;
        }
        if (request.getParameter(DriverRemote.ORDER) == null) {
            PrintWriter out = response.getWriter();
            Answer(request, out, "<OPD><Result>KO</Result><Msg>Disconnected</Msg></OPD>");
            out.close();
            return;
        }
        String Order = request.getParameter(DriverRemote.ORDER);
        if (Connected(request) && Order.equals(DriverGeneric.S_RETRIEVEFILE)) {
            SendFile(request, response);
            return;
        }
        if (Connected(request) || Order.equals(DriverGeneric.S_LOGIN)) {
            PrintWriter out = response.getWriter();
            ProcessPage(request, out);
            out.close();
        } else {
            PrintWriter out = response.getWriter();
            Answer(request, out, false, "<OPD><Result>KO</Result><Msg>Disconnected</Msg></OPD>", null);
            out.close();
        }
    } catch (Exception e) {
        PrintWriter out = response.getWriter();
        AddLog(e.getMessage());
        Answer(request, out, false, e.getMessage(), null);
        //    e.printStackTrace();
        out.close();
    }
}

From source file:org.dspace.rest.providers.AbstractBaseProvider.java

public void before(EntityView view, HttpServletRequest req, HttpServletResponse res) {

    log.info(userInfo() + "starting to write for collection adding");
    try {//w w  w. j av a2 s  . co m
        if (req.getContentType().equals("application/json")) {
            view.setExtension("json");
            format = "json";
        } else if (req.getContentType().equals("application/xml")) {
            view.setExtension("xml");
            format = "xml";
        } else if (req.getContentType().startsWith("multipart/form-data")) {
            view.setExtension("stream");
            format = "stream";
        } else {
            view.setExtension("json");
            format = "json";
        }
    } catch (Exception ex) {
        if (view.getFormat().equals("xml")) {
            view.setExtension("xml");
            format = "xml";
        } else {
            view.setExtension("json");
            format = "json";
        }
    }

    try {
        if (!(req.getHeader("user").isEmpty() && req.getHeader("pass").isEmpty())) {
            userc = req.getHeader("user");
            passc = req.getHeader("pass");
        }
    } catch (NullPointerException nu) {
        userc = "";
        passc = "";
    }
}

From source file:com.legstar.c2ws.servlet.C2wsProxy.java

/** {@inheritDoc} */
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException {

    long startTime = System.currentTimeMillis();

    /* Use correlation id received in http header. This allows logs on
     * this side to be easily correlated with the mainframe logs. */
    String requestID = request.getHeader(CORRELATION_ID_HDR);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Start proxy request " + requestID + " from client " + request.getRemoteHost());
    }// ww w .j  a v a 2  s  .com

    /* Make sure this is a Mainframe LegStar request. */
    if (!isSupportedContentType(request)) {
        throw new ServletException("Content type " + request.getContentType() + " is not supported");
    }

    try {
        /* Get all the bytes from the request in a byte array */
        int requestBytesLen = request.getContentLength();
        byte[] requestBytes = new byte[requestBytesLen];
        InputStream in = request.getInputStream();
        int offset = 0;
        int n;
        do {
            n = in.read(requestBytes, offset, requestBytesLen - offset);
        } while (n != -1);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Request data from host:");
            traceData(requestID, requestBytes, LOG);
        }

        /* Call the proxy getting a byte array back */
        byte[] replyBytes = getServiceProxy().invoke(requestID, requestBytes);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Reply data to host:");
            traceData(requestID, replyBytes, LOG);
        }

        /* Push the reply byte array into the http response */
        response.setContentType(request.getContentType());
        response.getOutputStream().write(replyBytes);

    } catch (IOException e) {
        throw (new ServletException(e));
    } catch (ProxyInvokerException e) {
        throw (new ServletException(e));
    }

    long endTime = System.currentTimeMillis();
    if (LOG.isDebugEnabled()) {
        LOG.debug("End proxy request " + requestID + " from client " + request.getRemoteHost() + " serviced in "
                + (endTime - startTime) + " msecs");
    }
}

From source file:com.grameenfoundation.ictc.controllers.FarmManagementPlanController.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w  w w  . j av a 2  s. c om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    Logger log = Logger.getLogger(FarmManagementPlanController.class.getName());
    BiodataModel biodataModel = new BiodataModel();
    String theString = IOUtils.toString(request.getInputStream(), "UTF-8");
    System.out.println("Salesforce data/n " + theString);
    Transaction tx;
    tx = ICTCDBUtil.getInstance().getGraphDB().beginTx();
    org.neo4j.graphdb.Node farmManagementPlanParent;
    try (PrintWriter out = response.getWriter()) {

        System.out.println(" " + request.getContentType());

        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(theString));
        System.out.println("After parsing XML");
        Document doc = db.parse(is);
        System.out.println("Should be normalised now");
        doc.getDocumentElement().normalize();

        Element ele = doc.getDocumentElement();
        //System.out.println("Root element :" + doc.getDocumentElement());
        Node node = doc.getDocumentElement();

        System.out.println("Root element " + doc.getDocumentElement());

        //get fields from objects
        NodeList sObject = doc.getElementsByTagName("sObject");
        // String farmerID = getXmlNodeValue("sf:Farmer_name__c",ele);

        for (int j = 0; j < sObject.getLength(); j++) {

            Node rowNode = sObject.item(j);
            //  Map<String,String> m = (Map<String,String>) rowNode.getAttributes();
            String salesforceObj = rowNode.getAttributes().getNamedItem("xsi:type").getNodeValue();
            System.out.println(salesforceObj);
            String farmerID = getXmlNodeValue("sf:Farmer_name__c", ele);
            System.out.println("farmerid " + farmerID);
            org.neo4j.graphdb.Node FMPNode = ICTCDBUtil.getInstance().getGraphDB()
                    .createNode(Labels.FARM_MANAGEMENT_PLAN);
            for (int k = 0; k < rowNode.getChildNodes().getLength(); k++) {

                //System.out.println("node: " + rowNode.getChildNodes().item(k).getNodeName() + ": " + rowNode.getChildNodes().item(k).getTextContent());
                if (rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")) {
                    System.out
                            .println("id : " + getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()));
                    FMPNode.setProperty(getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()),
                            rowNode.getChildNodes().item(k).getTextContent());
                }

                if (!rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")
                        && !rowNode.getChildNodes().item(k).getNodeName().equals("#text")) {

                    System.out.println(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()));
                    FMPNode.setProperty(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()),
                            rowNode.getChildNodes().item(k).getTextContent());

                }
            }

            farmManagementPlanParent = ParentNode.FMPlanParentNode();
            farmManagementPlanParent.createRelationshipTo(FMPNode, ICTCRelationshipTypes.FARM_MANAGEMENT_PLAN);

            log.log(Level.INFO, "new node created {0}", FMPNode.getId());
            Biodata b = biodataModel.getBiodata("Id", farmerID);

            biodataModel.BiodataToFMP(b.getId(), FMPNode);

            tx.success();

            out.println(sendAck());

        }

    } catch (ParserConfigurationException ex) {
        Logger.getLogger(FarmManagementPlanController.class.getName()).log(Level.SEVERE, null, ex);
        tx.failure();
    } catch (SAXException ex) {
        tx.failure();
        Logger.getLogger(FarmManagementPlanController.class.getName()).log(Level.SEVERE, null, ex);
    } finally {

        tx.finish();
    }
}

From source file:org.eclipse.lyo.oslc.am.resource.ResourceService.java

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

    boolean isFileUpload = ServletFileUpload.isMultipartContent(request);
    String contentType = request.getContentType();

    if (!isFileUpload && (RioStore.rdfFormatFromContentType(contentType) == null)) {
        throw new RioServiceException(IConstants.SC_UNSUPPORTED_MEDIA_TYPE);
    }/*  w  w w  .ja va 2s .  c o m*/

    InputStream content = request.getInputStream();

    if (isFileUpload) {
        // being uploaded from a web page
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(request);

            // find the first (and only) file resource in the post
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (item.isFormField()) {
                    // this is a form field, maybe we can accept a title or descr?
                } else {
                    content = item.getInputStream();
                    contentType = item.getContentType();
                }
            }

        } catch (Exception e) {
            throw new RioServiceException(e);
        }
    }

    RioStore store = this.getStore();
    if (RioStore.rdfFormatFromContentType(contentType) != null) {
        try {
            String resUri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            Resource resource = new Resource(resUri);
            List<RioStatement> statements = store.parse(resUri, content, contentType);
            resource.addStatements(statements);
            String userUri = getUserUri(request.getRemoteUser());

            // if it parsed, then add it to the store.
            store.update(resource, userUri);

            // now get it back, to find 
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (RioServerException e) {
            throw new RioServiceException(IConstants.SC_BAD, e);
        }
    } else if (IAmConstants.CT_APP_X_VND_MSPPT.equals(contentType) || isFileUpload) {
        try {

            ByteArrayInputStream bais = isToBais(content);

            String uri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            Resource resource = new Resource(uri);
            resource.addRdfType(IAmConstants.OSLC_AM_TYPE_RESOURCE);
            resource.addRdfType(IAmConstants.RIO_AM_PPT_DECK);
            String id = resource.getIdentifier();
            String deckTitle = "PPT Deck " + id;
            resource.setTitle(deckTitle);
            resource.setDescription("A Power Point Deck");
            String sourceUri = getBaseUrl() + '/' + IAmConstants.SERVICE_SOURCE + '/' + id;
            resource.setSource(sourceUri);
            resource.setSourceContentType(contentType);
            String userUri = getUserUri(request.getRemoteUser());

            store.storeBinaryResource(bais, id);
            bais.reset();

            SlideShow ppt = new SlideShow(bais);
            Dimension pgsize = ppt.getPageSize();

            Slide[] slide = ppt.getSlides();
            for (int i = 0; i < slide.length; i++) {
                String slideTitle = extractTitle(slide[i]);
                String slideUri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
                Resource slideResource = new Resource(slideUri);
                slideResource.addRdfType(IAmConstants.OSLC_AM_TYPE_RESOURCE);
                slideResource.addRdfType(IAmConstants.RIO_AM_PPT_SLIDE);
                String slideId = slideResource.getIdentifier();
                slideResource.setTitle(slideTitle);
                sourceUri = getBaseUrl() + '/' + IAmConstants.SERVICE_SOURCE + '/' + slideId;
                slideResource.setSource(sourceUri);
                slideResource.setSourceContentType(IConstants.CT_IMAGE_PNG);
                store.update(slideResource, userUri);

                BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                slide[i].draw(graphics);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                javax.imageio.ImageIO.write(img, "png", out);
                ByteArrayInputStream is = new ByteArrayInputStream(out.toByteArray());
                store.storeBinaryResource(is, slideId);
                out.close();
                is.close();
                try {
                    RioValue v = new RioValue(RioValueType.URI, slideResource.getUri());
                    resource.appendToSeq(IConstants.RIO_NAMESPACE + "slides", v);
                } catch (UnrecognizedValueTypeException e) {
                    // log this?  don't want to throw away everything, since this should never happen
                }
            }

            store.update(resource, userUri);

            // now get it back, to find eTag and creator stuff
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (RioServerException e) {
            throw new RioServiceException(IConstants.SC_BAD, e);
        }

    } else {
        // must be a binary or unknown format, treat as black box
        // normally a service provider will understand this and parse it appropriately
        // however this server will accept any blank box resource

        try {
            String uri = store.nextAvailableUri(IAmConstants.SERVICE_RESOURCE);
            Resource resource = new Resource(uri);
            String id = resource.getIdentifier();
            resource.setTitle("Resource " + id);
            resource.setDescription("A binary resource");
            String sourceUri = getBaseUrl() + IAmConstants.SERVICE_SOURCE + '/' + id;
            resource.setSource(sourceUri);
            resource.setSourceContentType(contentType);
            String userUri = getUserUri(request.getRemoteUser());
            store.update(resource, userUri);

            store.storeBinaryResource(content, id);

            // now get it back, to find eTag and creator stuff
            OslcResource returnedResource = store.getOslcResource(resource.getUri());
            Date created = returnedResource.getCreated();
            String eTag = returnedResource.getETag();

            response.setStatus(IConstants.SC_CREATED);
            response.setHeader(IConstants.HDR_LOCATION, resource.getUri());
            response.setHeader(IConstants.HDR_LAST_MODIFIED, StringUtils.rfc2822(created));
            response.setHeader(IConstants.HDR_ETAG, eTag);

        } catch (RioServerException e) {
            throw new RioServiceException(IConstants.SC_BAD, e);
        }
    }
}

From source file:org.apache.wookie.proxy.ProxyClient.java

@SuppressWarnings("unchecked")
public ProxyClient(HttpServletRequest request) {
    //        Properties systemProperties = System.getProperties();
    //        systemProperties.setProperty("http.proxyHost", "wwwcache.open.ac.uk");
    //        systemProperties.setProperty("http.proxyPort", "80");
    String proxyUserName = request.getParameter("username");
    String proxyPassword = request.getParameter("password");
    String base64Auth = request.getHeader("Authorization");
    if (proxyUserName != null && proxyPassword != null) {
        this.setProxyAuthConfig(proxyUserName, proxyPassword);
    }/*from  w ww.  j  ava 2 s.c om*/
    if (base64Auth != null) {
        this.setBase64AuthConfig(base64Auth);
    }
    filterParameters(request.getParameterMap());
    fContentType = request.getContentType();
}