Example usage for javax.servlet.http HttpServletRequest getContentType

List of usage examples for javax.servlet.http HttpServletRequest getContentType

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getContentType.

Prototype

public String getContentType();

Source Link

Document

Returns the MIME type of the body of the request, or null if the type is not known.

Usage

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

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    boolean mediaIsValid = true;
    ServletContext context = super.getServletContext();
    String repositoryPath = (String) context.getAttribute("FILEUPLOAD_REPOSITORY_PATH");
    String saveToDb = (String) context.getAttribute("FILEUPLOAD_SAVE_MEDIA_TO_DB");

    log.debug("req content length =" + req.getContentLength());
    log.debug("req content type =" + req.getContentType());

    // we get media location in assessmentXXX/questionXXX/agentId/audio_assessmentGradingIdXXX.au form
    String suffix = req.getParameter("suffix");
    if (suffix == null || ("").equals(suffix))
        suffix = "au";
    String mediaLocation = req.getParameter("media") + "." + suffix;
    log.debug("****media location=" + mediaLocation);
    String response = "empty";

    // test for nonemptiness first
    if (mediaLocation != null && !(mediaLocation.trim()).equals("")) {
        File repositoryPathDir = new File(repositoryPath);
        mediaLocation = repositoryPathDir.getCanonicalPath() + "/" + mediaLocation;
        File mediaFile = new File(mediaLocation);

        if (mediaFile.getCanonicalPath().equals(mediaLocation)) {
            File mediaDir = mediaFile.getParentFile();
            if (!mediaDir.exists())
                mediaDir.mkdirs();//from  w  ww .j  a v  a  2  s .com
            //log.debug("*** directory exist="+mediaDir.exists());
            mediaIsValid = writeToFile(req, mediaLocation);
        } else {
            log.debug("****Error in file paths " + mediaFile.getCanonicalPath() + " is not equal to "
                    + mediaLocation);
            mediaIsValid = false;
        }

        //this is progess for SAK-5792, comment is out for now
        //zip_mediaLocation = createZipFile(mediaDir.getPath(), mediaLocation);
    }

    //#2 - record media as question submission
    if (mediaIsValid) {
        // note that this delivery bean is empty. this is not the same one created for the
        // user during take assessment.
        try {
            response = submitMediaAsAnswer(req, mediaLocation, saveToDb);
            log.info(
                    "Audio has been saved and submitted as answer to the question. Any old recordings have been removed from the system.");
        } catch (Exception ex) {
            log.info(ex.getMessage());
        }
    }
    res.setContentType("text/plain");
    res.setContentLength(response.length());
    PrintWriter out = res.getWriter();
    out.println(response);
    out.close();
    out.flush();
}

From source file:com.controller.UploadLogo.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  w  w. j a  v a 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
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    getSqlMethodsInstance().session = request.getSession();
    String filePath = null;
    String fileName = null, fieldName = null, uploadPath = null, uploadType = null;
    RequestDispatcher request_dispatcher = null;

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {
        uploadPath = AppConstants.USER_LOGO;

        // Verify the content type
        String contentType = request.getContentType();

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

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

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

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

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

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                boolean ch = fi.isFormField();

                if (!fi.isFormField()) {

                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();

                    String uid = (String) getSqlMethodsInstance().session.getAttribute("EmailID");

                    int UID = getSqlMethodsInstance().getUserID(uid);
                    uploadPath = uploadPath + File.separator + UID + File.separator + "logo";

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

                    //                                int inStr = fileName.indexOf(".");
                    //                                String Str = fileName.substring(0, inStr);
                    //
                    //                                fileName = Str + "_" + UID + ".jpeg";
                    fileName = fileName + "_" + UID;
                    getSqlMethodsInstance().session.setAttribute("UID", UID);
                    getSqlMethodsInstance().session.setAttribute("ImageFileName", fileName);
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();

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

                    getSqlMethodsInstance().updateUsers(UID, fileName);
                    out.println("Uploaded Filename: " + filePath + "<br>");
                }

            }
        }

    } catch (Exception ex) {
        logger.log(Level.SEVERE, util.Utility.logMessage(ex, "Exception while updating org name:",
                getSqlMethodsInstance().error));

        out.println(getSqlMethodsInstance().error);
    } finally {
        out.close();
        getSqlMethodsInstance().closeConnection();
    }

}

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

private ModelAndView getSparqlUpdateResult(Transaction transaction, HttpServletRequest request,
        HttpServletResponse response) throws ServerHTTPException, ClientHTTPException, HTTPException {
    String sparqlUpdateString = null;
    final String contentType = request.getContentType();
    if (contentType != null && contentType.contains(Protocol.SPARQL_UPDATE_MIME_TYPE)) {
        try {/*from www  .  j  a va 2 s . c  om*/
            final String encoding = request.getCharacterEncoding() != null ? request.getCharacterEncoding()
                    : "UTF-8";
            sparqlUpdateString = IOUtils.toString(request.getInputStream(), encoding);
        } catch (IOException e) {
            logger.warn("error reading sparql update string from request body", e);
            throw new ClientHTTPException(SC_BAD_REQUEST,
                    "could not read SPARQL update string from body: " + e.getMessage());
        }
    } else {
        sparqlUpdateString = request.getParameter(Protocol.UPDATE_PARAM_NAME);
    }

    logger.debug("SPARQL update string: {}", sparqlUpdateString);

    // default query language is SPARQL
    QueryLanguage queryLn = QueryLanguage.SPARQL;

    String queryLnStr = request.getParameter(QUERY_LANGUAGE_PARAM_NAME);
    logger.debug("query language param = {}", queryLnStr);

    if (queryLnStr != null) {
        queryLn = QueryLanguage.valueOf(queryLnStr);

        if (queryLn == null) {
            throw new ClientHTTPException(SC_BAD_REQUEST, "Unknown query language: " + queryLnStr);
        }
    }

    String baseURI = request.getParameter(Protocol.BASEURI_PARAM_NAME);

    // determine if inferred triples should be included in query evaluation
    boolean includeInferred = ProtocolUtil.parseBooleanParam(request, INCLUDE_INFERRED_PARAM_NAME, true);

    // build a dataset, if specified
    String[] defaultRemoveGraphURIs = request.getParameterValues(REMOVE_GRAPH_PARAM_NAME);
    String[] defaultInsertGraphURIs = request.getParameterValues(INSERT_GRAPH_PARAM_NAME);
    String[] defaultGraphURIs = request.getParameterValues(USING_GRAPH_PARAM_NAME);
    String[] namedGraphURIs = request.getParameterValues(USING_NAMED_GRAPH_PARAM_NAME);

    SimpleDataset dataset = new SimpleDataset();

    if (defaultRemoveGraphURIs != null) {
        for (String graphURI : defaultRemoveGraphURIs) {
            try {
                IRI uri = null;
                if (!"null".equals(graphURI)) {
                    uri = SimpleValueFactory.getInstance().createIRI(graphURI);
                }
                dataset.addDefaultRemoveGraph(uri);
            } catch (IllegalArgumentException e) {
                throw new ClientHTTPException(SC_BAD_REQUEST,
                        "Illegal URI for default remove graph: " + graphURI);
            }
        }
    }

    if (defaultInsertGraphURIs != null && defaultInsertGraphURIs.length > 0) {
        String graphURI = defaultInsertGraphURIs[0];
        try {
            IRI uri = null;
            if (!"null".equals(graphURI)) {
                uri = SimpleValueFactory.getInstance().createIRI(graphURI);
            }
            dataset.setDefaultInsertGraph(uri);
        } catch (IllegalArgumentException e) {
            throw new ClientHTTPException(SC_BAD_REQUEST, "Illegal URI for default insert graph: " + graphURI);
        }
    }

    if (defaultGraphURIs != null) {
        for (String defaultGraphURI : defaultGraphURIs) {
            try {
                IRI uri = null;
                if (!"null".equals(defaultGraphURI)) {
                    uri = SimpleValueFactory.getInstance().createIRI(defaultGraphURI);
                }
                dataset.addDefaultGraph(uri);
            } catch (IllegalArgumentException e) {
                throw new ClientHTTPException(SC_BAD_REQUEST,
                        "Illegal URI for default graph: " + defaultGraphURI);
            }
        }
    }

    if (namedGraphURIs != null) {
        for (String namedGraphURI : namedGraphURIs) {
            try {
                IRI uri = null;
                if (!"null".equals(namedGraphURI)) {
                    uri = SimpleValueFactory.getInstance().createIRI(namedGraphURI);
                }
                dataset.addNamedGraph(uri);
            } catch (IllegalArgumentException e) {
                throw new ClientHTTPException(SC_BAD_REQUEST, "Illegal URI for named graph: " + namedGraphURI);
            }
        }
    }

    try {
        // determine if any variable bindings have been set on this update.
        @SuppressWarnings("unchecked")
        Enumeration<String> parameterNames = request.getParameterNames();

        Map<String, Value> bindings = new HashMap<>();
        while (parameterNames.hasMoreElements()) {
            String parameterName = parameterNames.nextElement();

            if (parameterName.startsWith(BINDING_PREFIX) && parameterName.length() > BINDING_PREFIX.length()) {
                String bindingName = parameterName.substring(BINDING_PREFIX.length());
                Value bindingValue = ProtocolUtil.parseValueParam(request, parameterName,
                        SimpleValueFactory.getInstance());
                bindings.put(bindingName, bindingValue);
            }
        }

        transaction.executeUpdate(queryLn, sparqlUpdateString, baseURI, includeInferred, dataset, bindings);

        return new ModelAndView(EmptySuccessView.getInstance());
    } catch (UpdateExecutionException | InterruptedException | ExecutionException 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("Repository update error: " + e.getMessage(), e);
        }
    } catch (RepositoryException 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("Repository update error: " + e.getMessage(), e);
        }
    } catch (MalformedQueryException e) {
        ErrorInfo errInfo = new ErrorInfo(ErrorType.MALFORMED_QUERY, e.getMessage());
        throw new ClientHTTPException(SC_BAD_REQUEST, errInfo.toString());
    }
}

From source file:org.apache.jena.fuseki.servlets.Dispatcher.java

/**
 * Identify the operation being requested.
 * It is analysing the HTTP request using global configuration. 
 * The decision is is based on//from ww  w. j a v  a 2s. c  o  m
 * <ul>
 * <li>Query parameters (URL query string or HTML form)</li>
 * <li>Content-Type header</li>
 * <li>Otherwise it is a plain REST (quads) operation.chooseOperation</li>
 * </ul>
 * The HTTP Method is not considered.
 * <p>
 * The operation is not guaranteed to be supported on every {@link DataService}
 * nor that access control will allow it to be performed. 
 */
public static Operation chooseOperation(HttpAction action) {
    HttpServletRequest request = action.getRequest();

    // ---- Dispatch based on HttpParams : Query, Update, GSP.
    // -- Query
    boolean isQuery = request.getParameter(HttpNames.paramQuery) != null;
    if (isQuery)
        return Query;
    // -- Update
    // Standards name "update", non-standard name "request" (old use by Fuseki)
    boolean isUpdate = request.getParameter(HttpNames.paramUpdate) != null
            || request.getParameter(HttpNames.paramRequest) != null;
    if (isUpdate)
        // The SPARQL_Update servlet will deal with using GET.
        return Update;

    // -- SPARQL Graph Store Protocol
    boolean hasParamGraph = request.getParameter(HttpNames.paramGraph) != null;
    boolean hasParamGraphDefault = request.getParameter(HttpNames.paramGraphDefault) != null;
    if (hasParamGraph || hasParamGraphDefault)
        return gspOperation(action, request);

    // -- Any other queryString
    // Place for an extension point.
    boolean hasParams = request.getParameterMap().size() > 0;
    if (hasParams) {
        // Unrecognized ?key=value
        ServletOps.errorBadRequest(
                "Malformed request: unrecognized query string parameters: " + request.getQueryString());
    }

    // ---- Content-type
    // We don't wire in all the RDF syntaxes.
    // Instead, "Quads" drops through to the default operation.

    // This does not have the ";charset="
    String ct = request.getContentType();
    if (ct != null) {
        Operation operation = action.getOperationRegistry().findByContentType(ct);
        if (operation != null)
            return operation;
    }

    // ---- No registered content type, no query parameters.
    // Plain HTTP operation on the dataset handled as quads or rejected.
    return quadsOperation(action, request);
}

From source file:admin.controller.ServletAddLooks.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  ww w. jav  a2s .c  om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    super.processRequest(request, response);
    String filePath;
    String fileName, fieldName;
    Looks look;
    RequestDispatcher request_dispatcher;
    String look_name = null;
    Integer organization_id = 0;
    boolean check;
    look = new Looks();
    check = false;

    response.setContentType("text/html;charset=UTF-8");
    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {
        String uploadPath = AppConstants.LOOK_IMAGES_HOME;

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

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

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

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

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

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();

                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    try {
                        if (fieldName.equals("lookname")) {
                            look_name = fi.getString();
                        }
                        if (fieldName.equals("organization")) {
                            organization_id = Integer.parseInt(fi.getString());
                        }
                    } catch (Exception e) {
                        logger.log(Level.SEVERE, "Exception while getting the look_name and organization_id",
                                e);
                    }
                } else {
                    check = look.checkAvailability(look_name, organization_id);

                    if (check == false) {
                        fieldName = fi.getFieldName();
                        fileName = fi.getName();

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

                        //                            int inStr = fileName.indexOf(".");
                        //                            String Str = fileName.substring(0, inStr);
                        //
                        //                            fileName = look_name + "_" + Str + ".png";
                        fileName = look_name + "_" + fileName;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

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

                        fi.write(storeFile);

                        look.addLooks(look_name, fileName, organization_id);
                        response.sendRedirect(request.getContextPath() + "/admin/looks.jsp");
                    } else {
                        response.sendRedirect(request.getContextPath() + "/admin/looks.jsp?exist=exist");
                    }

                }
            }

        } else {
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while uploading the Looks image", ex);
    }
}

From source file:com.controller.changeLogo.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w  w w.  j a  va2 s .co  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    getSqlMethodsInstance().session = request.getSession();
    String filePath = null;
    String fileName = null, fieldName = null, uploadPath = null, uploadType = null;
    RequestDispatcher request_dispatcher = null;

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {
        uploadPath = AppConstants.USER_LOGO;

        // Verify the content type
        String contentType = request.getContentType();

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

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

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

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

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

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    fieldName = fi.getFieldName();
                    if (fieldName.equals("upload")) {
                        uploadType = fi.getString();
                    }

                } else {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();

                    Integer UID = (Integer) getSqlMethodsInstance().session.getAttribute("UID");

                    uploadPath = uploadPath + File.separator + UID + File.separator + "logo";

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

                    //                                int inStr = fileName.indexOf(".");
                    //                                String Str = fileName.substring(0, inStr);
                    //
                    //                                fileName = Str + "_" + UID + ".jpeg";
                    fileName = fileName + "_" + UID;
                    getSqlMethodsInstance().session.setAttribute("ImageFileName", fileName);
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();

                    if (uploadType.equals("update")) {
                        String file_name_to_delete = getSqlMethodsInstance().getLogofileName(UID);
                        String filePath_to_delete = uploadPath + File.separator + file_name_to_delete;

                        File deletefile = new File(filePath_to_delete);
                        deletefile.delete();
                    }

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

                    getSqlMethodsInstance().updateUsers(UID, fileName);
                    out.println("Uploaded Filename: " + filePath + "<br>");

                    response.sendRedirect(request.getContextPath() + "/settings.jsp");

                }

            }
        }

    } catch (Exception ex) {
        logger.log(Level.SEVERE, util.Utility.logMessage(ex, "Exception while updating org name:",
                getSqlMethodsInstance().error));

        out.println(getSqlMethodsInstance().error);
    } finally {
        out.close();
        getSqlMethodsInstance().closeConnection();
    }

}

From source file:org.eclipse.lyo.samples.sharepoint.adapter.ResourceService.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("entered do Post for /resource");
    boolean isFileUpload = ServletFileUpload.isMultipartContent(request);
    String contentType = request.getContentType();

    if (!isFileUpload && !IConstants.CT_RDF_XML.equals(contentType)) {
        throw new ShareServiceException(IConstants.SC_UNSUPPORTED_MEDIA_TYPE);
    }/*www .j  a va2s  .  c om*/

    InputStream content = request.getInputStream();

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

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

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

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

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

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

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

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

            ByteArrayInputStream bais = isToBais(content);

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

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

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

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

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

            store.update(resource, userUri);

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

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

        } catch (ShareServerException e) {
            throw new ShareServiceException(IConstants.SC_BAD, e);
        }

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

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

            store.storeBinaryResource(content, id);

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

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

        } catch (ShareServerException e) {
            throw new ShareServiceException(IConstants.SC_BAD, e);
        }
    }
}

From source file:org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilter.java

private HttpResponse forward(HttpClient httpclient, String verb, String uri, HttpServletRequest request,
        MultiValueMap<String, String> headers, MultiValueMap<String, String> params, InputStream requestEntity)
        throws Exception {
    Map<String, Object> info = this.helper.debug(verb, uri, headers, params, requestEntity);
    URL host = RequestContext.getCurrentContext().getRouteHost();
    HttpHost httpHost = getHttpHost(host);
    uri = StringUtils.cleanPath((host.getPath() + uri).replaceAll("/{2,}", "/"));
    int contentLength = request.getContentLength();
    InputStreamEntity entity = new InputStreamEntity(requestEntity, contentLength,
            request.getContentType() != null ? ContentType.create(request.getContentType()) : null);

    HttpRequest httpRequest = buildHttpRequest(verb, uri, entity, headers, params);
    try {/*from   w ww  .ja v  a2s  . co  m*/
        log.debug(httpHost.getHostName() + " " + httpHost.getPort() + " " + httpHost.getSchemeName());
        HttpResponse zuulResponse = forwardRequest(httpclient, httpHost, httpRequest);
        this.helper.appendDebug(info, zuulResponse.getStatusLine().getStatusCode(),
                revertHeaders(zuulResponse.getAllHeaders()));
        return zuulResponse;
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        // httpclient.getConnectionManager().shutdown();
    }
}

From source file:io.mapzone.arena.tracker.GoogleAnalyticsTracker.java

private void extractParams(List<NameValuePair> params, ServletRequestEvent event) {
    params.add(new BasicNameValuePair("t", "event"));
    params.add(new BasicNameValuePair("ec", "externalRequest"));
    HttpServletRequest request = (HttpServletRequest) event.getServletRequest();
    if (request != null) {
        try {/*www  . j  a va2 s  . co  m*/
            // TODO, add user or session or something else here authToken
            String clientId = "anonymous";
            String authToken = request.getParameter("authToken");
            if (!StringUtils.isBlank(authToken)) {
                clientId = authToken;
            }
            addEncoded(params, "cid", clientId);

            // request.get
            String context = request.getServletPath();
            int index = context.lastIndexOf("/");
            if (index != -1) {
                context = context.substring(index + 1);
            }
            addEncoded(params, "ea", context);
            if (!StringUtils.isBlank(request.getContentType())) {
                index = request.getContentType().toLowerCase().lastIndexOf("charset=");
                if (index != -1) {
                    addEncoded(params, "de", request.getContentType().substring(index + 8));
                }
            }
            addEncoded(params, "dl", request.getServletPath() + "?" + request.getQueryString());
            addEncoded(params, "el", request.getQueryString());
            addEncoded(params, "dr", request.getHeader("Referer"));
            addEncoded(params, "ua", request.getHeader("User-Agent"));
            addEncoded(params, "uip", request.getRemoteAddr());
        } catch (UnsupportedEncodingException e) {
            // do nothing
            log.error(e);
        }

    }
}

From source file:com.krawler.esp.servlets.ExportImportContactsServlet.java

private String getFileHeaders(HttpServletRequest request)
        throws SessionExpiredException, ServiceException, IOException, com.krawler.utils.json.JSONException {
    String contentType = request.getContentType();
    CsvReader csvReader = null;//from w  w w .  ja  va 2 s  .c o  m
    String header = "";
    String realFileName = request.getParameter("fileName");
    {
        FileInputStream fstream = null;

        try {
            if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
                String fileid = UUID.randomUUID().toString();
                String userid = AuthHandler.getUserid(request);
                String f1 = uploadDocument(request, fileid, userid);
                if (f1.length() != 0) {
                    String destinationDirectory = StorageHandler.GetDocStorePath()
                            + StorageHandler.GetFileSeparator() + "importcontacts"
                            + StorageHandler.GetFileSeparator() + userid;
                    File csv = new File(destinationDirectory + StorageHandler.GetFileSeparator() + f1);
                    String mimetype = SVNFileUtil.detectMimeType(csv);
                    boolean flag = false;
                    if (StringUtil.isNullOrEmpty(mimetype)) {
                        flag = true;
                    }
                    if (flag) {
                        fstream = new FileInputStream(csv);
                        csvReader = new CsvReader(new InputStreamReader(fstream));
                        csvReader.readRecord();
                        int i = 0;
                        if (!StringUtil.isNullOrEmpty(csvReader.get(i))) {
                            while (!(StringUtil.isNullOrEmpty(csvReader.get(i)))) {
                                header += "{\"header\":\"" + csvReader.get(i) + "\",\"index\":" + i + "},";
                                i++;
                            }
                            header = header.substring(0, header.length() - 1);
                            header = "{\"success\": true,\"FileName\":\"" + f1 + "\",\"RealFileName\":\""
                                    + realFileName + "\",\"FileID\":\"" + fileid + "\",\"Headers\":[" + header
                                    + "]}";
                            // e.g. Header= "{'Task Name':0,'Start Date':1,'End Date':2,'Proirity':3,'Percent Completed':4,'Notes':5}";
                        } else {
                            header = "{\"success\": false}";
                        }
                    } else {
                        header = "{\"success\": false}";
                    }
                } else {
                    header = "{\"success\": true,\"FileName\":\"\"}";
                }

            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ExportImportContactsServlet.class.getName()).log(Level.SEVERE, "File not Found",
                    ex);
        } catch (ConfigurationException ex) {
            KrawlerLog.op.warn(ex.getMessage());
            throw ServiceException.FAILURE("ExportImportContactsServlet", ex);
        } finally {
            if (csvReader != null) {
                csvReader.close();
            }
            if (fstream != null) {
                fstream.close();
            }
        }
    }
    return header;
}