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:com.tasktop.c2c.server.web.proxy.HttpProxy.java

@Override
protected void proxy(String targetUrl, final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {

    final HttpMethod proxyRequest = createProxyRequest(targetUrl, request);

    if (proxyRequest instanceof EntityEnclosingMethod) {
        EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) proxyRequest;
        RequestEntity requestEntity = new InputStreamRequestEntity(request.getInputStream(),
                request.getContentLength(), request.getContentType());
        entityEnclosingMethod.setRequestEntity(requestEntity);
    }//from  w  w w  .j a  v  a 2 s.c om
    int code = httpClient.executeMethod(proxyRequest);
    response.setStatus(code);
    copyProxyReponse(proxyRequest, response);

}

From source file:org.fosstrak.epcis.repository.capture.CaptureOperationsServlet.java

/**
 * Implements the EPCIS capture operation. Takes HTTP POST request, extracts
 * the payload into an XML document, validates the document against the
 * EPCIS schema, and captures the EPCIS events given in the document. Errors
 * are caught and returned as simple plaintext messages via HTTP.
 * /*from w  w w  . j  a va2 s  .  c o m*/
 * @param req
 *            The HttpServletRequest.
 * @param rsp
 *            The HttpServletResponse.
 * @throws IOException
 *             If an error occurred while validating the request or writing
 *             the response.
 */
public void doPost(final HttpServletRequest req, final HttpServletResponse rsp)
        throws ServletException, IOException {
    LOG.info("EPCIS Capture Interface invoked.");
    InputStream is = null;

    // check if we have a POST request with form parameters
    if ("application/x-www-form-urlencoded".equalsIgnoreCase(req.getContentType())) {
        rsp.setContentType("text/plain");
        PrintWriter out = rsp.getWriter();
        // check if the 'event' or 'dbReset' form parameter are given
        String event = req.getParameter("event");
        String dbReset = req.getParameter("dbReset");
        if (event != null) {
            LOG.info("Found deprecated 'event=' parameter. Refusing to process request.");
            String msg = "Starting from version 0.2.2, the EPCIS repository does not accept the EPCISDocument in the HTTP POST form parameter 'event' anymore. Please provide the EPCISDocument as HTTP POST payload instead.";
            rsp.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
            out.println(msg);
        } else if (dbReset != null && dbReset.equalsIgnoreCase("true")) {
            doDbReset(rsp);
        }
        out.flush();
        out.close();
        return;
    } else {
        is = req.getInputStream();
    }

    // do the capture operation and handle exceptions
    String responseMsg = "";
    String detailedMsg = "";
    try {
        captureOperationsModule.doCapture(is, req.getUserPrincipal());
        rsp.setStatus(HttpServletResponse.SC_OK);
        responseMsg = "EPCIS capture request succeeded.";
    } catch (SAXException e) {
        responseMsg = "An error processing the XML document occurred.";
        detailedMsg = "Unable to parse incoming XML due to error: " + e.getMessage();
        LOG.info(detailedMsg);
        rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } catch (InvalidFormatException e) {
        responseMsg = "An error parsing the XML contents occurred.";
        detailedMsg = "Unable to parse incoming EPCISDocument due to error: " + e.getMessage();
        LOG.info(detailedMsg);
        rsp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } catch (final Exception e) {
        responseMsg = "An unexpected error occurred.";
        detailedMsg = "The repository is unable to handle the request due to an internal error.";
        LOG.error(responseMsg, e);
        rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    // dispatch the response
    req.setAttribute("responseMsg", responseMsg);
    req.setAttribute("detailedMsg", detailedMsg);
    RequestDispatcher dispatcher;
    String showCaptureForm = (String) req.getAttribute("showCaptureForm");
    if (showCaptureForm != null && "true".equals(showCaptureForm)) {
        dispatcher = getServletContext().getRequestDispatcher(PAGE_CAPTURE_FORM);
    } else {
        dispatcher = getServletContext().getRequestDispatcher(PAGE_CAPTURE_INTERFACE);
    }
    dispatcher.forward(req, rsp);
}

From source file:org.commoncrawl.service.listcrawler.MultiPartFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *///w  ww .j  a  v a2s . c o m
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    LOG.info("Hit doFilter");
    HttpServletRequest srequest = (HttpServletRequest) request;
    if (srequest.getContentType() == null || !srequest.getContentType().startsWith("multipart/form-data")) {
        LOG.info(srequest.toString());
        LOG.info("Rejecting. Invalid mime type:" + srequest.getContentType());
        chain.doFilter(request, response);
        return;
    }

    LOG.info("OK Looks Good So Far");

    BufferedInputStream in = new BufferedInputStream(request.getInputStream());
    String content_type = srequest.getContentType();

    // TODO - handle encodings

    String boundary = "--" + value(content_type.substring(content_type.indexOf("boundary=")));
    byte[] byteBoundary = (boundary + "--").getBytes(StringUtil.__ISO_8859_1);
    MultiMap params = new MultiMap();

    try {
        // Get first boundary
        byte[] bytes = TypeUtil.readLine(in);
        String line = bytes == null ? null : new String(bytes, "UTF-8");
        if (line == null || !line.equals(boundary)) {
            throw new IOException("Missing initial multi part boundary");
        }

        // Read each part
        boolean lastPart = false;
        String content_disposition = null;
        String file_content_type = null;
        while (!lastPart) {
            while (true) {
                bytes = TypeUtil.readLine(in);
                // If blank line, end of part headers
                if (bytes == null || bytes.length == 0)
                    break;
                line = new String(bytes, "UTF-8");

                // place part header key and value in map
                int c = line.indexOf(':', 0);
                if (c > 0) {
                    String key = line.substring(0, c).trim().toLowerCase();
                    String value = line.substring(c + 1, line.length()).trim();
                    if (key.equals("content-disposition"))
                        content_disposition = value;
                    else if (key.equals("content-type"))
                        file_content_type = value;
                }
            }
            // Extract content-disposition
            boolean form_data = false;
            if (content_disposition == null) {
                throw new IOException("Missing content-disposition");
            }

            StringTokenizer tok = new StringTokenizer(content_disposition, ";");
            String name = null;
            String filename = null;
            while (tok.hasMoreTokens()) {
                String t = tok.nextToken().trim();
                String tl = t.toLowerCase();
                if (t.startsWith("form-data"))
                    form_data = true;
                else if (tl.startsWith("name="))
                    name = value(t);
                else if (tl.startsWith("filename="))
                    filename = value(t);
            }

            // Check disposition
            if (!form_data) {
                continue;
            }
            if (name == null || name.length() == 0) {
                continue;
            }

            OutputStream out = null;
            File file = null;
            try {
                if (filename != null && filename.length() > 0) {
                    file = File.createTempFile("MultiPart", "", tempdir);
                    LOG.info("Got FileName:" + filename + " Creating Temp File:" + file);
                    out = new FileOutputStream(file);

                    UploadFileData uploadData = new UploadFileData();

                    uploadData.fieldName = name;
                    uploadData.incomingFile = file;
                    uploadData.incomingFilename = filename;
                    uploadData.incomingContentType = file_content_type;

                    request.setAttribute(name, uploadData);

                    params.put(name, filename);

                    if (_deleteFiles) {
                        //file.deleteOnExit();
                        ArrayList<UploadFileData> files = (ArrayList<UploadFileData>) request
                                .getAttribute(FILES);
                        if (files == null) {
                            files = new ArrayList<UploadFileData>();
                            request.setAttribute(FILES, files);
                        }
                        files.add(uploadData);
                    }

                } else
                    out = new ByteArrayOutputStream();

                int state = -2;
                int c;
                boolean cr = false;
                boolean lf = false;

                // loop for all lines`
                while (true) {
                    int b = 0;
                    while ((c = (state != -2) ? state : in.read()) != -1) {
                        state = -2;
                        // look for CR and/or LF
                        if (c == 13 || c == 10) {
                            if (c == 13)
                                state = in.read();
                            break;
                        }
                        // look for boundary
                        if (b >= 0 && b < byteBoundary.length && c == byteBoundary[b])
                            b++;
                        else {
                            // this is not a boundary
                            if (cr)
                                out.write(13);
                            if (lf)
                                out.write(10);
                            cr = lf = false;
                            if (b > 0)
                                out.write(byteBoundary, 0, b);
                            b = -1;
                            out.write(c);
                        }
                    }
                    // check partial boundary
                    if ((b > 0 && b < byteBoundary.length - 2) || (b == byteBoundary.length - 1)) {
                        if (cr)
                            out.write(13);
                        if (lf)
                            out.write(10);
                        cr = lf = false;
                        out.write(byteBoundary, 0, b);
                        b = -1;
                    }
                    // boundary match
                    if (b > 0 || c == -1) {
                        if (b == byteBoundary.length)
                            lastPart = true;
                        if (state == 10)
                            state = -2;
                        break;
                    }
                    // handle CR LF
                    if (cr)
                        out.write(13);
                    if (lf)
                        out.write(10);
                    cr = (c == 13);
                    lf = (c == 10 || state == 10);
                    if (state == 10)
                        state = -2;
                }
            } finally {
                if (out != null) {
                    out.close();
                }
            }

            if (file == null) {
                bytes = ((ByteArrayOutputStream) out).toByteArray();
                params.add(name, bytes);
            }
        }

        // handle request
        chain.doFilter(new Wrapper(srequest, params), response);
    } catch (IOException e) {
        LOG.error("###Exception In Multipart:" + CCStringUtils.stringifyException(e));
        throw e;
    } finally {
        LOG.info("Deleting Files Here");
        deleteFiles(request);
    }
}

From source file:org.dataconservancy.ui.api.ProjectController.java

/**
 * Handles updating a project matching the given id Note: Dates should be in
 * the format dd mm yyyy//ww w  .jav  a2s .c o  m
 * 
 * @param idpart
 * @throws ProjectServiceException
 * @throws InvalidXmlException
 * @throws BizPolicyException
 * @throws IOException
 */
@RequestMapping(value = "/{idpart}", method = { RequestMethod.PUT })
public void handleUpdateProjectRequest(@PathVariable String idpart,
        @RequestHeader(value = "Accept", required = false) String mimeType, @RequestBody byte[] content,
        HttpServletRequest req, HttpServletResponse resp)
        throws BizInternalException, InvalidXmlException, BizPolicyException, IOException {

    // TODO Why doesn't spring do this?
    if (req.getContentType().contains("application/x-www-form-urlencoded")) {
        content = URLDecoder.decode(new String(content, "UTF-8"), "UTF-8").getBytes("UTF-8");
    }

    Person user = getAuthenticatedUser();
    if (user == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    } else {
        Project newProject = objectBuilder.buildProject(new ByteArrayInputStream(content));
        String id = util.buildRequestUrl(req);

        Project originalProject = projectService.get(id);

        if (originalProject != null) {

            if (newProject.getId().equalsIgnoreCase(id)) {
                if (authorizationService.canUpdateProject(user, newProject)) {
                    projectBizService.updateProject(newProject, user);

                    resp.setCharacterEncoding("UTF-8");
                    resp.setContentType("text/xml");

                    newProject = projectService.get(id);
                    Bop bop = new Bop();
                    bop.addProject(newProject);
                    objectBuilder.buildBusinessObjectPackage(bop, resp.getOutputStream());
                } else {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
            } else {
                try {
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                            "ID doesn't match ID of supplied project");
                } catch (Exception ee) {
                    log.debug("Handling exception", ee);
                }
            }

        } else {
            try {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Could not find project with id: " + idpart);
            } catch (Exception ee) {
                log.debug("Handling exception", ee);
            }
        }
    }
}

From source file:org.appcelerator.transport.AjaxServiceTransportServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //// www  .j  ava  2  s .c  o m
    // make sure we check the integrity of the request before we continue
    //
    if (!validate(req, resp)) {
        LOG.warn("security validation failed for request=" + req + " from " + req.getRemoteAddr());
        return;
    }

    String type = req.getContentType();
    int idx = type.indexOf(';');

    if (idx > 0) {
        type = type.substring(0, idx);
    }

    try {
        // decode the incoming request
        ArrayList<Message> requests = new ArrayList<Message>(1);
        ArrayList<Message> responses = new ArrayList<Message>(1);

        ServiceMarshaller.getMarshaller(type).decode(req.getInputStream(), requests);

        if (requests.isEmpty()) {
            // no incoming messages, just return accepted header
            resp.setHeader("Content-Length", "0");
            resp.setContentType("text/plain;charset=UTF-8");
            resp.setStatus(HttpServletResponse.SC_ACCEPTED);
            return;
        }

        HttpSession session = req.getSession();
        InetAddress address = InetAddress.getByName(req.getRemoteAddr());
        //String instanceid = req.getParameter("instanceid");

        for (Message request : requests) {
            request.setUser(req.getUserPrincipal());
            request.setSession(session);
            request.setAddress(address);
            request.setServletRequest(req);

            //FIXME => refactor this out
            if (request.getType().equals(MessageType.APPCELERATOR_STATUS_REPORT)) {
                IMessageDataObject data = (IMessageDataObject) request.getData();
                data.put("remoteaddr", req.getRemoteAddr());
                data.put("remotehost", req.getRemoteHost());
                data.put("remoteuser", req.getRemoteUser());
            }

            ServiceRegistry.dispatch(request, responses);
        }

        if (responses.isEmpty()) {
            // no response messages, just return accepted header
            resp.setHeader("Content-Length", "0");
            resp.setContentType("text/plain;charset=UTF-8");
            resp.setStatus(HttpServletResponse.SC_ACCEPTED);
            return;
        }

        // setup the response
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setHeader("Connection", "Keep-Alive");
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-control", "no-cache, no-store, private, must-revalidate");
        resp.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");

        // encode the responses
        ServletOutputStream output = resp.getOutputStream();
        ByteArrayOutputStream bout = new ByteArrayOutputStream(1000);
        String responseType = ServiceMarshaller.getMarshaller(type).encode(responses, req.getSession().getId(),
                bout);
        byte buf[] = bout.toByteArray();
        ByteArrayInputStream bin = new ByteArrayInputStream(buf);

        resp.setContentType(responseType);

        // do gzip encoding if browser supports it and if length > 1000 bytes
        String ae = req.getHeader("accept-encoding");
        if (ae != null && ae.indexOf("gzip") != -1 && buf.length > 1000) {
            resp.setHeader("Content-Encoding", "gzip");
            //a Vary: Accept-Encoding HTTP response header to alert proxies that a cached response should be sent only to 
            //clients that send the appropriate Accept-Encoding request header. This prevents compressed content from being sent 
            //to a client that will not understand it.
            resp.addHeader("Vary", "Accept-Encoding");
            GZIPOutputStream gzip = new GZIPOutputStream(output, buf.length);
            Util.copy(bin, gzip);
            gzip.flush();
            gzip.finish();
        } else {
            resp.setContentLength(buf.length);
            Util.copy(bin, output);
        }
        output.flush();
    } catch (Throwable e) {
        LOG.error("Error handling incoming POST request", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:io.druid.server.AsyncQueryForwardingServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final boolean isSmile = SmileMediaTypes.APPLICATION_JACKSON_SMILE.equals(request.getContentType())
            || APPLICATION_SMILE.equals(request.getContentType());
    final ObjectMapper objectMapper = isSmile ? smileMapper : jsonMapper;
    request.setAttribute(OBJECTMAPPER_ATTRIBUTE, objectMapper);

    final String requestURI = request.getRequestURI();
    final String method = request.getMethod();
    final Server targetServer;

    // The Router does not have the ability to look inside SQL queries and route them intelligently, so just treat
    // them as a generic request.
    final boolean isQueryEndpoint = requestURI.startsWith("/druid/v2")
            && !requestURI.startsWith("/druid/v2/sql");

    final boolean isAvatica = requestURI.startsWith("/druid/v2/sql/avatica");

    if (isAvatica) {
        Map<String, Object> requestMap = objectMapper.readValue(request.getInputStream(),
                JacksonUtils.TYPE_REFERENCE_MAP_STRING_OBJECT);
        String connectionId = getAvaticaConnectionId(requestMap);
        targetServer = hostFinder.findServerAvatica(connectionId);
        byte[] requestBytes = objectMapper.writeValueAsBytes(requestMap);
        request.setAttribute(AVATICA_QUERY_ATTRIBUTE, requestBytes);
    } else if (isQueryEndpoint && HttpMethod.DELETE.is(method)) {
        // query cancellation request
        targetServer = hostFinder.pickDefaultServer();

        for (final Server server : hostFinder.getAllServers()) {
            // send query cancellation to all brokers this query may have gone to
            // to keep the code simple, the proxy servlet will also send a request to the default targetServer.
            if (!server.getHost().equals(targetServer.getHost())) {
                // issue async requests
                Response.CompleteListener completeListener = result -> {
                    if (result.isFailed()) {
                        log.warn(result.getFailure(), "Failed to forward cancellation request to [%s]",
                                server.getHost());
                    }//from w w  w  .  j  a  v a 2s . co m
                };

                Request broadcastReq = broadcastClient
                        .newRequest(rewriteURI(request, server.getScheme(), server.getHost()))
                        .method(HttpMethod.DELETE).timeout(CANCELLATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);

                copyRequestHeaders(request, broadcastReq);
                broadcastReq.send(completeListener);
            }
            interruptedQueryCount.incrementAndGet();
        }
    } else if (isQueryEndpoint && HttpMethod.POST.is(method)) {
        // query request
        try {
            Query inputQuery = objectMapper.readValue(request.getInputStream(), Query.class);
            if (inputQuery != null) {
                targetServer = hostFinder.pickServer(inputQuery);
                if (inputQuery.getId() == null) {
                    inputQuery = inputQuery.withId(UUID.randomUUID().toString());
                }
            } else {
                targetServer = hostFinder.pickDefaultServer();
            }
            request.setAttribute(QUERY_ATTRIBUTE, inputQuery);
        } catch (IOException e) {
            log.warn(e, "Exception parsing query");
            final String errorMessage = e.getMessage() == null ? "no error message" : e.getMessage();
            requestLogger
                    .log(new RequestLogLine(DateTimes.nowUtc(), request.getRemoteAddr(), null, new QueryStats(
                            ImmutableMap.<String, Object>of("success", false, "exception", errorMessage))));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType(MediaType.APPLICATION_JSON);
            objectMapper.writeValue(response.getOutputStream(), ImmutableMap.of("error", errorMessage));

            return;
        } catch (Exception e) {
            handleException(response, objectMapper, e);
            return;
        }
    } else {
        targetServer = hostFinder.pickDefaultServer();
    }

    request.setAttribute(HOST_ATTRIBUTE, targetServer.getHost());
    request.setAttribute(SCHEME_ATTRIBUTE, targetServer.getScheme());

    doService(request, response);
}

From source file:eu.freme.broker.tools.loggingfilter.LoggingFilter.java

private void logRequest(final HttpServletRequest request) {
    StringBuilder msg = new StringBuilder();
    msg.append(REQUEST_PREFIX);/* w w w .  j  av  a  2s.co  m*/
    if (request instanceof RequestWrapper) {
        msg.append("request id=").append(((RequestWrapper) request).getId()).append("; ");
    }
    HttpSession session = request.getSession(false);
    if (session != null) {
        msg.append("session id=").append(session.getId()).append("; ");
    }
    if (request.getContentType() != null) {
        msg.append("content type=").append(request.getContentType()).append("; ");
    }
    msg.append("uri=").append(request.getRequestURI());
    if (request.getQueryString() != null) {
        msg.append('?').append(request.getQueryString());
    }

    if (request instanceof RequestWrapper && !isMultipart(request)) {
        RequestWrapper requestWrapper = (RequestWrapper) request;
        try {
            String charEncoding = requestWrapper.getCharacterEncoding() != null
                    ? requestWrapper.getCharacterEncoding()
                    : "UTF-8";
            if (request.getContentLength() == 0 || checkAgainstWhitelist(request)) {
                String body = new String(requestWrapper.toByteArray(), charEncoding);
                if (request.getContentLength() >= maxSize) {
                    try {
                        body = body.substring(0, maxSize).concat("... (truncated by LoggingFilter)");
                    } catch (StringIndexOutOfBoundsException e) {
                        logger.warn(
                                "A Request was made whose Content-Length Header is longer than its actual content");
                    }
                }
                msg.append("; payload=").append(body);
            } else {
                msg.append("; payload ommitted from logging as it is not in the whitelisted mime-types");
            }

        } catch (UnsupportedEncodingException e) {
            logger.warn("Failed to parse request payload", e);
        }

    }
    logger.info(msg.toString());
}

From source file:org.sakaiproject.tool.assessment.ui.servlet.delivery.UploadAudioMediaServlet.java

private String submitMediaAsAnswer(HttpServletRequest req, String mediaLocation, String saveToDb)
        throws Exception {
    // read parameters passed in
    String mimeType = req.getContentType();
    String duration = req.getParameter("lastDuration");
    String agentId = req.getParameter("agent");

    int attemptsRemaining = Integer.parseInt(req.getParameter("attempts"));
    GradingService gradingService = new GradingService();
    PublishedAssessmentService pubService = new PublishedAssessmentService();
    int assessmentIndex = mediaLocation.indexOf("assessment");
    int questionIndex = mediaLocation.indexOf("question");
    int agentIndex = mediaLocation.indexOf("/", questionIndex + 8);
    //int myfileIndex = mediaLocation.lastIndexOf("/");
    String pubAssessmentId = mediaLocation.substring(assessmentIndex + 10, questionIndex - 1);
    String questionId = mediaLocation.substring(questionIndex + 8, agentIndex);
    //String agentEid = mediaLocation.substring(agentIndex+1, myfileIndex);
    //log.debug("****pubAss="+pubAssessmentId);
    //log.debug("****questionId="+questionId);
    //log.debug("****agent="+agentId);

    PublishedItemData item = pubService.loadPublishedItem(questionId);
    PublishedItemText itemText = (PublishedItemText) (item.getItemTextSet()).iterator().next();

    log.debug("****agentId=" + agentId);
    log.debug("****pubAssId=" + pubAssessmentId);
    // 1. get assessmentGrading form DB
    AssessmentGradingData adata = gradingService.getLastSavedAssessmentGradingByAgentId(pubAssessmentId,
            agentId);/*www . ja v a2 s.c  o  m*/

    if (adata == null) {
        // adata should already be created by BeginAssessment
        // lets throws exception
        throw new Exception("This page must have been reached by mistake.");
    }

    // 2. get itemGrading from DB, remove any attached media
    //    also work out no. of attempts remaining 
    ItemGradingData itemGrading = gradingService.getItemGradingData(adata.getAssessmentGradingId().toString(),
            questionId);
    ArrayList mediaList = new ArrayList();
    if (itemGrading != null) {
        // just need update itemGrading, and media.media 
        GradingService service = new GradingService();
        if (itemGrading.getItemGradingId() != null)
            mediaList = service.getMediaArray(itemGrading.getItemGradingId().toString());

        if (mediaList.size() > 0) {
            log.debug("*** delete old audio");
            gradingService.deleteAll(mediaList);
        }
        if (itemGrading.getAttemptsRemaining() == null) {
            // this is not possible unless the question is submitted without the
            // attempt set correctly
            if ((item.getTriesAllowed()).intValue() >= 9999)
                attemptsRemaining = 9999;
        } else {
            if ((item.getTriesAllowed()).intValue() >= 9999)
                attemptsRemaining = 9999;
            else if (itemGrading.getAttemptsRemaining().intValue() > 0)
                ;
            // We're now getting the applet to tell us how many attempts remain
            //          attemptsRemaining = itemGrading.getAttemptsRemaining().intValue() - 1;
            else
                throw new Exception(
                        "This page must have been reached by mistake. Our record shows that no more attempt for this question is allowed.");
        }
    } else {
        // create an itemGrading
        if ((item.getTriesAllowed()).intValue() >= 9999)
            attemptsRemaining = 9999;
        else
            ;
        //        attemptsRemaining = (item.getTriesAllowed()).intValue() -1;
        itemGrading = new ItemGradingData();
        itemGrading.setAssessmentGradingId(adata.getAssessmentGradingId());
        itemGrading.setPublishedItemId(item.getItemId());
        itemGrading.setPublishedItemTextId(itemText.getId());
        itemGrading.setAgentId(agentId);
        itemGrading.setOverrideScore(Double.valueOf(0));
        itemGrading.setSubmittedDate(new Date());
        itemGrading.setAttemptsRemaining(Integer.valueOf(attemptsRemaining));
        itemGrading.setLastDuration(duration);
        gradingService.saveItemGrading(itemGrading);
    }
    log.debug("****1. assessmentGradingId=" + adata.getAssessmentGradingId());
    log.debug("****2. attemptsRemaining=" + attemptsRemaining);
    log.debug("****3. itemGradingDataId=" + itemGrading.getItemGradingId());
    // 3. save Media and fix up itemGrading
    return saveMedia(attemptsRemaining, mimeType, agentId, mediaLocation, itemGrading, saveToDb, duration);
}

From source file:com.nc.api.controller.APIServiceController.java

/**
 * <pre>//  ww  w.j a v a 2s . c  o m
 * 1.  : API ?? (?)
 * 2.  : ?   (jobNo, enprTp-1(??), 2(??))
 * </pre>
 *
 * @method Name : getEnprInfoList
 * @param request, httpRequest, model
 * @return ModelMap
 * @throws Exception
 * 
 */
@SuppressWarnings("unchecked")
@RequestMapping(value = "/api/member/getEnprInfoList.json", method = { RequestMethod.GET, RequestMethod.POST })
public ModelMap getEnprInfoList(@RequestParam Map<String, Object> request, HttpServletRequest httpRequest,
        ModelMap model) throws Exception {
    ModelMap result = new ModelMap();
    ResponseBean respBean = new ResponseBean();
    Map<String, Object> paramMap = new HashMap<String, Object>();
    List<ModelMap> resultList = new ArrayList<ModelMap>();

    if ("POST".equals(httpRequest.getMethod())
            && "application/x-www-form-urlencoded".equals(httpRequest.getContentType())) {
        request = validator.getPostContents(httpRequest, request);
    }

    paramMap = validator.makeParamRequest(request, httpRequest);

    request.put("key", StringUtil.nvl(httpRequest.getHeader("x-etri-authorization"), ""));

    /* 
     * ? ?  ? 
     * 0. Http Header Check 
     */
    if (validator.isValidParam(request) != null) {
        return validator.isValidParam(request);
    }

    /*  ?    */
    respBean.getParams().putAll(paramMap);

    /* 
     *   
     * 1. ?   
     */
    List<?> tmpResult = apiService.getEnprInfoList("api.selectEnprInfoList", paramMap);

    /* 
     *   
     * 2. ?   
     */
    int totalCount = apiService.getEnprInfoListCnt("api.selectEnprInfoListCnt", paramMap);

    try {
        if (tmpResult != null && tmpResult.size() > 0) {
            respBean.setStatus(HttpStatus.SC_OK, "Ok");

            for (int i = 0; i < tmpResult.size(); i++) {
                Map<String, Object> temp = (Map<String, Object>) tmpResult.get(i);
                ModelMap itemData = new ModelMap();

                for (String keyStr : temp.keySet()) {
                    itemData.put(keyStr, temp.get(keyStr));
                }

                resultList.add(itemData);
            }

            ModelMap page = new ModelMap();
            page.put("page_no", 1);
            page.put("tuple_count", totalCount);
            respBean.setPaging(page);

            respBean.setItems(resultList);
            result.put("results", respBean.getResult());
        } else {
            result.put("results", respBean.getResultNoPage());
        }
    } catch (Exception err) {
        respBean.setStatus(Integer.valueOf(APIConstants.ERROR_SYSTEM.getCode()),
                " ??  ?? ? ?.");
        result.put("results", respBean.getResult(APIConstants.ERROR_SYSTEM.getCode()));
    }

    if (log.isDebugEnabled()) {
        log.debug("==========================================================================================");
        log.debug("= Parameter is [{}] =", paramMap);
        log.debug("= Controller name is [{}] =", this.getClass().getMethods()[0].getName());
        log.debug("= Result is [{}] =", result);
        log.debug("==========================================================================================");
    }

    return result;
}

From source file:com.ec2box.common.interceptor.CSRFInterceptor.java

@Override
protected String handleToken(ActionInvocation invocation) throws Exception {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpSession session = request.getSession(true);
    synchronized (session) {
        String sessionToken = (String) session.getAttribute(AuthUtil.CSRF_TOKEN_NM);
        String token = request.getParameter(AuthUtil.CSRF_TOKEN_NM);
        if (StringUtils.isEmpty(token) || StringUtils.isEmpty(sessionToken) || !token.equals(sessionToken)) {
            AuthUtil.deleteAllSession(session);
            return this.handleInvalidToken(invocation);
        }//from   w ww .  j  a v  a 2 s  .  com

        //generate new token upon post
        if ("POST".equals(request.getMethod()) && !request.getContentType().contains("multipart/form-data")) {
            AuthUtil.generateCSRFToken(session);
        }
    }

    return this.handleValidToken(invocation);
}