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:pe.edu.upeu.application.web.controller.CVacaciones.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww  w  .  ja va  2s. 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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    Map<String, Object> mp = new HashMap<String, Object>();
    InterfaceDgpDAO dgp = new DgpDAO();
    ContratoDAO cD = new ContratoDAO();
    VacacionDAO vC = new VacacionDAO();

    InterfaceVacacionesDAO vaca = new VacacionDAO();
    DocumentoDAO d = new DocumentoDAO();
    Detalle_VacacionDAO Dvac = new Detalle_VacacionDAO();
    HttpSession sesion = request.getSession(true);
    String iddir = (String) sesion.getAttribute("IDDIR");
    String iddep = (String) sesion.getAttribute("DEPARTAMENTO_ID");
    String user = (String) sesion.getAttribute("IDUSER");
    String contentType = request.getContentType();
    System.out.println("contentType = " + contentType);

    boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Check that we have a file upload request
    System.out.println("isMultipart = " + isMultipart);
    if (isMultipart) {

        String opc = request.getParameter("opc");// Retrieves all text inputs
        if (opc.equals("asign")) {
            Part filePart = request.getPart("docadj"); // Retrieves <input type="file" name="file">
            response.setContentType("application/json;charset=UTF-8");
            String idcon = (String) sesion.getAttribute("id_con_vac");
            System.out.println(opc);
            String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
            System.out.println(fileName);

            String renombre_archivo = null;
            Calendar fecha = new GregorianCalendar();
            int hora = fecha.get(Calendar.HOUR_OF_DAY);
            int min = fecha.get(Calendar.MINUTE);
            int sec = fecha.get(Calendar.SECOND);
            renombre_archivo = String.valueOf(hora) + String.valueOf(min) + String.valueOf(sec) + "_" + idcon
                    + "_" + fileName.toUpperCase();
            System.out.println(renombre_archivo);

            //           String ubicacionArchivo = "";
            //           ubicacionArchivo = FactoryConnectionDB.url + "Archivo/";
            //                // ubicacion = getServletContext().getRealPath(".").substring(0, getServletContext().getRealPath(".").length() - 11) + "web\\Vista\\Usuario\\Fotos";
            //                DiskFileItemFactory f = new DiskFileItemFactory();
            //                f.setSizeThreshold(1024);
            //                f.setRepository(new File(ubicacionArchivo));
            //                ServletFileUpload upload = new ServletFileUpload(f);
            String Descripcion = request.getParameter("dest");
            String Estado = request.getParameter("est");
            System.out.println(Descripcion);
            System.out.println(Estado);
            String iddaj = d.INSERT_DOCUMENTO_ADJUNTO(null, iddep, "1", user, null, null, null, null,
                    Descripcion, null, Estado, idcon).trim();

            System.out.println(iddaj);
            d.INSERT_ARCHIVO_DOCUMENTO(null, iddaj, renombre_archivo, fileName, null);
            String idvac = vC.insert_vacation(iddaj, idcon);
            //  System.out.println("idvac: "+idvac);
            //  System.out.println("iddaj: "+iddaj);
            //  System.out.println("idcon: "+idcon);
            if (idcon != null) {
                System.out.println("aaaa:" + idvac);
                mp.put("info", idvac);
            } else {
                mp.put("info", "-1");
            }
            Gson gson = new Gson();
            out.println(gson.toJson(mp));
            out.flush();
            out.close();
        }

    } else {
        String opc = request.getParameter("opc");
        if (opc.equals("rolrequest")) {
            response.setContentType("application/json;charset=UTF-8");
            String idrol = (String) sesion.getAttribute("IDROL");
            System.out.println(idrol);
            mp.put("idrol", idrol);
            Gson gson = new Gson();
            out.println(gson.toJson(mp));
            out.flush();
            out.close();
        }
        if (opc.equals("Listar")) {
            response.sendRedirect("Vista/Vacaciones/Lista_Empleados.jsp");
        }
        if (opc.equals("listartadm")) {
            response.sendRedirect("Vista/Vacaciones/List_Trab_Adm.jsp");
        }
        if (opc.equals("listaraut")) {
            response.sendRedirect("Vista/Vacaciones/List_Trab_Adm.jsp");
        }
        if (opc.equals("listTA")) {
            response.setContentType("application/json;charset=UTF-8");
            System.out.println("llega");
            mp.put("aptos", vC.trabajadoresapt());
            Gson gson = new Gson();
            out.println(gson.toJson(mp));
            out.flush();
            out.close();
        }
        if (opc.equals("listadm")) {
            response.setContentType("application/json;charset=UTF-8");
            String idep = (String) sesion.getAttribute("DEPARTAMENTO_ID");
            mp.put("adm", vC.trabajadoresadm(idep));
            Gson gson = new Gson();

            out.println(gson.toJson(mp));
            out.flush();

            out.close();
        }
        if (opc.equals("listToAut")) {
            response.setContentType("application/json;charset=UTF-8");
            String idep = (String) sesion.getAttribute("DEPARTAMENTO_ID");
            mp.put("adm", vC.ListToAut(idep));
            Gson gson = new Gson();

            out.println(gson.toJson(mp));
            out.flush();

            out.close();
        }
        if (opc.equals("AutorizAN")) {
            response.setContentType("application/json;charset=UTF-8");
            String[] id_au = request.getParameterValues("AutorizAN");
            List<String> list = new ArrayList<String>();
            for (int i = 0; i < id_au.length; i++) {
                list.add(id_au[i]);
            }
            boolean a = vC.admitirV(list);
            if (a) {
                response.sendRedirect("Vista/Vacaciones/Lista_Empleados.jsp");
                //ok
            } else {
                //error
            }
            //System.out.println(a);
            /*sesion.setAttribute("lista", list);
             response.sendRedirect("Vista/Contrato/Formato_Plantilla/Impresion_Masiva.jsp");*/
        }
        if (opc.equals("sendcon")) {
            String idcon = request.getParameter("idcon");
            System.out.println(idcon);
            sesion.setAttribute("id_con_vac", idcon);
            response.sendRedirect("Vista/Vacaciones/prog_vacaciones.jsp");
        }
        if (opc.equals("get_info_trab")) {
            response.setContentType("application/json;charset=UTF-8");
            System.out.println("hola que hace");
            System.out.println("ola k ase");
            String idcon = (String) sesion.getAttribute("id_con_vac");
            System.out.println(idcon);
            if (idcon != null) {
                mp.put("info", vC.get_info_trab(idcon));
            } else {
                mp.put("info", "-1");
            }
            Gson gson = new Gson();

            out.println(gson.toJson(mp));
            out.flush();

            out.close();
        }

        if (opc.equals("Procesar")) {
            String iddgp = "";
            String idpro = "";
            try {
                iddgp = CCriptografiar.Desencriptar(request.getParameter("dgp"));
                idpro = CCriptografiar.Desencriptar(request.getParameter("proceso"));
            } catch (Exception ex) {
                System.out.println("Error: " + ex);
            }
            if (iddgp.equals("") && idpro.equals("")) {
                vaca.PROCESAR_VACACIONES(idpro, iddgp);
            }
            response.sendRedirect("Vista/Vacaciones/Proceso_Vacacion.jsp");
            mp.put("rpta", true);

        }
        if (opc.equals("listEsVacaciones")) {
            mp.put("list", dgp.LIST_DGP_PROCESO(iddep, "", true));
        }

        //             if (opc.equals("asign")) {
        //                 response.setContentType("application/json;charset=UTF-8");
        //                 String idcon = (String) sesion.getAttribute("id_con_vac");
        //                 String idvac = "DOC-0002";
        //                 if (idcon != null) {
        //                   mp.put("info", idvac);
        //                } else {
        //                    mp.put("info", "-1");
        //                }
        //                Gson gson = new Gson();
        // 
        //                 out.println(gson.toJson(mp));
        //                 out.flush();
        // 
        //                 out.close();
        //              }
        if (opc.equals("asigndv")) {

            String idDetvac = null;
            String fedesde = request.getParameter("from");
            String fehasta = request.getParameter("to");
            //String idvacacion = "1";
            String idvacacion = request.getParameter("idvac");
            // System.out.println(idvacacion);
            System.out.println(fedesde + " " + fehasta + " " + idvacacion);
            Detalle_VacacionDAO MoDet_Vac = new Detalle_VacacionDAO();
            Detalle_Vacacion Detv = new Detalle_Vacacion();

            Detv.setIddetalle(null);
            Detv.setFe_inicio(fedesde);
            Detv.setFe_fin(fehasta);
            Detv.setIdvacacion(idvacacion);

            //
            //                Dvac.insert(MoDet_Vac);

            MoDet_Vac.insert(Detv);
            // sesion.setAttribute("List_Usuario_var", usu.List_Usuario_var());

            response.setContentType("application/json;charset=UTF-8");

            Gson gson = new Gson();
            out.println(gson.toJson(mp));
            out.flush();
            out.close();
        }
    }

    try {

    } finally {
        out.close();
    }
}

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

@SuppressWarnings({ "unchecked", "rawtypes" })
private Map<String, String[]> loadParameters(HttpServletRequest servletRequest,
        Map<String, FormDataItem> formItems) {
    Map<String, String[]> parameterMap = new HashMap<String, String[]>();

    // requestParameter???
    Map<String, String[]> map = servletRequest.getParameterMap();
    for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();
        String key = (String) entry.getKey();
        String[] _value = (String[]) entry.getValue();
        String[] value = new String[_value.length];
        for (int i = 0; i < _value.length; i++) {
            value[i] = _value[i];/*  w  ww .  j av a 2  s . co  m*/
        }
        parameterMap.put(key, value);
    }

    if (servletRequest.getContentType() != null) {
        // Content-type?multipart/form-data??????
        if (ContentTypes.MULTIPART_FORM_CONTENT_TYPE
                .equals(ContentTypes.extractMimePart(servletRequest.getContentType()))) {
            if (formParser.isMultipartContent(servletRequest)) {
                Collection<FormDataItem> items = null;
                try {
                    items = formParser.parse(servletRequest);
                } catch (IOException e) {
                    // ignore
                }
                if (items != null) {
                    for (FormDataItem item : items) {
                        if (item.isFormField()) {
                            String value = item.getAsString();
                            String key = item.getFieldName();
                            if (value != null) {
                                try {
                                    value = new String(value.getBytes("iso-8859-1"), "utf-8");
                                } catch (UnsupportedEncodingException e) {
                                    // ignore
                                }
                            }
                            String[] valueArray = { value };
                            if (parameterMap.containsKey(key)) {
                                String[] preValue = parameterMap.get(key);
                                valueArray = Arrays.copyOf(preValue, preValue.length + 1);
                                valueArray[preValue.length] = value;
                            }
                            parameterMap.put(key, valueArray);
                        } else {
                            formItems.put(item.getFieldName(), item);
                        }
                    }
                }
            }

        }

        // Content-type?application/x-www-form-urlencoded??????
        if ("application/x-www-form-urlencoded"
                .equals(ContentTypes.extractMimePart(servletRequest.getContentType()))) {
            try {
                List<NameValuePair> params = URLEncodedUtils
                        .parse(new URI("http://localhost:8080?" + getBodyAsString(servletRequest)), "UTF-8");
                for (NameValuePair param : params) {
                    String[] valueArray = { param.getValue() };
                    if (parameterMap.containsKey(param.getName())) {
                        String[] preValue = parameterMap.get(param.getName());
                        valueArray = Arrays.copyOf(preValue, preValue.length + 1);
                        valueArray[preValue.length] = param.getValue();
                    }
                    parameterMap.put(param.getName(), valueArray);
                }
            } catch (URISyntaxException e) {
                // ignore
            }
        }
    }

    return parameterMap;
}

From source file:com.castlemock.web.mock.rest.web.rest.controller.AbstractRestServiceController.java

/**
 * The method prepares an request//ww w . j ava2  s.  c om
 * @param projectId The id of the project that the incoming request belongs to
 * @param applicationId The id of the application that the incoming request belongs to
 * @param httpMethod The HTTP method that should be mocked, such as GET or POST
 * @param httpServletRequest The incoming request
 * @return A new created project
 */
protected RestRequestDto prepareRequest(final String projectId, final String applicationId,
        final HttpMethod httpMethod, final HttpServletRequest httpServletRequest) {
    final RestRequestDto request = new RestRequestDto();
    final String body = RestMessageSupport.getBody(httpServletRequest);
    final String incomingRequestUri = httpServletRequest.getRequestURI();
    final String restResourceUri = incomingRequestUri.replace(getContext() + SLASH + MOCK + SLASH + REST + SLASH
            + PROJECT + SLASH + projectId + SLASH + APPLICATION + SLASH + applicationId, EMPTY);
    final List<HttpParameterDto> httpParameters = HttpMessageSupport.extractParameters(httpServletRequest);
    final List<HttpHeaderDto> httpHeaders = HttpMessageSupport.extractHttpHeaders(httpServletRequest);

    request.setHttpMethod(httpMethod);
    request.setBody(body);
    request.setUri(restResourceUri);
    request.setHttpParameters(httpParameters);
    request.setHttpHeaders(httpHeaders);
    request.setContentType(httpServletRequest.getContentType());
    return request;
}

From source file:org.georchestra.security.Proxy.java

private boolean isFormContentType(HttpServletRequest request) {
    if (request.getContentType() == null) {
        return false;
    }// w ww . j av  a 2 s .  co  m
    String contentType = request.getContentType().split(";")[0].trim();

    boolean equalsIgnoreCase = "application/x-www-form-urlencoded".equalsIgnoreCase(contentType);
    return equalsIgnoreCase;
}

From source file:org.sakaiproject.sdata.tool.JCRHandler.java

@Override
public void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from ww  w  . j ava 2  s  .  c om
        snoopRequest(request);

        ResourceDefinition rp = resourceDefinitionFactory.getSpec(request);
        String mimeType = ContentTypes.getContentType(rp.getRepositoryPath(), request.getContentType());
        String charEncoding = null;
        if (mimeType.startsWith("text")) {
            charEncoding = request.getCharacterEncoding();
        }
        Node n = jcrNodeFactory.getNode(rp.getRepositoryPath());
        boolean created = false;
        if (n == null) {
            n = jcrNodeFactory.createFile(rp.getRepositoryPath(), mimeType);
            created = true;
            if (n == null) {
                throw new RuntimeException(
                        "Failed to create node at " + rp.getRepositoryPath() + " type " + JCRConstants.NT_FILE);
            }
        } else {
            NodeType nt = n.getPrimaryNodeType();
            if (!JCRConstants.NT_FILE.equals(nt.getName())) {
                response.reset();
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Content Can only be put to a file, resource type is " + nt.getName());
                return;
            }
        }

        GregorianCalendar gc = new GregorianCalendar();
        long lastMod = request.getDateHeader(LAST_MODIFIED);
        if (lastMod > 0) {
            gc.setTimeInMillis(lastMod);
        } else {
            gc.setTime(new Date());
        }

        InputStream in = request.getInputStream();
        saveStream(n, in, mimeType, charEncoding, gc);

        in.close();
        if (created) {
            response.setStatus(HttpServletResponse.SC_CREATED);
        } else {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    } catch (UnauthorizedException ape) {
        // catch any Unauthorized exceptions and send a 401
        response.reset();
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, ape.getMessage());
    } catch (PermissionDeniedException pde) {
        // catch any permission denied exceptions, and send a 403
        response.reset();
        response.sendError(HttpServletResponse.SC_FORBIDDEN, pde.getMessage());
    } catch (SDataException e) {
        sendError(request, response, e);
        LOG.error("Failed  To service Request " + e.getMessage());
    } catch (Exception e) {
        sendError(request, response, e);
        snoopRequest(request);
        LOG.error("Failed  TO service Request ", e);
    }
}

From source file:org.dspace.submit.step.UploadStep.java

/**
 * Do any processing of the information input by the user, and/or perform
 * step processing (if no user interaction required)
 * <P>//from   w ww .j a v a2s.com
 * It is this method's job to save any data to the underlying database, as
 * necessary, and return error messages (if any) which can then be processed
 * by the appropriate user interface (JSP-UI or XML-UI)
 * <P>
 * NOTE: If this step is a non-interactive step (i.e. requires no UI), then
 * it should perform *all* of its processing in this method!
 * 
 * @param context
 *     The relevant DSpace Context.
 * @param request
 *     Servlet's HTTP request object.
 * @param response
 *     Servlet's HTTP response object.
 * @param subInfo
 *     submission info object
 * @return Status or error flag which will be processed by
 *     doPostProcessing() below! (if STATUS_COMPLETE or 0 is returned,
 *     no errors occurred!)
 * @throws ServletException
 *     A general exception a servlet can throw when it encounters difficulty.
 * @throws IOException
 *     A general class of exceptions produced by failed or interrupted I/O operations.
 * @throws SQLException
 *     An exception that provides information on a database access error or other errors.
 * @throws AuthorizeException
 *     Exception indicating the current user of the context does not have permission
 *     to perform a particular action.
 */
@Override
public int doProcessing(Context context, HttpServletRequest request, HttpServletResponse response,
        SubmissionInfo subInfo) throws ServletException, IOException, SQLException, AuthorizeException {
    // get button user pressed
    String buttonPressed = Util.getSubmitButton(request, NEXT_BUTTON);

    // get reference to item
    Item item = subInfo.getSubmissionItem().getItem();

    // -----------------------------------
    // Step #0: Upload new files (if any)
    // -----------------------------------
    String contentType = request.getContentType();

    // if multipart form, then we are uploading a file
    if ((contentType != null) && (contentType.indexOf("multipart/form-data") != -1)) {
        // This is a multipart request, so it's a file upload
        // (return any status messages or errors reported)
        int status = processUploadFile(context, request, response, subInfo);

        // if error occurred, return immediately
        if (status != STATUS_COMPLETE) {
            return status;
        }
    }

    // if user pressed jump-to button in process bar,
    // return success (so that jump will occur)
    if (buttonPressed.startsWith(PROGRESS_BAR_PREFIX) || buttonPressed.startsWith(PREVIOUS_BUTTON)) {
        // check if a file is required to be uploaded
        if (fileRequired && !itemService.hasUploadedFiles(item)) {
            return STATUS_NO_FILES_ERROR;
        } else {
            return STATUS_COMPLETE;
        }
    }

    // ---------------------------------------------
    // Step #1: Check if this was just a request to
    // edit file information.
    // (or canceled editing information)
    // ---------------------------------------------
    // check if we're already editing a specific bitstream
    if (request.getParameter("bitstream_id") != null) {
        if (buttonPressed.equals(CANCEL_EDIT_BUTTON)) {
            // canceled an edit bitstream request
            subInfo.setBitstream(null);

            // this flag will just return us to the normal upload screen
            return STATUS_EDIT_COMPLETE;
        } else {
            // load info for bitstream we are editing
            Bitstream b = bitstreamService.find(context, Util.getUUIDParameter(request, "bitstream_id"));

            // save bitstream to submission info
            subInfo.setBitstream(b);
        }
    } else if (buttonPressed.startsWith("submit_edit_")) {
        // get ID of bitstream that was requested for editing
        String bitstreamID = buttonPressed.substring("submit_edit_".length());

        Bitstream b = bitstreamService.find(context, UUID.fromString(bitstreamID));

        // save bitstream to submission info
        subInfo.setBitstream(b);

        // return appropriate status flag to say we are now editing the
        // bitstream
        return STATUS_EDIT_BITSTREAM;
    }

    // ---------------------------------------------
    // Step #2: Process any remove file request(s)
    // ---------------------------------------------
    // Remove-selected requests come from Manakin
    if (buttonPressed.equalsIgnoreCase("submit_remove_selected")) {
        // this is a remove multiple request!

        if (request.getParameter("remove") != null) {
            // get all files to be removed
            String[] removeIDs = request.getParameterValues("remove");

            // remove each file in the list
            for (int i = 0; i < removeIDs.length; i++) {
                UUID id = UUID.fromString(removeIDs[i]);

                int status = processRemoveFile(context, item, id);

                // if error occurred, return immediately
                if (status != STATUS_COMPLETE) {
                    return status;
                }
            }

            // remove current bitstream from Submission Info
            subInfo.setBitstream(null);
        }
    } else if (buttonPressed.startsWith("submit_remove_")) {
        // A single file "remove" button must have been pressed

        UUID id = UUID.fromString(buttonPressed.substring(14));
        int status = processRemoveFile(context, item, id);

        // if error occurred, return immediately
        if (status != STATUS_COMPLETE) {
            return status;
        }

        // remove current bitstream from Submission Info
        subInfo.setBitstream(null);
    }

    // -------------------------------------------------
    // Step #3: Check for a change in file description
    // -------------------------------------------------
    // We have to check for descriptions from users using the resumable upload
    // and from users using the simple upload.
    // Beginning with the resumable ones.
    Enumeration<String> parameterNames = request.getParameterNames();
    Map<String, String> descriptions = new HashMap<>();
    while (parameterNames.hasMoreElements()) {
        String name = parameterNames.nextElement();
        if (StringUtils.startsWithIgnoreCase(name, "description[")) {
            descriptions.put(name.substring("description[".length(), name.length() - 1),
                    request.getParameter(name));
        }
    }
    if (!descriptions.isEmpty()) {
        // we got descriptions from the resumable upload
        if (item != null) {
            List<Bundle> bundles = itemService.getBundles(item, "ORIGINAL");
            for (Bundle bundle : bundles) {
                List<Bitstream> bitstreams = bundle.getBitstreams();
                for (Bitstream bitstream : bitstreams) {
                    if (descriptions.containsKey(bitstream.getName())) {
                        bitstream.setDescription(context, descriptions.get(bitstream.getName()));
                        bitstreamService.update(context, bitstream);
                    }
                }
            }
        }
        return STATUS_COMPLETE;
    }

    // Going on with descriptions from the simple upload
    String fileDescription = request.getParameter("description");

    if (fileDescription != null && fileDescription.length() > 0) {
        // save this file description
        int status = processSaveFileDescription(context, request, response, subInfo);

        // if error occurred, return immediately
        if (status != STATUS_COMPLETE) {
            return status;
        }
    }

    // ------------------------------------------
    // Step #4: Check for a file format change
    // (if user had to manually specify format)
    // ------------------------------------------
    int formatTypeID = Util.getIntParameter(request, "format");
    String formatDesc = request.getParameter("format_description");

    // if a format id or description was found, then save this format!
    if (formatTypeID >= 0 || (formatDesc != null && formatDesc.length() > 0)) {
        // save this specified format
        int status = processSaveFileFormat(context, request, response, subInfo);

        // if error occurred, return immediately
        if (status != STATUS_COMPLETE) {
            return status;
        }
    }

    // ---------------------------------------------------
    // Step #5: Check if primary bitstream has changed
    // -------------------------------------------------
    if (request.getParameter("primary_bitstream_id") != null) {
        List<Bundle> bundles = itemService.getBundles(item, "ORIGINAL");
        if (bundles.size() > 0) {
            bundles.get(0).setPrimaryBitstreamID(
                    bitstreamService.find(context, Util.getUUIDParameter(request, "primary_bitstream_id")));
            bundleService.update(context, bundles.get(0));
        }
    }

    // ---------------------------------------------------
    // Step #6: Determine if there is an error because no
    // files have been uploaded.
    // ---------------------------------------------------
    //check if a file is required to be uploaded
    if (fileRequired && !itemService.hasUploadedFiles(item) && !buttonPressed.equals(SUBMIT_MORE_BUTTON)) {
        return STATUS_NO_FILES_ERROR;
    }

    context.dispatchEvents();

    return STATUS_COMPLETE;
}

From source file:it.classhidra.core.controller.bsController.java

public static String getPropertyMultipart(String key, HttpServletRequest req) {

    try {/*from   ww w  .  j a  v  a  2s . c o  m*/
        String file = (String) req.getAttribute("multipart/form-data");
        DataInputStream in = null;
        String contentType = req.getContentType();
        if (contentType != null && contentType.indexOf("multipart/form-data") != -1) {
            if (file == null) {
                in = new DataInputStream(req.getInputStream());
                int formDataLength = req.getContentLength();
                byte dataBytes[] = new byte[formDataLength];
                int bytesRead = 0;
                int totalBytesRead = 0;
                while (totalBytesRead < formDataLength) {
                    bytesRead = in.read(dataBytes, totalBytesRead, formDataLength);
                    totalBytesRead += bytesRead;
                }
                file = new String(dataBytes, 0, dataBytes.length, "ASCII");
                in.close();
                req.setAttribute("multipart/form-data", file);
            }

            String check = "Content-Disposition: form-data; name=\"" + key + "\"";

            int pos = file.indexOf(check);

            if (pos > -1) {
                int pos1 = file.indexOf("-----------------------------", pos);
                if (pos1 > -1) {
                    String result = file.substring(pos + check.length(), pos1);
                    result = result.replace('\n', ' ').replace('\r', ' ');
                    return result.trim();
                }
            }
        }

    } catch (Exception e) {
        new bsControllerException(e, iStub.log_DEBUG);

        return null;
    }
    return null;
}

From source file:com.bigdata.rdf.sail.webapp.UpdateServlet.java

@Override
protected void doPut(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {

    if (!isWritable(getServletContext(), req, resp)) {
        // Service must be writable.
        return;//www  .  ja va  2s  .  c  o m
    }

    final String queryStr = req.getParameter(QueryServlet.ATTR_QUERY);

    final String contentType = req.getContentType();

    if (contentType == null) {

        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);

    }

    if (queryStr == null) {

        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);

    }

    doUpdateWithQuery(req, resp);

}

From source file:org.broadleafcommerce.core.web.api.BroadleafSpringRestExceptionMapper.java

@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public @ResponseBody ErrorWrapper handleHttpMediaTypeNotSupportedException(HttpServletRequest request,
        HttpServletResponse response, Exception ex) {
    ErrorWrapper errorWrapper = (ErrorWrapper) context.getBean(ErrorWrapper.class.getName());
    Locale locale = null;//from  w w  w  .j ava 2s.  co  m
    BroadleafRequestContext requestContext = BroadleafRequestContext.getBroadleafRequestContext();
    if (requestContext != null) {
        locale = requestContext.getJavaLocale();
    }

    LOG.error("An error occured invoking a REST service", ex);
    if (locale == null) {
        locale = Locale.getDefault();
    }
    errorWrapper.setHttpStatusCode(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE);
    response.setStatus(resolveResponseStatusCode(ex, errorWrapper));
    ErrorMessageWrapper errorMessageWrapper = (ErrorMessageWrapper) context
            .getBean(ErrorMessageWrapper.class.getName());
    errorMessageWrapper
            .setMessageKey(resolveClientMessageKey(BroadleafWebServicesException.CONTENT_TYPE_NOT_SUPPORTED));
    errorMessageWrapper.setMessage(messageSource.getMessage(
            BroadleafWebServicesException.CONTENT_TYPE_NOT_SUPPORTED, new String[] { request.getContentType() },
            BroadleafWebServicesException.CONTENT_TYPE_NOT_SUPPORTED, locale));
    errorWrapper.getMessages().add(errorMessageWrapper);

    return errorWrapper;
}

From source file:org.georchestra.security.Proxy.java

/**
 * Since the URL param can access any url we need to control what it can
 * request so it is not used for nefarious purposes. We are basing the
 * control on contentType because it is supposed to be able to access any
 * server./*from   w w  w  .ja  v a  2 s  .  c om*/
 */
private void testLegalContentType(HttpServletRequest request) {
    String contentType = request.getContentType();
    if (contentType == null) {
        return;
    }
    // focus only on type, not on the text encoding
    String type = contentType.split(";")[0];
    for (String validTypeContent : requireCharsetContentTypes) {
        if (!validTypeContent.equals(type)) {
            return;
        }
    }
    throw new IllegalArgumentException("ContentType " + contentType
            + " is not permitted to be requested when the request is made through the URL parameter form.");
}