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

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String timeStamp = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(Calendar.getInstance().getTime());
    String timeStamp2 = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());

    Pembayaran p = new Pembayaran();
    DatabaseManager db = new DatabaseManager();

    //Menyimpan file ke dalam sistem
    File file;//from  w w w  .j  ava2  s .  c o  m
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    String filePath = "c:/Apache/";

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

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        factory.setRepository(new File("c:\\temp"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxFileSize);
        try {
            List fileItems = upload.parseRequest(request);
            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    if (fi.getName().contains(".csv")) {
                        String fieldName = fi.getFieldName();
                        String fileName = fi.getName();
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        file = new File(filePath + "DataPembayaran_" + timeStamp + ".csv");
                        fi.write(file);
                    } else {
                        throw new Exception("Format File Salah");
                    }
                }
            }
        } catch (Exception ex) {
            returnError(request, response, ex);
        }
    } else {
        Exception e = new Exception("no file uploaded");
        returnError(request, response, e);
    }
    //Membaca file dari dalam sistem
    String csvFile = filePath + "DataPembayaran_" + timeStamp + ".csv";
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";

    try {
        br = new BufferedReader(new FileReader(csvFile));
        int counter = 1;
        while ((line = br.readLine()) != null) {

            // use comma as separator
            String[] dataSet = line.split(cvsSplitBy);
            p.setID(timeStamp2 + "_" + counter);
            p.setWaktuPembayaran(dataSet[0]);
            p.setNoRekening(dataSet[1]);
            p.setJumlahPembayaran(Double.parseDouble(dataSet[2]));
            p.setNis(dataSet[3].substring(0, 5));
            p.setBulanTagihan(Integer.parseInt(dataSet[3].substring(6)));
            //Membandingkan nis, jumlah, bulan pembayaran ke tagihan
            Tagihan[] t = Tagihan.getListTagihan(p.getNis());
            for (int i = 0; i < t.length; i++) {
                if (t[i].getNis().equals(p.getNis()) && t[i].getJumlah_pembayaran() == p.getJumlahPembayaran()
                        && t[i].getBulan_tagihan() == p.getBulanTagihan())// bandingkan jumlah pembayaran
                {
                    //Masukan data pembayaran ke database
                    Pembayaran.simpanPembayaran(p);
                    //update status pembayaran tagihan
                    t[i].verifikasiSukses(p.getNis(), p.getBulanTagihan());//update status bayar tagihan menjadi sudah bayar
                }
            }
            counter++;
        }
        this.tampil(request, response, "Data Terverifikasi");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //        }
}

From source file:grails.web.servlet.mvc.GrailsParameterMap.java

/**
 * Creates a GrailsParameterMap populating from the given request object
 * @param request The request object/*from   ww  w.j a  v a2s .c  o m*/
 */
public GrailsParameterMap(HttpServletRequest request) {
    this.request = request;
    final Map requestMap = new LinkedHashMap(request.getParameterMap());
    if (requestMap.isEmpty() && ("PUT".equals(request.getMethod()) || "PATCH".equals(request.getMethod()))
            && request.getAttribute(REQUEST_BODY_PARSED) == null) {
        // attempt manual parse of request body. This is here because some containers don't parse the request body automatically for PUT request
        String contentType = request.getContentType();
        if ("application/x-www-form-urlencoded".equals(contentType)) {
            try {
                Reader reader = request.getReader();
                if (reader != null) {
                    String contents = IOUtils.toString(reader);
                    request.setAttribute(REQUEST_BODY_PARSED, true);
                    requestMap.putAll(WebUtils.fromQueryString(contents));
                }
            } catch (Exception e) {
                LOG.error("Error processing form encoded " + request.getMethod() + " request", e);
            }
        }
    }

    if (request instanceof MultipartHttpServletRequest) {
        Map<String, MultipartFile> fileMap = ((MultipartHttpServletRequest) request).getFileMap();
        for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
            requestMap.put(entry.getKey(), entry.getValue());
        }
    }

    updateNestedKeys(requestMap);
}

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

/**
 * Evaluates a query on the given connection and returns the resulting {@link QueryResultView}. The
 * {@link QueryResultView} will take care of correctly releasing the connection back to the
 * {@link ActiveTransactionRegistry}, after fully rendering the query result for sending over the wire.
 *//*from ww w.j  a v  a2s  .co m*/
private ModelAndView processQuery(Transaction txn, HttpServletRequest request, HttpServletResponse response)
        throws IOException, HTTPException {
    String queryStr = null;
    final String contentType = request.getContentType();
    if (contentType != null && contentType.contains(Protocol.SPARQL_QUERY_MIME_TYPE)) {
        final String encoding = request.getCharacterEncoding() != null ? request.getCharacterEncoding()
                : "UTF-8";
        queryStr = IOUtils.toString(request.getInputStream(), encoding);
    } else {
        queryStr = request.getParameter(QUERY_PARAM_NAME);
    }

    View view;
    Object queryResult;
    FileFormatServiceRegistry<? extends FileFormat, ?> registry;

    try {
        Query query = getQuery(txn, queryStr, request, response);

        if (query instanceof TupleQuery) {
            TupleQuery tQuery = (TupleQuery) query;

            queryResult = txn.evaluate(tQuery);
            registry = TupleQueryResultWriterRegistry.getInstance();
            view = TupleQueryResultView.getInstance();
        } else if (query instanceof GraphQuery) {
            GraphQuery gQuery = (GraphQuery) query;

            queryResult = txn.evaluate(gQuery);
            registry = RDFWriterRegistry.getInstance();
            view = GraphQueryResultView.getInstance();
        } else if (query instanceof BooleanQuery) {
            BooleanQuery bQuery = (BooleanQuery) query;

            queryResult = txn.evaluate(bQuery);
            registry = BooleanQueryResultWriterRegistry.getInstance();
            view = BooleanQueryResultView.getInstance();
        } else {
            throw new ClientHTTPException(SC_BAD_REQUEST,
                    "Unsupported query type: " + query.getClass().getName());
        }
    } catch (QueryInterruptedException | InterruptedException | ExecutionException e) {
        logger.info("Query interrupted", e);
        throw new ServerHTTPException(SC_SERVICE_UNAVAILABLE, "Query execution interrupted");
    } catch (QueryEvaluationException e) {
        logger.info("Query evaluation error", e);
        if (e.getCause() != null && e.getCause() instanceof HTTPException) {
            // custom signal from the backend, throw as HTTPException
            // directly (see SES-1016).
            throw (HTTPException) e.getCause();
        } else {
            throw new ServerHTTPException("Query evaluation error: " + e.getMessage());
        }
    }
    Object factory = ProtocolUtil.getAcceptableService(request, response, registry);

    Map<String, Object> model = new HashMap<String, Object>();
    model.put(QueryResultView.FILENAME_HINT_KEY, "query-result");
    model.put(QueryResultView.QUERY_RESULT_KEY, queryResult);
    model.put(QueryResultView.FACTORY_KEY, factory);
    model.put(QueryResultView.HEADERS_ONLY, false); // TODO needed for HEAD
    // requests.
    return new ModelAndView(view, model);
}

From source file:org.jspresso.framework.server.remote.RemotePeerRegistryServlet.java

/**
 * {@inheritDoc}/*w  w w .  j  ava 2  s .  c  om*/
 */
@SuppressWarnings("unchecked")
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

    String id = request.getParameter(ID_PARAMETER);

    if (id == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No state id specified.");
        return;
    }

    IRemotePeerRegistry peerRegistry = (IRemotePeerRegistry) request.getSession().getAttribute(PEER_REGISTRY);
    try {
        HttpRequestHolder.setServletRequest(request);
        byte[] content;
        if ("application/x-www-form-urlencoded".equals(request.getContentType())) {
            String data = request.getParameter("data");
            content = Base64.decodeBase64(data);
        } else {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            OutputStream out = new BufferedOutputStream(baos);
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            if (items.size() > 0) {
                FileItem item = items.get(0);
                IoHelper.copyStream(item.getInputStream(), out);
            }
            out.flush();
            out.close();
            content = baos.toByteArray();
        }

        if (content != null && content.length == 0) {
            content = null;
        }

        IRemoteStateOwner stateOwner = (IRemoteStateOwner) peerRegistry.getRegistered(id);
        stateOwner.setValueFromState(content);

    } catch (Exception ex) {
        if (peerRegistry instanceof IExceptionHandler) {
            ((IExceptionHandler) peerRegistry).handleException(ex, Collections.<String, Object>emptyMap());
        } else {
            LOG.error("An unexpected error occurred while uploading the content.", ex);
        }
    } finally {
        HttpRequestHolder.setServletRequest(null);
    }
}

From source file:se.vgregion.portal.requestlogger.RequestLoggerController.java

private Map<String, String> getRequestInfo(PortletRequest request) {
    Map<String, String> requestResult = new TreeMap<String, String>();

    HttpServletRequest httpRequest = PortalUtil.getHttpServletRequest(request);

    requestResult.put("RemoteUser", httpRequest.getRemoteUser());
    requestResult.put("P3P.USER_LOGIN_ID", getRemoteUserId(request));
    requestResult.put("RemoteAddr", httpRequest.getRemoteAddr());
    requestResult.put("RemoteHost", httpRequest.getRemoteHost());
    requestResult.put("RemotePort", String.valueOf(httpRequest.getRemotePort()));
    requestResult.put("AuthType", httpRequest.getAuthType());
    requestResult.put("CharacterEncoding", httpRequest.getCharacterEncoding());
    requestResult.put("ContentLength", String.valueOf(httpRequest.getContentLength()));
    requestResult.put("ContentType", httpRequest.getContentType());
    requestResult.put("ContextPath", httpRequest.getContextPath());
    requestResult.put("LocalAddr", httpRequest.getLocalAddr());
    requestResult.put("Locale", httpRequest.getLocale().toString());
    requestResult.put("LocalName", httpRequest.getLocalName());
    requestResult.put("LocalPort", String.valueOf(httpRequest.getLocalPort()));
    requestResult.put("Method", httpRequest.getMethod());
    requestResult.put("PathInfo", httpRequest.getPathInfo());
    requestResult.put("PathTranslated", httpRequest.getPathTranslated());
    requestResult.put("Protocol", httpRequest.getProtocol());
    requestResult.put("QueryString", httpRequest.getQueryString());
    requestResult.put("RequestedSessionId", httpRequest.getRequestedSessionId());
    requestResult.put("RequestURI", httpRequest.getRequestURI());
    requestResult.put("Scheme", httpRequest.getScheme());
    requestResult.put("ServerName", httpRequest.getServerName());
    requestResult.put("ServerPort", String.valueOf(httpRequest.getServerPort()));
    requestResult.put("ServletPath", httpRequest.getServletPath());

    return requestResult;
}

From source file:com.sun.syndication.propono.atom.server.AtomServlet.java

/**
 * Handles an Atom POST by calling handler to identify URI, reading/parsing
 * data, calling handler and writing results to response.
 *//* w  w w  .jav  a  2 s.c  om*/
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    log.debug("Entering");
    AtomHandler handler = createAtomRequestHandler(req, res);
    String userName = handler.getAuthenticatedUsername();
    if (userName != null) {
        AtomRequest areq = new AtomRequestImpl(req);
        try {
            if (handler.isCollectionURI(areq)) {

                if (req.getContentType().startsWith("application/atom+xml")) {

                    // parse incoming entry
                    Entry entry = Atom10Parser.parseEntry(
                            new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8")), null);

                    // call handler to post it
                    Entry newEntry = handler.postEntry(areq, entry);

                    // set Location and Content-Location headers                        
                    for (Iterator it = newEntry.getOtherLinks().iterator(); it.hasNext();) {
                        Link link = (Link) it.next();
                        if ("edit".equals(link.getRel())) {
                            res.addHeader("Location", link.getHrefResolved());
                            break;
                        }
                    }
                    for (Iterator it = newEntry.getAlternateLinks().iterator(); it.hasNext();) {
                        Link link = (Link) it.next();
                        if ("alternate".equals(link.getRel())) {
                            res.addHeader("Content-Location", link.getHrefResolved());
                            break;
                        }
                    }

                    // write entry back out to response
                    res.setStatus(HttpServletResponse.SC_CREATED);
                    res.setContentType("application/atom+xml; type=entry; charset=utf-8");

                    Writer writer = res.getWriter();
                    Atom10Generator.serializeEntry(newEntry, writer);
                    writer.close();

                } else if (req.getContentType() != null) {

                    // get incoming title and slug from HTTP header
                    String title = areq.getHeader("Title");

                    // create new entry for resource, set title and type
                    Entry resource = new Entry();
                    resource.setTitle(title);
                    Content content = new Content();
                    content.setType(areq.getContentType());
                    resource.setContents(Collections.singletonList(content));

                    // hand input stream off to hander to post file
                    Entry newEntry = handler.postMedia(areq, resource);

                    // set Location and Content-Location headers
                    for (Iterator it = newEntry.getOtherLinks().iterator(); it.hasNext();) {
                        Link link = (Link) it.next();
                        if ("edit".equals(link.getRel())) {
                            res.addHeader("Location", link.getHrefResolved());
                            break;
                        }
                    }
                    for (Iterator it = newEntry.getAlternateLinks().iterator(); it.hasNext();) {
                        Link link = (Link) it.next();
                        if ("alternate".equals(link.getRel())) {
                            res.addHeader("Content-Location", link.getHrefResolved());
                            break;
                        }
                    }

                    res.setStatus(HttpServletResponse.SC_CREATED);
                    res.setContentType("application/atom+xml; type=entry; charset=utf-8");

                    Writer writer = res.getWriter();
                    Atom10Generator.serializeEntry(newEntry, writer);
                    writer.close();

                } else {
                    res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                            "No content-type specified in request");
                }

            } else {
                res.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid collection specified in request");
            }
        } catch (AtomException ae) {
            res.sendError(ae.getStatus(), ae.getMessage());
            log.debug("ERROR processing POST", ae);
        } catch (Exception e) {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            log.debug("ERROR processing POST", e);
        }
    } else {
        res.setHeader("WWW-Authenticate", "BASIC realm=\"AtomPub\"");
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
    log.debug("Exiting");
}

From source file:org.mule.transport.servlet.MockHttpServletRequestBuilder.java

public HttpServletRequest buildRequest() throws Exception {
    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    when(mockRequest.getMethod()).thenReturn(method);

    Enumeration<String> emptyEnumeration = new Hashtable<String, String>().elements();
    when(mockRequest.getParameterNames()).thenReturn(emptyEnumeration);

    when(mockRequest.getRequestURI()).thenReturn(requestUri);
    when(mockRequest.getQueryString()).thenReturn(queryString);
    when(mockRequest.getInputStream()).thenReturn(inputStream);
    when(mockRequest.getSession(anyBoolean())).thenReturn(session);
    when(mockRequest.getCharacterEncoding()).thenReturn(characterEncoding);
    when(mockRequest.getLocalPort()).thenReturn(localPort);
    when(mockRequest.getContentType()).thenReturn(contentType);
    when(mockRequest.getRemoteAddr()).thenReturn(host);
    when(mockRequest.getHeader(eq(HttpConstants.HEADER_HOST))).thenReturn(host);
    when(mockRequest.getPathInfo()).thenReturn(pathInfo);

    addParameterExpectations(mockRequest);
    addAttributeExpectations(mockRequest);
    addHeaderExpectations(mockRequest);//  ww  w .  j  av  a 2  s.c o m

    return mockRequest;
}

From source file:org.dspace.webmvc.controller.admin.CollectionWizardController.java

@RequestMapping(method = RequestMethod.POST, params = "submit_next_logo")
protected String uploadFile(@RequestAttribute Context context, ModelMap model, HttpServletRequest request,
        HttpServletResponse response, @RequestParam("file") CommonsMultipartFile file)
        throws ServletException, IOException, SQLException, AuthorizeException {

    // First, see if we have a multipart request (uploading a logo)
    String contentType = request.getContentType();

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

    } //end if/*from   w ww .j  a v a2  s  .c o m*/
    return "";
}

From source file:com.glaf.mail.website.springmvc.MailReceiveController.java

@ResponseBody
@RequestMapping("/view")
public void view(HttpServletRequest request) {
    String messageId = request.getParameter("messageId");
    if (messageId != null) {
        messageId = RequestUtils.decodeString(messageId);
        Map<String, Object> dataMap = JsonUtils.decode(messageId);
        String taskId = (String) dataMap.get("taskId");
        String itemId = (String) dataMap.get("itemId");
        if (taskId != null && itemId != null) {
            MailItem mailItem = mailDataFacede.getMailItem(taskId, itemId);
            if (mailItem != null) {
                mailItem.setReceiveStatus(1);
                mailItem.setReceiveDate(new Date());
                mailItem.setReceiveIP(RequestUtils.getIPAddress(request));
                String contentType = request.getContentType();
                mailItem.setContentType(contentType);
                logger.debug("contentType:" + contentType);
                java.util.Enumeration<String> e = request.getHeaderNames();
                while (e.hasMoreElements()) {
                    String name = e.nextElement();
                    logger.debug(name + "=" + request.getHeader(name));
                }//from w  ww.jav  a  2s  . com
                String userAgent = request.getHeader("user-agent");
                if (userAgent != null) {
                    if (userAgent.indexOf("Chrome") != -1) {
                        mailItem.setBrowser("Chrome");
                    } else if (userAgent.indexOf("MSIE") != -1) {
                        mailItem.setBrowser("IE");
                    } else if (userAgent.indexOf("Firefox") != -1) {
                        mailItem.setBrowser("Firefox");
                    }
                    if (userAgent.indexOf("Windows") != -1) {
                        mailItem.setClientOS("Windows");
                    }
                }
                mailDataFacede.updateMail(taskId, mailItem);
            }
        }
    }
}

From source file:byps.http.HActiveMessages.java

private HIncomingStreamSync addIncomingStreamSync2(final BTargetId targetId, HttpServletRequest request)
        throws BException {
    if (log.isDebugEnabled())
        log.debug("addIncomingStreamSync2(" + targetId);

    HIncomingStreamSync istrm = null;/*from w ww  .  ja  va 2 s.com*/

    try {
        final String contentType = request.getContentType();
        final String contentDisposition = request.getHeader("Content-Disposition");
        final String contentLengthStr = request.getHeader("Content-Length");
        final long contentLength = contentLengthStr != null && contentLengthStr.length() != 0
                ? Long.parseLong(contentLengthStr)
                : -1L;
        final String totalLengthStr = request.getParameter("total");
        final long totalLength = totalLengthStr != null && totalLengthStr.length() != 0
                ? Long.parseLong(totalLengthStr)
                : -1L;

        if (log.isDebugEnabled()) {
            log.debug("contentType=" + contentType + ", contentLength=" + contentLengthStr + ", totalLength="
                    + totalLength);
        }

        istrm = incomingStreams != null ? (HIncomingStreamSync) incomingStreams.get(targetId.getStreamId())
                : null;

        if (istrm == null) {

            if (log.isDebugEnabled())
                log.debug("create HInputStreamBuffer");
            long length = totalLength >= 0 ? totalLength : contentLength;
            istrm = new HIncomingStreamSync(targetId, contentType, length, contentDisposition,
                    HConstants.REQUEST_TIMEOUT_MILLIS, tempDir) {

                @Override
                public void close() throws IOException {
                    if (log.isDebugEnabled())
                        log.debug("close " + targetId + "(");
                    Long streamId = getTargetId().getStreamId();
                    incomingStreams.remove(streamId);
                    super.close();
                    if (log.isDebugEnabled())
                        log.debug(")close");
                }
            };

            if (log.isDebugEnabled())
                log.debug("put incoming stream into map, targetId=" + targetId);
            incomingStreams.put(targetId.getStreamId(), istrm);
        }

        // Notify threads waiting to read this stream
        synchronized (this) {
            notifyAll();
        }

    } catch (Throwable e) {
        throw new BException(BExceptionC.IOERROR, "Failed to add incoming stream", e);
    }

    if (log.isDebugEnabled())
        log.debug(")addIncomingStreamSync2=" + istrm);
    return istrm;
}