Example usage for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax.

Prototype

public void setSizeMax(long sizeMax) 

Source Link

Document

Sets the maximum allowed upload size.

Usage

From source file:org.nordapp.web.servlet.DEVServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {/*  w  ww.j  av a 2s  . c  o  m*/

        //@SuppressWarnings("unused")
        final String mandatorId = RequestPath.getMandator(req);
        final String uuid = RequestPath.getSession(req);

        //
        // Session handler (HTTP) and session control (OSGi)
        //
        //SessionControl ctrl = new HttpSessionControlImpl(context, req.getSession());
        SessionControl ctrl = new SessionControlImpl(context);
        ctrl.setMandatorID(mandatorId);
        ctrl.setCertID(uuid);

        //RequestHandler rqHdl = new RequestHandler(context, ctrl);

        ctrl.loadTempSession();
        ctrl.getAll();
        ctrl.incRequestCounter();
        ctrl.setAll();
        ctrl.saveTempSession();

        //
        // Session and other services
        //
        String cert = null;

        //The '0' session of the mandator
        Session mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), "0");

        //The 'user' session
        mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(),
                ctrl.decodeCert().toString());
        if (mSession == null) {
            List<String> list = ctrl.getShortTimePassword();
            if (ctrl.getCertID() == null || (!list.contains(ctrl.getCertID())))
                throw new UnavailableException("Needs a valid User-Session.");
        }

        //The mandator
        Mandator mandator = MandatorServiceImpl.getMandator(context, ctrl.getMandatorID());
        if (mandator == null) {
            throw new UnavailableException("Needs a valid mandator id:" + ctrl.getMandatorID() + ".");
        }

        //
        // Get some data
        //

        FilePath tmpLoc = FilePath.get(mandator.getPath()).add("temp");

        //
        // prepare the engine
        //

        String[] elem = RequestPath.getPath(req);
        if (elem.length != 0)
            throw new MalformedURLException("The URL needs the form '" + req.getServletPath() + "' but was '"
                    + req.getRequestURI() + "'");

        //
        // Initialize the work
        //

        ServiceReference<DeployService> srDeploy = context.getServiceReference(DeployService.class);
        if (srDeploy == null)
            throw new IOException(
                    "The deploy service reference is not available (maybe down or a version conflict).");
        DeployService svDeploy = context.getService(srDeploy);
        if (svDeploy == null)
            throw new IOException("The deploy service is not available (maybe down or a version conflict).");

        String processID = IdGen.getURLSafeString(IdGen.getUUID());
        String mandatorID = ctrl.getMandatorID();
        String groupID = ctrl.getGroupID();
        String artifactID = ctrl.getArtifactID();

        //
        // Process upload
        //

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // sets memory threshold - beyond which files are stored in disk
        factory.setSizeThreshold(MEMORY_THRESHOLD);

        File repository = tmpLoc.add("http-upload").toFile();
        if (!repository.exists()) {
            repository.mkdirs();
        }
        factory.setRepository(repository);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // sets maximum size of request (include file + form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        try {
            // parses the request's content to extract file data
            //@SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(req);

            if (formItems != null && formItems.size() > 0) {
                // iterates over form's fields
                for (FileItem item : formItems) {
                    // processes only fields that are not form fields
                    if (item.isFormField()) {
                        //data
                    } else {
                        File zip = svDeploy.createEmptyZip(processID, mandatorID, groupID, artifactID);
                        OutputStream os = new FileOutputStream(zip);
                        InputStream is = item.getInputStream();
                        try {
                            IOUtils.copy(is, os);
                        } finally {
                            IOUtils.closeQuietly(is);
                            IOUtils.closeQuietly(os);
                        }
                        svDeploy.zipToData(processID, mandatorID, groupID, artifactID, zip.getName());
                    } //fi
                } //for
            } //fi
        } catch (Exception ex) {
            req.setAttribute("message", "There was an error: " + ex.getMessage());
        }

        //
        // Prints the result from the user-session
        //
        StringBuffer buffer = new StringBuffer();
        ResponseHandler rsHdl = new ResponseHandler(context, ctrl);

        logger.debug("The user session is{}found mandatorId:{}, sessionId:{}.",
                (mSession == null ? " not " : " "), ctrl.getMandatorID(), ctrl.getCertID());
        rsHdl.getSessionData(buffer, mSession);

        //
        //
        //
        byte[] bytes = buffer.toString().getBytes();

        //
        // Send the resource
        //
        rsHdl.avoidCaching(resp);
        rsHdl.sendData(bytes, resp);

    } catch (Exception e) {
        ResponseHandler rsHdl = new ResponseHandler(context, null);
        rsHdl.sendError(logger, e, resp, null);
    }
}

From source file:org.nordapp.web.servlet.IOServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {/*from w w w.j a v  a 2 s .co m*/

        //@SuppressWarnings("unused")
        final String mandatorId = RequestPath.getMandator(req);
        final String uuid = RequestPath.getSession(req);

        //
        // Session handler (HTTP) and session control (OSGi)
        //
        //SessionControl ctrl = new HttpSessionControlImpl(context, req.getSession());
        SessionControl ctrl = new SessionControlImpl(context);
        ctrl.setMandatorID(mandatorId);
        ctrl.setCertID(uuid);

        //RequestHandler rqHdl = new RequestHandler(context, ctrl);

        ctrl.loadTempSession();
        ctrl.getAll();
        ctrl.incRequestCounter();

        //
        // Session and other services
        //
        String cert = null;

        //The '0' session of the mandator
        Session mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), "0");
        Integer baseIndex = ((Integer) mSession.getValue(Session.ENGINE_BASE_INDEX)).intValue();

        //The 'user' session
        mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(),
                ctrl.decodeCert().toString());
        if (mSession == null) {
            List<String> list = ctrl.getShortTimePassword();
            if (ctrl.getCertID() == null || (!list.contains(ctrl.getCertID())))
                throw new UnavailableException("Needs a valid User-Session.");
        }

        //The mandator
        Mandator mandator = MandatorServiceImpl.getMandator(context, ctrl.getMandatorID());
        if (mandator == null) {
            throw new UnavailableException("Needs a valid mandator id:" + ctrl.getMandatorID() + ".");
        }

        EngineBaseService engineBaseService = null;
        try {
            engineBaseService = EngineBaseServiceImpl.getService(context, ctrl.getMandatorID(),
                    String.valueOf(baseIndex));
        } catch (InvalidSyntaxException e1) {
        }
        if (engineBaseService == null)
            throw new IOException(
                    "The mandator base service is not available (maybe down or a version conflict).");

        //
        // Get some data
        //

        FilePath tmpLoc = FilePath.get(mandator.getPath()).add("temp");

        //
        // prepare the engine
        //

        String[] elem = RequestPath.getPath(req);
        if (elem.length == 0)
            throw new MalformedURLException("The URL needs the form '" + req.getServletPath()
                    + "/function-id' but was '" + req.getRequestURI() + "'");

        BigInteger engineId = ctrl.decodeCert();
        String functionId = elem.length >= 1 ? elem[0] : null;

        Engine engine = null;
        try {
            engine = engineBaseService.getEngine(engineId);
        } catch (Exception e1) {
            throw new ServletException(e1);
        }
        if (!engine.isLogin())
            throw new ServletException("There is no login to this session.");

        //
        // Initialize the work
        //

        engine.setLocalValue(httpSessionID, engineId.toString()); //ctrl.decodeCert().toString()

        IdRep processUUID = IdGen.getUUID();
        engine.setLocalValue(httpProcessID, processUUID);

        IOContainer ioc = new IOContainer();
        ioc.setProcessUUID(processUUID.toString());
        engine.setLocalValue(httpIOContainer, ioc);

        //
        // Process upload
        //

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // sets memory threshold - beyond which files are stored in disk
        factory.setSizeThreshold(MEMORY_THRESHOLD);

        File repository = tmpLoc.add("http-upload").toFile();
        if (!repository.exists()) {
            repository.mkdirs();
        }
        factory.setRepository(repository);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // sets maximum size of request (include file + form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        try {
            // parses the request's content to extract file data
            //@SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(req);

            if (formItems != null && formItems.size() > 0) {
                // iterates over form's fields
                for (FileItem item : formItems) {
                    // processes only fields that are not form fields
                    if (item.isFormField()) {
                        //data
                        ioc.setField(item.getFieldName(), item);
                    } else {
                        ioc.setFile(IdGen.getUUID().toString(), item);
                    } //fi
                } //for
            } //fi
        } catch (Exception ex) {
            req.setAttribute("message", "There was an error: " + ex.getMessage());
        }

        //
        // Call script
        //

        try {
            engine.call(functionId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        ioc.cleanup();
        engine.setLocalValue(httpSessionID, null);
        engine.setLocalValue(httpProcessID, null);
        engine.setLocalValue(httpIOContainer, null);

        //
        // Prints the result from the user-session
        //
        StringBuffer buffer = new StringBuffer();
        ResponseHandler rsHdl = new ResponseHandler(context, ctrl);

        logger.debug("The user session is{}found mandatorId:{}, sessionId:{}.",
                (mSession == null ? " not " : " "), ctrl.getMandatorID(), ctrl.getCertID());
        rsHdl.getSessionData(buffer, mSession);

        //
        //
        //
        byte[] bytes = buffer.toString().getBytes();

        //
        // Send the resource
        //
        rsHdl.avoidCaching(resp);
        rsHdl.sendData(bytes, resp);

    } catch (Exception e) {
        ResponseHandler rsHdl = new ResponseHandler(context, null);
        rsHdl.sendError(logger, e, resp, null);
    }
}

From source file:org.nordapp.web.servlet.SessionCallServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {/*www . j  av  a 2  s.  c om*/

        //@SuppressWarnings("unused")
        final String mandatorId = RequestPath.getMandator(req);
        final String uuid = RequestPath.getSession(req);

        //
        // Session handler
        //
        //SessionControl ctrl = new HttpSessionControlImpl(context, req.getSession());
        SessionControl ctrl = new SessionControlImpl(context);
        ctrl.setMandatorID(mandatorId);
        ctrl.setCertID(uuid);

        ctrl.loadTempSession();
        ctrl.getAll();
        ctrl.incRequestCounter();
        ctrl.setAll();
        ctrl.saveTempSession();

        //
        // Process upload
        //

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // sets memory threshold - beyond which files are stored in disk
        factory.setSizeThreshold(MEMORY_THRESHOLD);

        //The mandator
        Mandator mandator = MandatorServiceImpl.getMandator(context, ctrl.getMandatorID());
        if (mandator == null) {
            throw new UnavailableException("Needs a valid mandator id:" + ctrl.getMandatorID() + ".");
        }

        FilePath tmpLoc = FilePath.get(mandator.getPath()).add("temp");

        File repository = tmpLoc.add("http-upload").toFile();
        if (!repository.exists()) {
            repository.mkdirs();
        }
        factory.setRepository(repository);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // sets maximum size of request (include file + form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // Gets the JSON data
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(LinkedHashMap.class, new GsonHashMapDeserializer());
        Gson gson = gsonBuilder.create();

        Map<String, Object> res = new HashMap<String, Object>();
        try {
            // parses the request's content to extract file data
            //@SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(req);

            if (formItems != null && formItems.size() > 0) {
                // iterates over form's fields
                for (FileItem item : formItems) {
                    // processes only fields that are not form fields
                    if (item.isFormField()) {
                        //data
                        res.put(item.getFieldName(), item.getString());
                        //ioc.setField(item.getFieldName(), item);
                    } else {
                        //Gets JSON as Stream
                        Reader json = new InputStreamReader(item.getInputStream());
                        //String json = item.getString();

                        try {
                            @SuppressWarnings("unchecked")
                            LinkedHashMap<String, Object> mapJ = gson.fromJson(json, LinkedHashMap.class);
                            for (String key : mapJ.keySet()) {
                                Object val = mapJ.get(key);
                                if (val == null)
                                    continue;

                                res.put(key, val);
                            } //for
                        } finally {
                            json.close();
                        }
                    } //fi
                } //for

            } //fi
        } catch (Exception ex) {
            req.setAttribute("message", "There was an error: " + ex.getMessage());
        }

        process(ctrl, req, resp, res);

    } catch (Exception e) {
        ResponseHandler rsHdl = new ResponseHandler(context, null);
        rsHdl.sendError(logger, e, resp, null);
    }
}

From source file:org.ofbiz.webapp.event.RestEventHandler.java

/**
* @see org.ofbiz.webapp.event.EventHandler#invoke(ConfigXMLReader.Event, ConfigXMLReader.RequestMap, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*//* ww  w.j  a v  a 2s .  com*/
public String invoke(Event event, RequestMap requestMap, HttpServletRequest request,
        HttpServletResponse response) throws EventHandlerException {
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    Delegator delegator = (GenericDelegator) request.getAttribute("delegator");
    DispatchContext dctx = dispatcher.getDispatchContext();

    HttpSession session = request.getSession();

    Map<String, Object> serviceContext = FastMap.newInstance();

    Map<String, Object> parameterMap = null;
    List uploadedFileList = new ArrayList();
    String method = request.getMethod();
    if ("POST".equals(method) || "PUT".equals(method)) {
        // get the service name and parameters
        BufferedReader reader = null;
        StringBuilder buf = new StringBuilder();
        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        try {
            Map<String, Object> multiPartMap = new HashMap<String, Object>();
            if (isMultiPart) {
                // get the http upload configuration
                String maxSizeStr = EntityUtilProperties.getPropertyValue("general.properties",
                        "http.upload.max.size", "-1", dctx.getDelegator());
                long maxUploadSize = -1;
                try {
                    maxUploadSize = Long.parseLong(maxSizeStr);
                } catch (NumberFormatException e) {
                    Debug.logError(e,
                            "Unable to obtain the max upload size from general.properties; using default -1",
                            module);
                    maxUploadSize = -1;
                }
                // get the http size threshold configuration - files bigger than this will be
                // temporarly stored on disk during upload
                String sizeThresholdStr = EntityUtilProperties.getPropertyValue("general.properties",
                        "http.upload.max.sizethreshold", "10240", dctx.getDelegator());
                int sizeThreshold = 10240; // 10K
                try {
                    sizeThreshold = Integer.parseInt(sizeThresholdStr);
                } catch (NumberFormatException e) {
                    Debug.logError(e,
                            "Unable to obtain the threshold size from general.properties; using default 10K",
                            module);
                    sizeThreshold = -1;
                }
                // directory used to temporarily store files that are larger than the configured size threshold
                String tmpUploadRepository = EntityUtilProperties.getPropertyValue("general.properties",
                        "http.upload.tmprepository", "runtime/tmp", dctx.getDelegator());
                String encoding = request.getCharacterEncoding();
                // check for multipart content types which may have uploaded items

                ServletFileUpload upload = new ServletFileUpload(
                        new DiskFileItemFactory(sizeThreshold, new File(tmpUploadRepository)));

                // create the progress listener and add it to the session
                FileUploadProgressListener listener = new FileUploadProgressListener();
                upload.setProgressListener(listener);
                session.setAttribute("uploadProgressListener", listener);

                if (encoding != null) {
                    upload.setHeaderEncoding(encoding);
                }
                upload.setSizeMax(maxUploadSize);

                List<FileItem> uploadedItems = null;
                try {
                    uploadedItems = UtilGenerics.<FileItem>checkList(upload.parseRequest(request));
                } catch (FileUploadException e) {
                    throw new EventHandlerException("Problems reading uploaded data", e);
                }
                if (uploadedItems != null) {
                    for (FileItem item : uploadedItems) {
                        String fieldName = item.getFieldName();
                        if (item.isFormField() || item.getName() == null) {
                            if (multiPartMap.containsKey(fieldName)) {
                                Object mapValue = multiPartMap.get(fieldName);
                                if (mapValue instanceof List<?>) {
                                    checkList(mapValue, Object.class).add(item.getString());
                                } else if (mapValue instanceof String) {
                                    List<String> newList = new LinkedList<String>();
                                    newList.add((String) mapValue);
                                    newList.add(item.getString());
                                    multiPartMap.put(fieldName, newList);
                                } else {
                                    Debug.logWarning(
                                            "Form field found [" + fieldName + "] which was not handled!",
                                            module);
                                }
                            } else {
                                if (encoding != null) {
                                    try {
                                        multiPartMap.put(fieldName, item.getString(encoding));
                                    } catch (java.io.UnsupportedEncodingException uee) {
                                        Debug.logError(uee, "Unsupported Encoding, using deafault", module);
                                        multiPartMap.put(fieldName, item.getString());
                                    }
                                } else {
                                    multiPartMap.put(fieldName, item.getString());
                                }
                            }
                        } else {
                            Map<String, Object> uploadedMap = FastMap.newInstance();
                            String fileName = item.getName();
                            if (fileName.indexOf('\\') > -1 || fileName.indexOf('/') > -1) {
                                // get just the file name IE and other browsers also pass in the local path
                                int lastIndex = fileName.lastIndexOf('\\');
                                if (lastIndex == -1) {
                                    lastIndex = fileName.lastIndexOf('/');
                                }
                                if (lastIndex > -1) {
                                    fileName = fileName.substring(lastIndex + 1);
                                }
                            }
                            uploadedMap.put("uploadedFile", ByteBuffer.wrap(item.get()));
                            uploadedMap.put("_uploadedFile_size", Long.valueOf(item.getSize()));
                            uploadedMap.put("_uploadedFile_fileName", fileName);
                            uploadedMap.put("_uploadedFile_contentType", item.getContentType());
                            uploadedFileList.add(uploadedMap);
                        }
                    }
                }
                request.setAttribute("multiPartMap", multiPartMap);
                Map<String, Object> rawParametersMap = UtilHttp.getParameterMap(request, null, null);
                Set<String> urlOnlyParameterNames = UtilHttp.getUrlOnlyParameterMap(request).keySet();
                Map<String, Object> requestBodyMap = null;
                try {
                    requestBodyMap = RequestBodyMapHandlerFactory.extractMapFromRequestBody(request);
                } catch (IOException ioe) {
                    Debug.logWarning(ioe, module);
                }
                if (requestBodyMap != null) {
                    rawParametersMap.putAll(requestBodyMap);
                }

            } else {
                //                      parameterMap = requestByMap(request, response);
                // read the inputstream buffer
                String line;
                //                      reader = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));  
                reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
                while ((line = reader.readLine()) != null) {
                    buf.append(line).append("\n");
                }
            }

        } catch (Exception e) {
            throw new EventHandlerException(e.getMessage(), e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    throw new EventHandlerException(e.getMessage(), e);
                }
            }
        }
        Debug.logInfo("json: " + buf.toString(), module);
        Map<String, Object> rawParametersMap = UtilHttp.getParameterMap(request, null, null);
        serviceContext.putAll(rawParametersMap);
        if (UtilValidate.isNotEmpty(rawParametersMap)) {
            serviceContext.putAll(rawParametersMap);
        } else if (buf.toString().length() > 0) {
            JSONObject json = JSONObject.fromObject(buf.toString());
            serviceContext.putAll(json);
        }
    }
    if ("GET".equals(method) || "DELETE".equals(method)) {
        Map<String, Object> rawParametersMap = UtilHttp.getParameterMap(request, null, null);
        serviceContext.putAll(rawParametersMap);

    }

    String serviceName = getOverrideViewUri(request.getPathInfo());
    String restIdValue = "";
    List<String> pathItemList = StringUtil.split(serviceName, "/");
    if (pathItemList.size() > 1) {
        serviceName = pathItemList.get(0);
        restIdValue = pathItemList.get(1);
    }
    Debug.log("serviceName:\n" + serviceName + "\n", module);
    GenericValue userLogin = null;

    try {
        ModelService model = dctx.getModelService(serviceName);

        if (model == null) {
            sendError(response, "Problem processing the service", serviceName);
            Debug.logError("Could not find Service [" + serviceName + "].", module);
            return null;
        }

        //                 if (!model.export) {
        //                     sendError(response, "Problem processing the service", serviceName);
        //                     Debug.logError("Trying to call Service [" + serviceName + "] that is not exported.", module);
        //                     return null;
        //                 }

        if (model.auth) {
            String username = request.getHeader("USERNAME");
            String password = request.getHeader("PASSWORD");
            if (UtilValidate.isNotEmpty(username) && UtilValidate.isNotEmpty(password)) {
                serviceContext.remove("USERNAME");
                serviceContext.remove("PASSWORD");
            } else {
                username = request.getParameter("USERNAME");
                password = request.getParameter("PASSWORD");
            }

            //                   GenericValue yuemeiUser = delegator.findOne("YuemeiUser", UtilMisc.toMap("userLoginId", username), true);
            //                   if(UtilValidate.isNotEmpty(yuemeiUser)){
            //                     String tenantId = yuemeiUser.getString("tenantId");
            //                     if(UtilValidate.isNotEmpty(tenantId)){
            //                         delegator = DelegatorFactory.getDelegator(delegator.getDelegatorBaseName() + "#" + tenantId);
            //                         dispatcher = GenericDispatcher.getLocalDispatcher(dispatcher.getName(), delegator);
            //                     }
            //                   }

            Map<String, Object> loginResult = dispatcher.runSync("userLogin",
                    UtilMisc.toMap("login.username", username, "login.password", password));//, "locale", Locale.CHINESE
            Debug.log(loginResult.toString(), module);
            if (ServiceUtil.isSuccess(loginResult)) {
                userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", username), false);
            }
            if (UtilValidate.isEmpty(userLogin)) {
                sendError(response, "Problem processing the service, check your USERNAME and PASSWORD.",
                        "serviceName");
            }
        }

        Locale locale = UtilHttp.getLocale(request);
        TimeZone timeZone = UtilHttp.getTimeZone(request);
        // get only the parameters for this service - converted to proper type
        // TODO: pass in a list for error messages, like could not convert type or not a proper X, return immediately with messages if there are any
        List<Object> errorMessages = FastList.newInstance();
        //              serviceContext = model.makeValid(serviceContext, ModelService.IN_PARAM, true, errorMessages, timeZone, locale);
        if (errorMessages.size() > 0) {

            sendError(response, "Problem processing the serviceContext Valid," + errorMessages, serviceName);
        }

        // include the UserLogin value object
        if (userLogin != null) {
            serviceContext.put("userLogin", userLogin);
        }

        // include the Locale object
        if (locale != null) {
            serviceContext.put("locale", locale);
        }

        // include the TimeZone object
        if (timeZone != null) {
            serviceContext.put("timeZone", timeZone);
        }
        if (UtilValidate.isNotEmpty(model.defaultEntityName)) {
            ModelEntity modelEntity = delegator.getModelEntity(model.defaultEntityName);
            if (UtilValidate.isNotEmpty(restIdValue) && modelEntity.getPksSize() == 1) {
                String pkFieldName = modelEntity.getPkFieldNames().get(0);
                serviceContext.put(pkFieldName, restIdValue);
            }
        }
    } catch (GenericServiceException e) {
        Debug.logError(e.getMessage(), module);
        sendError(response, "Problem processing the service, check ." + e.getMessage(), serviceName);
    } catch (GenericEntityException e) {
        Debug.logError(e.getMessage(), module);
        sendError(response, "Problem processing the service, check your ." + e.getMessage(), serviceName);
    }

    //response.setContentType("text/xml");
    response.setContentType("application/json");

    Debug.logVerbose("[Processing]: REST Event", module);

    try {
        if (UtilValidate.isNotEmpty(uploadedFileList))
            serviceContext.put("uploadedFileList", uploadedFileList);
        if (UtilValidate.isNotEmpty(serviceName) && !"updateOutsideExperts".equals(serviceName)
                && !"saveTgAndItemAndDse".equals(serviceName) && !"getMyFriends".equals(serviceName)) {
            serviceContext.remove("json");
        }
        Map<String, Object> serviceResults = dispatcher.runSync(serviceName, serviceContext);
        Debug.logVerbose("[EventHandler] : Service invoked", module);
        createAndSendRESTResponse(serviceResults, serviceName, response);
    } catch (GenericServiceException e) {

        if (e.getMessageList() == null) {
            sendError(response, e.getMessage(), serviceName);
        } else {
            sendError(response, e.getMessageList(), serviceName);
        }
        Debug.logError(e, module);
        return null;

    }

    return null;
}

From source file:org.ofbiz.webapp.event.RestEventHandler.java

private Map getServiceContext(HttpServletRequest request, DispatchContext dctx, ModelService model,
        Locale locale) throws EventHandlerException {

    // get the http upload configuration
    String maxSizeStr = EntityUtilProperties.getPropertyValue("general.properties", "http.upload.max.size",
            "-1", dctx.getDelegator());
    long maxUploadSize = -1;
    try {/*w ww.j a v  a 2s  . co m*/
        maxUploadSize = Long.parseLong(maxSizeStr);
    } catch (NumberFormatException e) {
        Debug.logError(e, "Unable to obtain the max upload size from general.properties; using default -1",
                module);
        maxUploadSize = -1;
    }
    // get the http size threshold configuration - files bigger than this will be
    // temporarly stored on disk during upload
    String sizeThresholdStr = EntityUtilProperties.getPropertyValue("general.properties",
            "http.upload.max.sizethreshold", "10240", dctx.getDelegator());
    int sizeThreshold = 10240; // 10K
    try {
        sizeThreshold = Integer.parseInt(sizeThresholdStr);
    } catch (NumberFormatException e) {
        Debug.logError(e, "Unable to obtain the threshold size from general.properties; using default 10K",
                module);
        sizeThreshold = -1;
    }
    // directory used to temporarily store files that are larger than the configured size threshold
    String tmpUploadRepository = EntityUtilProperties.getPropertyValue("general.properties",
            "http.upload.tmprepository", "runtime/tmp", dctx.getDelegator());
    String encoding = request.getCharacterEncoding();
    // check for multipart content types which may have uploaded items
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    Map<String, Object> multiPartMap = FastMap.newInstance();
    if (isMultiPart) {
        ServletFileUpload upload = new ServletFileUpload(
                new DiskFileItemFactory(sizeThreshold, new File(tmpUploadRepository)));

        // create the progress listener and add it to the session
        FileUploadProgressListener listener = new FileUploadProgressListener();
        upload.setProgressListener(listener);
        //session.setAttribute("uploadProgressListener", listener);

        if (encoding != null) {
            upload.setHeaderEncoding(encoding);
        }
        upload.setSizeMax(maxUploadSize);

        List<FileItem> uploadedItems = null;
        try {
            uploadedItems = UtilGenerics.<FileItem>checkList(upload.parseRequest(request));
        } catch (FileUploadException e) {
            throw new EventHandlerException("Problems reading uploaded data", e);
        }
        if (uploadedItems != null) {
            for (FileItem item : uploadedItems) {
                String fieldName = item.getFieldName();
                //byte[] itemBytes = item.get();
                /*
                Debug.logInfo("Item Info [" + fieldName + "] : " + item.getName() + " / " + item.getSize() + " / " +
                       item.getContentType() + " FF: " + item.isFormField(), module);
                */
                if (item.isFormField() || item.getName() == null) {
                    if (multiPartMap.containsKey(fieldName)) {
                        Object mapValue = multiPartMap.get(fieldName);
                        if (mapValue instanceof List<?>) {
                            checkList(mapValue, Object.class).add(item.getString());
                        } else if (mapValue instanceof String) {
                            List<String> newList = FastList.newInstance();
                            newList.add((String) mapValue);
                            newList.add(item.getString());
                            multiPartMap.put(fieldName, newList);
                        } else {
                            Debug.logWarning("Form field found [" + fieldName + "] which was not handled!",
                                    module);
                        }
                    } else {
                        if (encoding != null) {
                            try {
                                multiPartMap.put(fieldName, item.getString(encoding));
                            } catch (java.io.UnsupportedEncodingException uee) {
                                Debug.logError(uee, "Unsupported Encoding, using deafault", module);
                                multiPartMap.put(fieldName, item.getString());
                            }
                        } else {
                            multiPartMap.put(fieldName, item.getString());
                        }
                    }
                } else {
                    String fileName = item.getName();
                    if (fileName.indexOf('\\') > -1 || fileName.indexOf('/') > -1) {
                        // get just the file name IE and other browsers also pass in the local path
                        int lastIndex = fileName.lastIndexOf('\\');
                        if (lastIndex == -1) {
                            lastIndex = fileName.lastIndexOf('/');
                        }
                        if (lastIndex > -1) {
                            fileName = fileName.substring(lastIndex + 1);
                        }
                    }
                    multiPartMap.put(fieldName, ByteBuffer.wrap(item.get()));
                    multiPartMap.put("_" + fieldName + "_size", Long.valueOf(item.getSize()));
                    multiPartMap.put("_" + fieldName + "_fileName", fileName);
                    multiPartMap.put("_" + fieldName + "_contentType", item.getContentType());
                }
            }
        }
    }

    // store the multi-part map as an attribute so we can access the parameters
    //request.setAttribute("multiPartMap", multiPartMap);

    Map<String, Object> rawParametersMap = UtilHttp.getParameterMap(request, null, null);
    Set<String> urlOnlyParameterNames = UtilHttp.getUrlOnlyParameterMap(request).keySet();

    // we have a service and the model; build the context
    Map<String, Object> serviceContext = FastMap.newInstance();
    for (ModelParam modelParam : model.getInModelParamList()) {
        String name = modelParam.name;

        // don't include userLogin, that's taken care of below
        if ("userLogin".equals(name))
            continue;
        // don't include locale, that is also taken care of below
        if ("locale".equals(name))
            continue;
        // don't include timeZone, that is also taken care of below
        if ("timeZone".equals(name))
            continue;

        Object value = null;
        if (UtilValidate.isNotEmpty(modelParam.stringMapPrefix)) {
            Map<String, Object> paramMap = UtilHttp.makeParamMapWithPrefix(request, multiPartMap,
                    modelParam.stringMapPrefix, null);
            value = paramMap;
            if (Debug.verboseOn())
                Debug.logVerbose("Set [" + modelParam.name + "]: " + paramMap, module);
        } else if (UtilValidate.isNotEmpty(modelParam.stringListSuffix)) {
            List<Object> paramList = UtilHttp.makeParamListWithSuffix(request, multiPartMap,
                    modelParam.stringListSuffix, null);
            value = paramList;
        } else {
            // first check the multi-part map
            value = multiPartMap.get(name);

            // next check attributes; do this before parameters so that attribute which can be changed by code can override parameters which can't
            if (UtilValidate.isEmpty(value)) {
                Object tempVal = request.getAttribute(name);
                if (tempVal != null) {
                    value = tempVal;
                }
            }

            // check the request parameters
            if (UtilValidate.isEmpty(value)) {
                //ServiceEventHandler.checkSecureParameter(requestMap, urlOnlyParameterNames, name, session, serviceName, dctx.getDelegator());

                // if the service modelParam has allow-html="any" then get this direct from the request instead of in the parameters Map so there will be no canonicalization possibly messing things up
                if ("any".equals(modelParam.allowHtml)) {
                    value = request.getParameter(name);
                } else {
                    // use the rawParametersMap from UtilHttp in order to also get pathInfo parameters, do canonicalization, etc
                    value = rawParametersMap.get(name);
                }

                // make any composite parameter data (e.g., from a set of parameters {name_c_date, name_c_hour, name_c_minutes})
                if (value == null) {
                    value = UtilHttp.makeParamValueFromComposite(request, name, locale);
                }
            }

            // then session
            //                   if (UtilValidate.isEmpty(value)) {
            //                       Object tempVal = request.getSession().getAttribute(name);
            //                       if (tempVal != null) {
            //                           value = tempVal;
            //                       }
            //                   }

            // no field found
            if (value == null) {
                //still null, give up for this one
                continue;
            }

            if (value instanceof String && ((String) value).length() == 0) {
                // interpreting empty fields as null values for each in back end handling...
                value = null;
            }
        }
        // set even if null so that values will get nulled in the db later on
        serviceContext.put(name, value);
    }

    return serviceContext;

}

From source file:org.ofbiz.webapp.event.ServiceEventHandler.java

/**
 * @see org.ofbiz.webapp.event.EventHandler#invoke(ConfigXMLReader.Event, ConfigXMLReader.RequestMap, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from ww w  .ja v a  2  s .  co  m
public String invoke(Event event, RequestMap requestMap, HttpServletRequest request,
        HttpServletResponse response) throws EventHandlerException {
    // make sure we have a valid reference to the Service Engine
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    if (dispatcher == null) {
        throw new EventHandlerException("The local service dispatcher is null");
    }
    DispatchContext dctx = dispatcher.getDispatchContext();
    if (dctx == null) {
        throw new EventHandlerException("Dispatch context cannot be found");
    }

    // get the details for the service(s) to call
    String mode = SYNC;
    String serviceName = null;

    if (UtilValidate.isEmpty(event.path)) {
        mode = SYNC;
    } else {
        mode = event.path;
    }

    // make sure we have a defined service to call
    serviceName = event.invoke;
    if (serviceName == null) {
        throw new EventHandlerException("Service name (eventMethod) cannot be null");
    }
    if (Debug.verboseOn())
        Debug.logVerbose("[Set mode/service]: " + mode + "/" + serviceName, module);

    // some needed info for when running the service
    Locale locale = UtilHttp.getLocale(request);
    TimeZone timeZone = UtilHttp.getTimeZone(request);
    HttpSession session = request.getSession();
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");

    // get the service model to generate context
    ModelService model = null;

    try {
        model = dctx.getModelService(serviceName);
    } catch (GenericServiceException e) {
        throw new EventHandlerException("Problems getting the service model", e);
    }

    if (model == null) {
        throw new EventHandlerException("Problems getting the service model");
    }

    if (Debug.verboseOn()) {
        Debug.logVerbose("[Processing]: SERVICE Event", module);
        Debug.logVerbose("[Using delegator]: " + dispatcher.getDelegator().getDelegatorName(), module);
    }

    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    Map<String, Object> multiPartMap = new HashMap<String, Object>();
    if (isMultiPart) {
        // get the http upload configuration
        String maxSizeStr = EntityUtilProperties.getPropertyValue("general.properties", "http.upload.max.size",
                "-1", dctx.getDelegator());
        long maxUploadSize = -1;
        try {
            maxUploadSize = Long.parseLong(maxSizeStr);
        } catch (NumberFormatException e) {
            Debug.logError(e, "Unable to obtain the max upload size from general.properties; using default -1",
                    module);
            maxUploadSize = -1;
        }
        // get the http size threshold configuration - files bigger than this will be
        // temporarly stored on disk during upload
        String sizeThresholdStr = EntityUtilProperties.getPropertyValue("general.properties",
                "http.upload.max.sizethreshold", "10240", dctx.getDelegator());
        int sizeThreshold = 10240; // 10K
        try {
            sizeThreshold = Integer.parseInt(sizeThresholdStr);
        } catch (NumberFormatException e) {
            Debug.logError(e, "Unable to obtain the threshold size from general.properties; using default 10K",
                    module);
            sizeThreshold = -1;
        }
        // directory used to temporarily store files that are larger than the configured size threshold
        String tmpUploadRepository = EntityUtilProperties.getPropertyValue("general.properties",
                "http.upload.tmprepository", "runtime/tmp", dctx.getDelegator());
        String encoding = request.getCharacterEncoding();
        // check for multipart content types which may have uploaded items

        ServletFileUpload upload = new ServletFileUpload(
                new DiskFileItemFactory(sizeThreshold, new File(tmpUploadRepository)));

        // create the progress listener and add it to the session
        FileUploadProgressListener listener = new FileUploadProgressListener();
        upload.setProgressListener(listener);
        session.setAttribute("uploadProgressListener", listener);

        if (encoding != null) {
            upload.setHeaderEncoding(encoding);
        }
        upload.setSizeMax(maxUploadSize);

        List<FileItem> uploadedItems = null;
        try {
            uploadedItems = UtilGenerics.<FileItem>checkList(upload.parseRequest(request));
        } catch (FileUploadException e) {
            throw new EventHandlerException("Problems reading uploaded data", e);
        }
        if (uploadedItems != null) {
            for (FileItem item : uploadedItems) {
                String fieldName = item.getFieldName();
                //byte[] itemBytes = item.get();
                /*
                Debug.logInfo("Item Info [" + fieldName + "] : " + item.getName() + " / " + item.getSize() + " / " +
                    item.getContentType() + " FF: " + item.isFormField(), module);
                */
                if (item.isFormField() || item.getName() == null) {
                    if (multiPartMap.containsKey(fieldName)) {
                        Object mapValue = multiPartMap.get(fieldName);
                        if (mapValue instanceof List<?>) {
                            checkList(mapValue, Object.class).add(item.getString());
                        } else if (mapValue instanceof String) {
                            List<String> newList = new LinkedList<String>();
                            newList.add((String) mapValue);
                            newList.add(item.getString());
                            multiPartMap.put(fieldName, newList);
                        } else {
                            Debug.logWarning("Form field found [" + fieldName + "] which was not handled!",
                                    module);
                        }
                    } else {
                        if (encoding != null) {
                            try {
                                multiPartMap.put(fieldName, item.getString(encoding));
                            } catch (java.io.UnsupportedEncodingException uee) {
                                Debug.logError(uee, "Unsupported Encoding, using deafault", module);
                                multiPartMap.put(fieldName, item.getString());
                            }
                        } else {
                            multiPartMap.put(fieldName, item.getString());
                        }
                    }
                } else {
                    String fileName = item.getName();
                    if (fileName.indexOf('\\') > -1 || fileName.indexOf('/') > -1) {
                        // get just the file name IE and other browsers also pass in the local path
                        int lastIndex = fileName.lastIndexOf('\\');
                        if (lastIndex == -1) {
                            lastIndex = fileName.lastIndexOf('/');
                        }
                        if (lastIndex > -1) {
                            fileName = fileName.substring(lastIndex + 1);
                        }
                    }
                    multiPartMap.put(fieldName, ByteBuffer.wrap(item.get()));
                    multiPartMap.put("_" + fieldName + "_size", Long.valueOf(item.getSize()));
                    multiPartMap.put("_" + fieldName + "_fileName", fileName);
                    multiPartMap.put("_" + fieldName + "_contentType", item.getContentType());
                }
            }
        }
    }

    // store the multi-part map as an attribute so we can access the parameters
    request.setAttribute("multiPartMap", multiPartMap);

    Map<String, Object> rawParametersMap = UtilHttp.getParameterMap(request, null, null);
    Set<String> urlOnlyParameterNames = UtilHttp.getUrlOnlyParameterMap(request).keySet();
    Map<String, Object> requestBodyMap = null;
    try {
        requestBodyMap = RequestBodyMapHandlerFactory.extractMapFromRequestBody(request);
    } catch (IOException ioe) {
        Debug.logWarning(ioe, module);
    }
    if (requestBodyMap != null) {
        rawParametersMap.putAll(requestBodyMap);
    }

    // we have a service and the model; build the context
    Map<String, Object> serviceContext = new HashMap<String, Object>();
    for (ModelParam modelParam : model.getInModelParamList()) {
        String name = modelParam.name;

        // don't include userLogin, that's taken care of below
        if ("userLogin".equals(name))
            continue;
        // don't include locale, that is also taken care of below
        if ("locale".equals(name))
            continue;
        // don't include timeZone, that is also taken care of below
        if ("timeZone".equals(name))
            continue;

        Object value = null;
        if (UtilValidate.isNotEmpty(modelParam.stringMapPrefix)) {
            Map<String, Object> paramMap = UtilHttp.makeParamMapWithPrefix(request, multiPartMap,
                    modelParam.stringMapPrefix, null);
            value = paramMap;
            if (Debug.verboseOn())
                Debug.logVerbose("Set [" + modelParam.name + "]: " + paramMap, module);
        } else if (UtilValidate.isNotEmpty(modelParam.stringListSuffix)) {
            List<Object> paramList = UtilHttp.makeParamListWithSuffix(request, multiPartMap,
                    modelParam.stringListSuffix, null);
            value = paramList;
        } else {
            // first check the multi-part map
            value = multiPartMap.get(name);

            // next check attributes; do this before parameters so that attribute which can be changed by code can override parameters which can't
            if (UtilValidate.isEmpty(value)) {
                Object tempVal = request
                        .getAttribute(UtilValidate.isEmpty(modelParam.requestAttributeName) ? name
                                : modelParam.requestAttributeName);
                if (tempVal != null) {
                    value = tempVal;
                }
            }

            // check the request parameters
            if (UtilValidate.isEmpty(value)) {
                ServiceEventHandler.checkSecureParameter(requestMap, urlOnlyParameterNames, name, session,
                        serviceName, dctx.getDelegator());

                // if the service modelParam has allow-html="any" then get this direct from the request instead of in the parameters Map so there will be no canonicalization possibly messing things up
                if ("any".equals(modelParam.allowHtml)) {
                    value = request.getParameter(name);
                } else {
                    // use the rawParametersMap from UtilHttp in order to also get pathInfo parameters, do canonicalization, etc
                    value = rawParametersMap.get(name);
                }

                // make any composite parameter data (e.g., from a set of parameters {name_c_date, name_c_hour, name_c_minutes})
                if (value == null) {
                    value = UtilHttp.makeParamValueFromComposite(request, name, locale);
                }
            }

            // then session
            if (UtilValidate.isEmpty(value)) {
                Object tempVal = request.getSession()
                        .getAttribute(UtilValidate.isEmpty(modelParam.sessionAttributeName) ? name
                                : modelParam.sessionAttributeName);
                if (tempVal != null) {
                    value = tempVal;
                }
            }

            // no field found
            if (value == null) {
                //still null, give up for this one
                continue;
            }

            if (value instanceof String && ((String) value).length() == 0) {
                // interpreting empty fields as null values for each in back end handling...
                value = null;
            }
        }
        // set even if null so that values will get nulled in the db later on
        serviceContext.put(name, value);
    }

    // get only the parameters for this service - converted to proper type
    // TODO: pass in a list for error messages, like could not convert type or not a proper X, return immediately with messages if there are any
    List<Object> errorMessages = new LinkedList<Object>();
    serviceContext = model.makeValid(serviceContext, ModelService.IN_PARAM, true, errorMessages, timeZone,
            locale);
    if (errorMessages.size() > 0) {
        // uh-oh, had some problems...
        request.setAttribute("_ERROR_MESSAGE_LIST_", errorMessages);
        return "error";
    }

    // include the UserLogin value object
    if (userLogin != null) {
        serviceContext.put("userLogin", userLogin);
    }

    // include the Locale object
    if (locale != null) {
        serviceContext.put("locale", locale);
    }

    // include the TimeZone object
    if (timeZone != null) {
        serviceContext.put("timeZone", timeZone);
    }

    // invoke the service
    Map<String, Object> result = null;
    try {
        if (ASYNC.equalsIgnoreCase(mode)) {
            dispatcher.runAsync(serviceName, serviceContext);
        } else {
            result = dispatcher.runSync(serviceName, serviceContext);
        }
    } catch (ServiceAuthException e) {
        // not logging since the service engine already did
        request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage());
        return "error";
    } catch (ServiceValidationException e) {
        // not logging since the service engine already did
        request.setAttribute("serviceValidationException", e);
        if (e.getMessageList() != null) {
            request.setAttribute("_ERROR_MESSAGE_LIST_", e.getMessageList());
        } else {
            request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage());
        }
        return "error";
    } catch (GenericServiceException e) {
        Debug.logError(e, "Service invocation error", module);
        throw new EventHandlerException("Service invocation error", e.getNested());
    }

    String responseString = null;

    if (result == null) {
        responseString = ModelService.RESPOND_SUCCESS;
    } else {

        if (!result.containsKey(ModelService.RESPONSE_MESSAGE)) {
            responseString = ModelService.RESPOND_SUCCESS;
        } else {
            responseString = (String) result.get(ModelService.RESPONSE_MESSAGE);
        }

        // set the messages in the request; this will be picked up by messages.ftl and displayed
        request.setAttribute("_ERROR_MESSAGE_LIST_", result.get(ModelService.ERROR_MESSAGE_LIST));
        request.setAttribute("_ERROR_MESSAGE_MAP_", result.get(ModelService.ERROR_MESSAGE_MAP));
        request.setAttribute("_ERROR_MESSAGE_", result.get(ModelService.ERROR_MESSAGE));

        request.setAttribute("_EVENT_MESSAGE_LIST_", result.get(ModelService.SUCCESS_MESSAGE_LIST));
        request.setAttribute("_EVENT_MESSAGE_", result.get(ModelService.SUCCESS_MESSAGE));

        // set the results in the request
        for (Map.Entry<String, Object> rme : result.entrySet()) {
            String resultKey = rme.getKey();
            Object resultValue = rme.getValue();

            if (resultKey != null && !ModelService.RESPONSE_MESSAGE.equals(resultKey)
                    && !ModelService.ERROR_MESSAGE.equals(resultKey)
                    && !ModelService.ERROR_MESSAGE_LIST.equals(resultKey)
                    && !ModelService.ERROR_MESSAGE_MAP.equals(resultKey)
                    && !ModelService.SUCCESS_MESSAGE.equals(resultKey)
                    && !ModelService.SUCCESS_MESSAGE_LIST.equals(resultKey)) {
                request.setAttribute(resultKey, resultValue);
            }
        }
    }

    if (Debug.verboseOn())
        Debug.logVerbose("[Event Return]: " + responseString, module);

    if (("Y").equals(request.getParameter("json"))) {
        JSONObject json = JSONObject.fromObject(result);
        String jsonStr = json.toString();
        Debug.log(jsonStr);
        if (jsonStr == null) {
            // Debug.logError("JSON Object was empty; fatal error!",
            // module);
        }
        // set the X-JSON content type
        response.setContentType("textml");
        // jsonStr.length is not reliable for unicode characters
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-type", "text/html;charset=UTF-8");
            response.setContentLength(jsonStr.getBytes("UTF8").length);
        } catch (UnsupportedEncodingException e) {
            // Debug.logError("Problems with Json encoding");
        }
        // return the JSON String
        Writer out;
        try {
            out = response.getWriter();
            out.write(jsonStr);
            out.flush();
        } catch (IOException e) {
            // Debug.logError("Unable to get response writer",
            // module);
        }
        return null;
    } else {
        return responseString;
    }
}

From source file:org.olat.core.gui.components.form.flexible.impl.Form.java

/**
 * Internal helper to initialize the request parameter map an to temporary store the uploaded files when a multipart request is used. The files are stored to a
 * temporary location and a filehandle is added to the requestMultipartFiles map for later retrieval by the responsible FormItem.
 * //w  w w  .j  a  va2  s. com
 * @param ureq
 */
private void doInitRequestParameterAndMulipartData(UserRequest ureq) {
    // First fill parameter map either from multipart data or standard http request
    if (isMultipartEnabled() && ServletFileUpload.isMultipartContent(ureq.getHttpReq())) {
        long uploadSize = -1; // default unlimited
        // Limit size of complete upload form: upload size limit + 500k for
        // other input fields
        if (multipartUploadMaxSizeKB > -1) {
            uploadSize = (multipartUploadMaxSizeKB * 1024l * 1024l) + 512000l;
        }

        // Create a new file upload handler, use commons fileupload streaming
        // API to save files right to the tmp location
        ServletFileUpload uploadParser = new ServletFileUpload();
        uploadParser.setSizeMax(uploadSize);
        // Parse the request
        try {
            FileItemIterator iter = uploadParser.getItemIterator(ureq.getHttpReq());
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String itemName = item.getFieldName();
                InputStream itemStream = item.openStream();
                if (item.isFormField()) {
                    // Normal form item
                    // analog to ureq.getParameter in non-multipart mode
                    String value = Streams.asString(itemStream, "UTF-8");
                    addRequestParameter(itemName, value);
                } else {
                    // File item, store it to temp location
                    String fileName = item.getName();
                    // Cleanup IE filenames that are absolute
                    int slashpos = fileName.lastIndexOf("/");
                    if (slashpos != -1)
                        fileName = fileName.substring(slashpos + 1);
                    slashpos = fileName.lastIndexOf("\\");
                    if (slashpos != -1)
                        fileName = fileName.substring(slashpos + 1);

                    File tmpFile = new File(System.getProperty("java.io.tmpdir") + File.separator + "upload-"
                            + CodeHelper.getGlobalForeverUniqueID());

                    try {
                        FileUtils.save(itemStream, tmpFile);
                        // Only save non-empty file transfers, ignore empty transfers
                        // (e.g. already submitted in a previous form submit, not an error!)

                        // Removing empty file check for now ... was introduced to cope with
                        // browser trouble which probably is not there any more ...
                        // so empty fileName means nothing selected in the file element

                        // if (tmpFile.length() > 0) {
                        if (fileName.length() > 0) {
                            // a file was selected
                            // Save file and also original file name
                            requestMultipartFiles.put(itemName, tmpFile);
                            requestMultipartFileNames.put(itemName, fileName);
                            requestMultipartFileMimeTypes.put(itemName, item.getContentType());
                        } else {
                            if (tmpFile.exists())
                                tmpFile.delete();
                        }
                    } catch (OLATRuntimeException e) {
                        // Could not save stream for whatever reason, cleanup temp file and delegate exception
                        if (tmpFile.exists())
                            tmpFile.delete();

                        if (e.getCause() instanceof MalformedStreamException) {
                            logWarn("Could not read uploaded file >" + fileName
                                    + "< from stream. Possibly an attempt to upload a directory instead of a file (happens on Mac)",
                                    e);
                            return;
                        }

                        throw new OLATRuntimeException("Could not save uploaded file", e);
                    }
                }
            }
        } catch (SizeLimitExceededException sizeLimitExceededException) {
            logError("Error while dispatching multipart form: file limit (" + uploadSize + ") exceeded",
                    sizeLimitExceededException);
            requestError = REQUEST_ERROR_UPLOAD_LIMIT_EXCEEDED;
        } catch (IOException e) {
            logWarn("Error while dispatching multipart form: ioexception", e);
            requestError = REQUEST_ERROR_GENERAL;
        } catch (Exception e) {
            logError("Error while dispatching multipart form: general exception", e);
            requestError = REQUEST_ERROR_GENERAL;
        }
    } else {
        // Get parameters the standard way
        logDebug("Dispatching non-multipart form", null);
        Set<String> keys = ureq.getParameterSet();
        for (String key : keys) {
            String[] values = ureq.getHttpReq().getParameterValues(key);
            if (values != null) {
                requestParams.put(key, values);
            } else {
                addRequestParameter(key, ureq.getParameter(key));
            }
        }
    }
}

From source file:org.olat.restapi.support.MultipartReader.java

private final void apache(HttpServletRequest request, long uploadLimit) {
    ServletFileUpload uploadParser = new ServletFileUpload();
    uploadParser.setSizeMax((uploadLimit * 1024l) + 512000l);
    // Parse the request
    try {//from  w  w w.  j  a v a  2s . c  o  m
        FileItemIterator iter = uploadParser.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String itemName = item.getFieldName();
            InputStream itemStream = item.openStream();
            if (item.isFormField()) {
                String value = Streams.asString(itemStream, "UTF-8");
                fields.put(itemName, value);
            } else {
                // File item, store it to temp location
                filename = item.getName();
                contentType = item.getContentType();

                if (filename != null) {
                    filename = UUID.randomUUID().toString().replace("-", "") + "_" + filename;
                } else {
                    filename = "upload-" + UUID.randomUUID().toString().replace("-", "");
                }
                file = new File(WebappHelper.getTmpDir(), filename);
                try {
                    save(itemStream, file);
                } catch (Exception e) {
                    log.error("", e);
                }
            }
        }
    } catch (Exception e) {
        log.error("", e);
    }
}

From source file:org.onesocialweb.openfire.web.FileServlet.java

private void processPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
    final PrintWriter out = response.getWriter();

    // 1- Bind this request to a XMPP JID
    final JID user = getAuthenticatedUser(request);
    if (user == null) {
        throw new AuthenticationException();
    }/*from  w  w  w.ja va 2  s .  c  o m*/

    // 2- Process the file
    final UploadManager uploadManager = UploadManager.getInstance();

    // Files larger than a threshold should be stored on disk in temporary
    // storage place
    final DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(256000);
    factory.setRepository(getTempFolder());

    // Prepare the upload parser and set a max size to enforce
    final ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(512000000);

    // Get the request ID
    final String requestId = request.getParameter("requestId");

    // Create a progress listener
    ProgressListener progressListener = new ProgressListener() {
        private long lastNotification = 0;

        public void update(long pBytesRead, long pContentLength, int pItems) {
            if (lastNotification == 0 || (pBytesRead - lastNotification) > NOTIFICATION_THRESHOLD) {
                lastNotification = pBytesRead;
                UploadManager.getInstance().updateProgress(user, pBytesRead, pContentLength, requestId);
            }
        }
    };
    upload.setProgressListener(progressListener);

    // Process the upload
    List items = upload.parseRequest(request);
    for (Object objItem : items) {
        FileItem item = (FileItem) objItem;
        if (!item.isFormField()) {
            String fileID = UUID.randomUUID().toString();
            File target = new File(getUploadFolder(), fileID);
            item.write(target);
            UploadManager.getInstance().commitFile(user, target, item.getName(), requestId);
            break; // Store only one file
        }
    }
}

From source file:org.opensingular.form.wicket.mapper.attachment.upload.ServletFileUploadFactory.java

public ServletFileUpload makeServletFileUpload(UploadInfo uploadInfo) {
    final ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());

    servletFileUpload.setFileSizeMax(resolveMax(uploadInfo.getMaxFileSize(), config.getDefaultMaxFileSize(),
            config.getGlobalMaxFileSize()));

    servletFileUpload.setSizeMax(resolveMax(uploadInfo.getMaxFileSize() * uploadInfo.getMaxFileCount(),
            config.getDefaultMaxRequestSize(), config.getGlobalMaxRequestSize()));

    return servletFileUpload;
}