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:admin.controller.ServletUpdateFonts.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w ww. jav  a2s.  c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String filePath = null;
    String fileName = null, fieldName = null, uploadPath = null, deletePath = null, file_name_to_delete = "";
    RequestDispatcher request_dispatcher;
    String fontname = null, fontid = null, lookid;

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        uploadPath = AppConstants.BASE_FONT_UPLOAD_PATH;
        deletePath = AppConstants.BASE_FONT_UPLOAD_PATH;
        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(AppConstants.TMP_FOLDER));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    if (fieldName.equals("fontname")) {
                        fontname = fi.getString();
                    }
                    if (fieldName.equals("fontid")) {
                        fontid = fi.getString();
                        file_name_to_delete = font.getFileName(Integer.parseInt(fontid));
                    }

                } else {
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();
                    if (fileName != "") {

                        File uploadDir = new File(uploadPath);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        String file_path = uploadPath + File.separator + fileName;
                        String delete_path = deletePath + File.separator + file_name_to_delete;
                        File deleteFile = new File(delete_path);
                        deleteFile.delete();
                        File storeFile = new File(file_path);
                        fi.write(storeFile);
                        out.println("Uploaded Filename: " + filePath + "<br>");
                    }
                }
            }
            font.changeFont(Integer.parseInt(fontid), fontname, fileName);
            response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp");
            out.println("</body>");
            out.println("</html>");
        } else {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while Updating fonts", ex);
    } finally {
        try {
            out.close();
        } catch (Exception e) {
        }
    }

}

From source file:org.openrdf.http.server.repository.transaction.TransactionController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    ModelAndView result;/*from  w ww  .  j  av  a2 s.  c  o  m*/

    String reqMethod = request.getMethod();
    UUID transactionId = getTransactionID(request);
    logger.debug("transaction id: {}", transactionId);
    logger.debug("request content type: {}", request.getContentType());
    RepositoryConnection connection = ActiveTransactionRegistry.INSTANCE
            .getTransactionConnection(transactionId);

    if (connection == null) {
        logger.warn("could not find connection for transaction id {}", transactionId);
        throw new ClientHTTPException(SC_BAD_REQUEST,
                "unable to find registerd connection for transaction id '" + transactionId + "'");
    }

    // if no action is specified in the request, it's a rollback (since it's
    // the only txn operation that does not require the action parameter).
    final String actionParam = request.getParameter(Protocol.ACTION_PARAM_NAME);
    final Action action = actionParam != null ? Action.valueOf(actionParam) : Action.ROLLBACK;
    switch (action) {
    case QUERY:
        // TODO SES-2238 note that we allow POST requests for backward
        // compatibility reasons with earlier
        // 2.8.x releases, even though according to the protocol spec only
        // PUT is allowed.
        if ("PUT".equals(reqMethod) || METHOD_POST.equals(reqMethod)) {
            logger.info("{} txn query request", reqMethod);
            result = processQuery(connection, transactionId, request, response);
            logger.info("{} txn query request finished", reqMethod);
        } else {
            throw new ClientHTTPException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                    "Method not allowed: " + reqMethod);
        }
        break;
    case GET:
        if ("PUT".equals(reqMethod) || METHOD_POST.equals(reqMethod)) {
            logger.info("{} txn get/export statements request", reqMethod);
            result = getExportStatementsResult(connection, transactionId, request, response);
            logger.info("{} txn get/export statements request finished", reqMethod);
        } else {
            throw new ClientHTTPException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                    "Method not allowed: " + reqMethod);
        }
        break;
    case SIZE:
        if ("PUT".equals(reqMethod) || METHOD_POST.equals(reqMethod)) {
            logger.info("{} txn size request", reqMethod);
            result = getSize(connection, transactionId, request, response);
            logger.info("{} txn size request finished", reqMethod);
        } else {
            throw new ClientHTTPException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                    "Method not allowed: " + reqMethod);
        }
        break;
    default:
        // modification operations - we can process these and then
        // immediately release the connection back to the registry.
        try {
            // TODO Action.ROLLBACK check is for backward compatibility with
            // older 2.8.x releases only. It's not in the protocol spec.
            if ("DELETE".equals(reqMethod) || (action.equals(Action.ROLLBACK)
                    && ("PUT".equals(reqMethod) || METHOD_POST.equals(reqMethod)))) {
                logger.info("transaction rollback");
                try {
                    connection.rollback();
                } finally {
                    ActiveTransactionRegistry.INSTANCE.deregister(transactionId);
                    connection.close();
                }
                result = new ModelAndView(EmptySuccessView.getInstance());
                logger.info("transaction rollback request finished.");
            } else if ("PUT".equals(reqMethod) || METHOD_POST.equals(reqMethod)) {
                // TODO filter for appropriate PUT operations
                logger.info("{} txn operation", reqMethod);
                result = processModificationOperation(connection, action, request, response);
                logger.info("PUT txn operation request finished.");
            } else {
                throw new ClientHTTPException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                        "Method not allowed: " + reqMethod);
            }
        } finally {
            ActiveTransactionRegistry.INSTANCE.returnTransactionConnection(transactionId);
        }
        break;
    }
    return result;
}

From source file:com.intbit.ServletModel.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww  w .  j  a  v  a2s.c  o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        look = new Looks();
        //            uploadXmlPath = getServletContext().getRealPath("") + "/model";
        uploadPath = AppConstants.BASE_MODEL_PATH;

        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(AppConstants.TMP_FOLDER));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    if (fieldName.equals("organization")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("users")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("categories")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("mapper")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("layout")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("mail")) {
                        lookName = fi.getString();
                    }
                    if (fieldName.equals("socialmedia")) {
                        lookName = fi.getString();
                    }

                    if (fieldName.equals("textstyle")) {
                        lookName = fi.getString();
                    }

                    if (fieldName.equals("containerstyle")) {
                        lookName = fi.getString();
                    }

                    if (fieldName.equals("element")) {
                        lookName = fi.getString();
                    }

                    String textstyleinfo = request.getParameter("textstyle");
                    String containerstyle = request.getParameter("containerstyle");
                    String mapfiledata = request.getParameter("element");
                    String textstylearray[] = textstyleinfo.split(",");
                    String containerstylearray[] = containerstyle.split(" ");
                    String mapfiledataarray[] = mapfiledata.split(",");
                    //        String image = request.getParameter("image");
                    logger.log(Level.INFO, containerstyle);

                    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

                    // root elements
                    Document doc = docBuilder.newDocument();
                    Element rootElement = doc.createElement("layout");
                    doc.appendChild(rootElement);

                    Document doc1 = docBuilder.newDocument();
                    Element rootElement1 = doc1.createElement("models");
                    doc1.appendChild(rootElement1);

                    Element container = doc.createElement("container");
                    rootElement.appendChild(container);

                    //                        for (int i = 0; i <= containerstylearray.length - 1; i++) {
                    //                            String v[] = containerstylearray[i].split(":");
                    //                            Attr attr = doc.createAttribute(v[0]);
                    //                            attr.setValue("" + v[1]);
                    //                            container.setAttributeNode(attr);
                    //                        }
                    //
                    //                        // staff elements
                    //                        for (int i = 0; i <= textstylearray.length - 1; i++) {
                    //                            Element element = doc.createElement("element");
                    //                            rootElement.appendChild(element);
                    //                            String field1[] = textstylearray[i].split(" ");
                    //                            for (int j = 0; j <= field1.length - 1; j++) {
                    //                                String field2[] = field1[j].split(":");
                    //                                for (int k = 0; k < field2.length - 1; k++) {
                    //                                    Attr attr = doc.createAttribute(field2[0]);
                    //                                    attr.setValue("" + field2[1]);
                    //                                    element.setAttributeNode(attr);
                    //                                }
                    //                            }
                    //                        }
                    //
                    //            //            for mapper xml file
                    //                        for (int i = 0; i <= mapfiledataarray.length - 1; i++) {
                    //                            Element element1 = doc1.createElement("model");
                    //                            rootElement1.appendChild(element1);
                    //                            String field1[] = mapfiledataarray[i].split(" ");
                    //                            for (int j = 0; j <= field1.length - 1; j++) {
                    //                                String field2[] = field1[j].split(":");
                    //                                for (int k = 0; k < field2.length - 1; k++) {
                    //                                    Attr attr = doc1.createAttribute(field2[k]);
                    //                                    attr.setValue("" + field2[1]);
                    //                                    element1.setAttributeNode(attr);
                    //                                }
                    //                            }
                    //                        }

                    // write the content into xml file
                    //                        TransformerFactory transformerFactory = TransformerFactory.newInstance();
                    //                        Transformer transformer = transformerFactory.newTransformer();
                    //                        DOMSource source = new DOMSource(doc);
                    //                        StreamResult result = new StreamResult(new File(uploadPath +File.separator + layoutfilename + ".xml"));
                    //
                    //                        TransformerFactory transformerFactory1 = TransformerFactory.newInstance();
                    //                        Transformer transformer1 = transformerFactory1.newTransformer();
                    //                        DOMSource source1 = new DOMSource(doc1);
                    //                        StreamResult result1 = new StreamResult(new File(uploadPath +File.separator + mapperfilename + ".xml"));

                    // Output to console for testing
                    // StreamResult result = new StreamResult(System.out);
                    //                        transformer.transform(source, result);
                    //                        transformer1.transform(source1, result1);
                    //                        layout.addLayouts(organization_id , user_id, category_id, layoutfilename, mapperfilename, type_email, type_social);

                } else {
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();

                    File uploadDir = new File(uploadPath);
                    if (!uploadDir.exists()) {
                        uploadDir.mkdirs();
                    }

                    int inStr = fileName.indexOf(".");
                    String Str = fileName.substring(0, inStr);

                    fileName = lookName + "_" + Str + ".png";
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();

                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);

                    fi.write(storeFile);

                    out.println("Uploaded Filename: " + filePath + "<br>");
                }
            }
            //                look.addLooks(lookName, fileName);
            response.sendRedirect(request.getContextPath() + "/admin/looks.jsp");
            //                        request_dispatcher = request.getRequestDispatcher("/admin/looks.jsp");
            //                        request_dispatcher.forward(request, response);
            out.println("</body>");
            out.println("</html>");
        } else {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet upload</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<p>No file uploaded</p>");
            out.println("</body>");
            out.println("</html>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, util.Utility.logMessage(ex, "Exception while updating org name:",
                getSqlMethodsInstance().error));
        out.println(getSqlMethodsInstance().error);
    } finally {
        out.close();
    }

}

From source file:org.opencastproject.manager.system.workflow.WorkflowManager.java

/**
 * Handles the workflow's operations.//from ww  w.ja  v  a 2s .c  o  m
 *
 * @param request
 * @param response
 * @throws TransformerException
 * @throws ServletException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
public void handleWorkflowOperations(HttpServletRequest request, HttpServletResponse response)
        throws TransformerException, ServletException, ParserConfigurationException, SAXException, IOException {

    String contentTyp = "text/xml; charset=UTF-8";
    String newWorkflowFile = request.getParameter("new_workflow_file");
    String deleteWorkflowFile = request.getParameter("delete_workflow_file");

    if (newWorkflowFile != null) {
        try {
            createNewWorkflowFile(newWorkflowFile);
        } catch (TransformerException e) {
        }
    }

    if (deleteWorkflowFile != null) {
        try {
            deleteWorkflowFile(deleteWorkflowFile);
        } catch (TransformerException e) {
        }
    }

    if (contentTyp.contains(request.getContentType())) {

        try {
            handleNewWorkflowFile(request, response);
        } catch (TransformerException e) {
        } catch (ParserConfigurationException e) {
        } catch (SAXException e) {
        }
    }

    if (request.getParameter("workflow_file") != null) {
        handleWorkflowFiles(request, response);
    }
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same content POST
 * data (JSON, XML, etc.) as was sent in the given {@link javax.servlet.http.HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are
 *                               configuring to send a standard POST request
 * @param httpServletRequest     The {@link javax.servlet.http.HttpServletRequest} that contains
 *                               the POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod}
 *//*from w ww.  j a v  a 2 s . c  o m*/
private void handleContentPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws IOException, ServletException {
    StringBuilder content = new StringBuilder();
    BufferedReader reader = httpServletRequest.getReader();
    for (;;) {
        String line = reader.readLine();
        if (line == null)
            break;
        content.append(line);
    }

    String contentType = httpServletRequest.getContentType();
    String postContent = content.toString();

    if (contentType.startsWith("text/x-gwt-rpc")) {
        String clientHost = httpServletRequest.getLocalName();
        if (clientHost.equals("127.0.0.1")) {
            clientHost = "localhost";
        }

        int clientPort = httpServletRequest.getLocalPort();
        String clientUrl = clientHost + ((clientPort != 80) ? ":" + clientPort : "");
        String serverUrl = stringProxyHost + ((intProxyPort != 80) ? ":" + intProxyPort : "")
                + httpServletRequest.getServletPath();
        //debug("Replacing client (" + clientUrl + ") with server (" + serverUrl + ")");
        postContent = postContent.replace(clientUrl, serverUrl);
    }

    String encoding = httpServletRequest.getCharacterEncoding();
    debug("POST Content Type: " + contentType + " Encoding: " + encoding, "Content: " + postContent);
    StringRequestEntity entity;
    try {
        entity = new StringRequestEntity(postContent, contentType, encoding);
    } catch (UnsupportedEncodingException e) {
        throw new ServletException(e);
    }
    // Set the proxy request POST data
    postMethodProxyRequest.setRequestEntity(entity);
}

From source file:com.ibm.liberty.starter.api.v1.LibertyFileUploader.java

private boolean isValidRequest(HttpServletRequest req, HttpServletResponse resp, String tech, String wsId,
        Collection<Part> parts, ServiceConnector sc, HashMap<Part, String> fileNames) throws IOException {
    if (tech == null || tech.trim().isEmpty() || !PatternValidation.checkPattern(PatternType.TECH, tech)) {
        log.log(Level.INFO, "Invalid tech parameter");
        resp.sendError(400, "Invalid request: specify valid tech");
        return false;
    }//  w  w w. jav a2  s.c  o  m
    if (sc.getServiceObjectFromId(tech) == null) {
        log.log(Level.INFO, "Invalid tech type: " + tech);
        resp.sendError(400, "Invalid technology type : " + tech);
        return false;
    }

    if (wsId == null || wsId.trim().isEmpty()) {
        log.log(Level.INFO, "Invalid workspace: " + wsId);
        resp.sendError(400, "Invalid workspace : " + wsId);
        return false;
    }
    if (req.getContentType() == null || !req.getContentType().toLowerCase().contains("multipart/form-data")) {
        log.log(Level.INFO, "Invalid request type : " + req.getContentType());
        resp.sendError(400, "Invalid request type : " + req.getContentType());
        return false;
    }

    if (parts == null || parts.size() == 0) {
        log.log(Level.INFO, "No file to upload");
        resp.sendError(400, "Invalid request: specify file(s) to upload");
        return false;
    }

    for (Part filePart : parts) {
        if (filePart == null) {
            log.log(Level.INFO, "Invalid filepart :" + parts);
            resp.sendError(400, "Invalid request: filepart can not be null");
            return false;
        }

        String fileName = getSubmittedFileName(filePart);
        if (fileName == null || fileName.trim().isEmpty()) {
            log.log(Level.INFO, "File name was invalid : filePart=" + filePart);
            resp.sendError(400, "Invalid request: specify a valid file name");
            return false;
        }
        fileNames.put(filePart, fileName);
    }

    return true;
}

From source file:com.esri.gpt.control.arcims.ServletConnectorProxy.java

/**
 * Communicates with redirect url and works as a transparent proxy
 * //from  w  ww . ja  va 2  s.  c  o  m
 * @param request
 *          the servlet request
 * @param response
 *          the servlet response
 * @throws IOException
 *           if an exception occurs
 */
private void executeProxy(HttpServletRequest request, HttpServletResponse response) throws IOException {

    HttpURLConnection httpCon = null;
    URL redirectURL = null;
    InputStream input = null;
    OutputStream output = null;
    InputStream proxyInput = null;
    OutputStream proxyOutput = null;

    try {

        input = request.getInputStream();
        output = response.getOutputStream();

        String sQueryStr = request.getQueryString();
        String sAuthorization = request.getHeader("Authorization");
        String requestBody = readInputCharacters(input);
        String requestMethod = request.getMethod();
        String contentType = request.getContentType();
        String encoding = request.getCharacterEncoding();

        LOGGER.finer(" Request method = " + requestMethod);
        LOGGER.finer(" Query string = " + sQueryStr);
        LOGGER.finer(" Authorization header =" + sAuthorization);
        LOGGER.finer(" Character Encoding = " + encoding);
        LOGGER.finer(" The redirect URL is " + this._redirectURL + "?" + sQueryStr);

        redirectURL = new URL(this._redirectURL + "?" + sQueryStr);

        httpCon = (HttpURLConnection) redirectURL.openConnection();

        httpCon.setDoInput(true);
        httpCon.setDoOutput(true);
        httpCon.setUseCaches(false);
        httpCon.setRequestMethod(requestMethod);
        httpCon.setRequestProperty("Content-type", contentType);

        if (sAuthorization != null) {
            httpCon.addRequestProperty("Authorization", sAuthorization);
        }

        proxyOutput = httpCon.getOutputStream();
        send(requestBody, proxyOutput);

        String authenticateHdr = httpCon.getHeaderField("WWW-Authenticate");
        if (authenticateHdr != null) {
            LOGGER.finer(" WWW-Authenticate : " + authenticateHdr);
            response.setHeader("WWW-Authenticate",
                    StringEscapeUtils.escapeHtml4(Val.stripControls(authenticateHdr)));
        }
        LOGGER.finer(" Response Code : " + httpCon.getResponseCode());

        if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN)) {

            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR)) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } else {
            proxyInput = httpCon.getInputStream();
            send(proxyInput, output);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (input != null) {
            input.close();
        }
        if (output != null) {
            output.close();
        }
        if (proxyInput != null) {
            proxyInput.close();
        }
        if (proxyOutput != null) {
            proxyOutput.close();
        }
        if (httpCon != null) {
            httpCon.disconnect();
        }
    }
}

From source file:com.aipo.container.protocol.AipoDataServiceServlet.java

/**
 * Handler for non-batch requests.//from  ww w.  ja v a 2  s .  c o  m
 */
protected void handleSingleRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        SecurityToken token) throws IOException {

    // Always returns a non-null handler.
    RestHandler handler = getRestHandler(servletRequest);

    // Get Content-Type
    String contentType = null;

    try {
        // TODO: First implementation causes bug when Content-Type is
        // application/atom+xml. Fix is applied.
        contentType = ContentTypes.extractMimePart(servletRequest.getContentType());
    } catch (Throwable t) {
        // this happens while testing
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("Unexpected error : content type is null " + t.toString());
        }
    }

    // Get BeanConverter for Request payload.
    BeanConverter requestConverter = getConverterForRequest(contentType, null);

    // Get BeanConverter for Response body.
    BeanConverter responseConverter = getConverterForFormat(null);

    // Execute the request
    Map<String, FormDataItem> formItems = Maps.newHashMap();
    Map<String, String[]> parameterMap = loadParameters(servletRequest, formItems);
    Future<?> future = handler.execute(parameterMap, formItems, token, requestConverter);
    ResponseItem responseItem = getResponseItem(future);

    servletResponse.setContentType(responseConverter.getContentType());

    if (responseItem.getErrorCode() >= 200 && responseItem.getErrorCode() < 400) {
        Object response = responseItem.getResponse();

        if (response instanceof StreamContent) {
            InputStream is = null;
            OutputStream out = null;
            try {
                StreamContent content = (StreamContent) response;
                servletResponse.setContentType(content.getContentType());
                if (content.getContentLength() != 0) {
                    servletResponse.setContentLength(content.getContentLength());
                }
                is = content.getInputStream();
                out = servletResponse.getOutputStream();
                int b;
                while ((b = is.read()) != -1) {
                    out.write(b);
                }
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException ignore) {
                    // ignore
                }
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException ignore) {
                    // ignore
                }
            }
            return;
        }

        // TODO: ugliness resulting from not using RestfulItem
        if (!(response instanceof DataCollection) && !(response instanceof RestfulCollection)) {
            response = ImmutableMap.of("entry", response);
        }

        // JSONP style callbacks
        String callback = (HttpUtil.isJSONP(servletRequest)
                && ContentTypes.OUTPUT_JSON_CONTENT_TYPE.equals(responseConverter.getContentType()))
                        ? servletRequest.getParameter("callback")
                        : null;

        PrintWriter writer = servletResponse.getWriter();
        if (callback != null) {
            writer.write(callback + '(');
        }
        writer.write(responseConverter.convertToString(response));
        if (callback != null) {
            writer.write(");\n");
        }
    } else {
        sendError(servletResponse, responseItem);
    }
}

From source file:org.jitsi.videobridge.rest.HandlerImpl.java

/**
 * Creates a new <tt>Conference</tt> in (the associated)
 * <tt>Videobridge</tt>./*from w w  w  .  j  a  v  a 2  s.  c  o  m*/
 *
 * @param baseRequest the original unwrapped {@link Request} object
 * @param request the request either as the {@code Request} object or a
 * wrapper of that request
 * @param response the response either as the {@code Response} object or a
 * wrapper of that response
 * @throws IOException
 * @throws ServletException
 */
private void doPostConferencesJSON(Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    Videobridge videobridge = getVideobridge();

    if (videobridge == null) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else if (RESTUtil.isJSONContentType(request.getContentType())) {
        Object requestJSONObject = null;
        int status = 0;

        try {
            requestJSONObject = new JSONParser().parse(request.getReader());
            if ((requestJSONObject == null) || !(requestJSONObject instanceof JSONObject)) {
                status = HttpServletResponse.SC_BAD_REQUEST;
            }
        } catch (ParseException pe) {
            status = HttpServletResponse.SC_BAD_REQUEST;
        }
        if (status == 0) {
            ColibriConferenceIQ requestConferenceIQ = JSONDeserializer
                    .deserializeConference((JSONObject) requestJSONObject);

            if ((requestConferenceIQ == null) || (requestConferenceIQ.getID() != null)) {
                status = HttpServletResponse.SC_BAD_REQUEST;
            } else {
                ColibriConferenceIQ responseConferenceIQ = null;

                try {
                    IQ responseIQ = videobridge.handleColibriConferenceIQ(requestConferenceIQ,
                            Videobridge.OPTION_ALLOW_NO_FOCUS);

                    if (responseIQ instanceof ColibriConferenceIQ) {
                        responseConferenceIQ = (ColibriConferenceIQ) responseIQ;
                    } else {
                        status = getHttpStatusCodeForResultIq(responseIQ);
                    }
                } catch (Exception e) {
                    status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                }
                if (status == 0 && responseConferenceIQ != null) {
                    JSONObject responseJSONObject = JSONSerializer.serializeConference(responseConferenceIQ);

                    if (responseJSONObject == null)
                        responseJSONObject = new JSONObject();

                    response.setStatus(HttpServletResponse.SC_OK);
                    responseJSONObject.writeJSONString(response.getWriter());
                }
            }
        }
        if (status != 0)
            response.setStatus(status);
    } else {
        response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
    }
}

From source file:org.jitsi.videobridge.rest.HandlerImpl.java

private void doPostShutdownJSON(Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    Videobridge videobridge = getVideobridge();

    if (videobridge == null) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return;//from w w  w  .  jav  a2 s  .  c o m
    }

    if (!RESTUtil.isJSONContentType(request.getContentType())) {
        response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        return;
    }

    Object requestJSONObject;
    int status;

    try {
        requestJSONObject = new JSONParser().parse(request.getReader());
        if ((requestJSONObject == null) || !(requestJSONObject instanceof JSONObject)) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
    } catch (ParseException pe) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    ShutdownIQ requestShutdownIQ = JSONDeserializer.deserializeShutdownIQ((JSONObject) requestJSONObject);

    if ((requestShutdownIQ == null)) {
        status = HttpServletResponse.SC_BAD_REQUEST;
    } else {
        // Fill source address
        String ipAddress = request.getHeader("X-FORWARDED-FOR");
        if (ipAddress == null) {
            ipAddress = request.getRemoteAddr();
        }

        requestShutdownIQ.setFrom(ipAddress);

        try {
            IQ responseIQ = videobridge.handleShutdownIQ(requestShutdownIQ);

            if (IQ.Type.RESULT.equals(responseIQ.getType())) {
                status = HttpServletResponse.SC_OK;
            } else {
                status = getHttpStatusCodeForResultIq(responseIQ);
            }
        } catch (Exception e) {
            logger.error("Error while trying to handle shutdown request", e);
            status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        }
    }
    response.setStatus(status);
}