Example usage for org.apache.commons.fileupload FileItem get

List of usage examples for org.apache.commons.fileupload FileItem get

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem get.

Prototype

byte[] get();

Source Link

Document

Returns the contents of the file item as an array of bytes.

Usage

From source file:org.ofbiz.product.imagemanagement.ImageManagementServices.java

public static String multipleUploadImage(HttpServletRequest request, HttpServletResponse response)
        throws IOException, JDOMException {
    HttpSession session = request.getSession(true);
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");

    Map<String, String> formInput = FastMap.newInstance();
    ServletFileUpload fu = new ServletFileUpload(
            new DiskFileItemFactory(10240, FileUtil.getFile("runtime/tmp")));
    List<FileItem> lst = null;
    try {/*  w  w  w . j a  v a2  s .co m*/
        lst = UtilGenerics.checkList(fu.parseRequest(request));
    } catch (FileUploadException e4) {
        return e4.getMessage();
    }

    FileItem fi = null;
    FileItem imageFi = null;
    byte[] imageBytes = {};
    for (int i = 0; i < lst.size(); i++) {
        fi = lst.get(i);
        String fieldName = fi.getFieldName();
        if (fi.isFormField()) {
            String fieldStr = fi.getString();
            formInput.put(fieldName, fieldStr);
        } else if (fieldName.startsWith("imageData")) {
            Map<String, Object> passedParams = FastMap.newInstance();
            Map<String, Object> contentLength = FastMap.newInstance();
            if (josonMap == null) {
                josonMap = FastList.newInstance();
            }
            imageFi = fi;
            String fileName = fi.getName();
            String contentType = fi.getContentType();
            imageBytes = imageFi.get();
            ByteBuffer byteWrap = ByteBuffer.wrap(imageBytes);
            passedParams.put("userLogin", userLogin);
            passedParams.put("productId", formInput.get("productId"));
            passedParams.put("productContentTypeId", "IMAGE");
            passedParams.put("_uploadedFile_fileName", fileName);
            passedParams.put("_uploadedFile_contentType", contentType);
            passedParams.put("uploadedFile", byteWrap);
            passedParams.put("imageResize", formInput.get("imageResize"));
            contentLength.put("imageSize", imageFi.getSize());
            josonMap.add(contentLength);

            if (passedParams.get("productId") != null) {
                try {
                    dispatcher.runSync("addMultipleuploadForProduct", passedParams);
                } catch (GenericServiceException e) {
                    Debug.logError(e, module);
                    return e.getMessage();
                }
            }

        }
    }
    return "success";
}

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)
*///from ww  w . java 2  s  .  c om
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  w  w . j av a  2 s. c  o  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   w  w w. j  a v  a 2  s .c om
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.olanto.mySelfQD.server.UploadServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    String response = "";
    _logger.info("Execute action.");

    for (FileItem item : sessionFiles) {
        if (false == item.isFormField()) {
            try {
                if ((item.getName().toLowerCase().endsWith(".txt"))
                        || (item.getName().toLowerCase().endsWith(".html"))) { // charge sous forme de txt
                    response += cleanConvertedFile(UtilsFiles.file2String(item.getInputStream(), "UTF-8"));
                } else {
                    // need conversion
                    response += cleanConvertedFile(convertFileWithRMI(item.get(), item.getName()));
                }//  w  w  w  . j  a  va  2 s.  com
                System.out.println("File converted successfully");
            } catch (Exception ex2) {
                _logger.error(ex2);
            }
        }
    }
    // Remove files from session because we have a copy of them    
    removeSessionFileItems(request);
    // Send your customized message to the client.    
    return response;
}

From source file:org.olanto.TranslationText.server.UploadServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    String response = "";
    _logger.info("Execute action.");
    ext = getFileExtension();//from w ww. j ava 2 s  .c  om
    System.out.println("Do not convert files ending with: " + ext);

    for (FileItem item : sessionFiles) {
        if (false == item.isFormField()) {
            try {
                if ((item.getName().toLowerCase().endsWith(".txt")) || (item.getName().endsWith(ext))) { // charge sous forme de txt
                    response += cleanConvertedFile(
                            addMissingIds(UtilsFiles.file2String(item.getInputStream(), "UTF-8")));
                    System.out.println("File uploaded successfully ");
                } else {
                    // need conversion
                    response += cleanConvertedFile(convertFileWithRMI(item.get(), item.getName()));
                    System.out.println("File converted successfully");
                }

            } catch (Exception ex2) {
                _logger.error(ex2);
            }
        }
    }
    // Remove files from session because we have a copy of them    
    removeSessionFileItems(request);
    // Send your customized message to the client.  
    //        System.out.println(response);

    return response;
}

From source file:org.openbravo.erpCommon.info.ImageInfoBLOB.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    VariablesSecureApp vars = new VariablesSecureApp(request);

    String columnName = vars.getStringParameter("columnName");
    if (columnName == null || columnName.equals(""))
        columnName = vars.getStringParameter("inpColumnName");
    String tableId = vars.getStringParameter("tableId");
    if (tableId == null || tableId.equals("")) {
        tableId = vars.getStringParameter("inpTableId");
    }/*from w  w w  . ja v  a  2s .  co m*/
    if (tableId == null || tableId.equals("")) {
        String tabId = vars.getStringParameter("inpTabId");
        try {
            OBContext.setAdminMode(true);
            Tab tab = OBDal.getInstance().get(Tab.class, tabId);
            tableId = tab.getTable().getId();
        } finally {
            OBContext.restorePreviousMode();
        }
    }
    String imageID = vars.getStringParameter("inp" + Sqlc.TransformaNombreColumna(columnName));
    if (imageID == null || imageID.equals("")) {
        imageID = vars.getStringParameter("imageId");
    }

    String orgId = vars.getStringParameter("inpOrgId");
    if (orgId == null || orgId.equals("")) {
        orgId = vars.getStringParameter("inpadOrgId");
    }
    if (orgId == null || orgId.equals("")) {
        orgId = OBContext.getOBContext().getCurrentOrganization().getId();
    }

    String parentObjectId = vars.getStringParameter("parentObjectId");
    if (parentObjectId == null || parentObjectId.equals("")) {
        OBContext.setAdminMode(true);
        try {
            Table table = OBDal.getInstance().get(Table.class, vars.getStringParameter("inpTableId"));
            if (table != null) {
                List<Column> cols = table.getADColumnList();
                String keyCol = "";
                for (Column col : cols) {
                    if (col.isKeyColumn()) {
                        keyCol = col.getDBColumnName();
                        break;
                    }
                }
                parentObjectId = vars.getStringParameter("inp" + Sqlc.TransformaNombreColumna(keyCol));
            }
        } finally {
            OBContext.restorePreviousMode();
        }

    }
    if (vars.commandIn("DEFAULT")) {

        printPageFrame(response, vars, imageID, tableId, columnName, parentObjectId, orgId);
    } else if (vars.getCommand().equals("SAVE")) {
        OBContext.setAdminMode(true);
        try {
            final FileItem fi = vars.getMultiFile("inpFile");
            byte[] bytea = fi.get();
            Long[] size = Utility.computeImageSize(bytea);
            String mimeType = MimeTypeUtil.getInstance().getMimeTypeName(bytea);
            // Using DAL to write the image data to the database
            Image image;
            if (imageID == null || imageID.equals("")) {
                image = OBProvider.getInstance().get(Image.class);
                Organization org = OBDal.getInstance().get(Organization.class, orgId);
                image.setOrganization(org);
                image.setBindaryData(bytea);
                image.setActive(true);
                image.setName("Image");
                image.setWidth(size[0]);
                image.setHeight(size[1]);
                image.setMimetype(mimeType);
                OBDal.getInstance().save(image);
                OBDal.getInstance().flush();
            } else {
                image = OBDal.getInstance().get(Image.class, imageID);
                image.setActive(true);
                image.setBindaryData(bytea);
                image.setWidth(size[0]);
                image.setHeight(size[1]);
                image.setMimetype(mimeType);
                OBDal.getInstance().flush();
            }
            response.setContentType("text/html; charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writeRedirect(writer, image.getId(), columnName);
        } finally {
            OBContext.restorePreviousMode();
        }
    } else if (vars.getCommand().startsWith("SAVE_OB3")) {
        OBContext.setAdminMode(true);
        try {
            final FileItem fi = vars.getMultiFile("inpFile");
            byte[] bytea = fi.get();
            String mimeType = MimeTypeUtil.getInstance().getMimeTypeName(bytea);
            String imageSizeAction = vars.getStringParameter("imageSizeAction");
            String imageId = "";
            Long[] sizeOld = new Long[2];
            Long[] sizeNew = new Long[2];
            if (!mimeType.contains("image") || (!mimeType.contains("jpeg") && !mimeType.contains("png")
                    && !mimeType.contains("gif") && !mimeType.contains("bmp"))) {
                imageId = "";
                imageSizeAction = "WRONGFORMAT";
                sizeOld[0] = (long) 0;
                sizeOld[1] = (long) 0;
                sizeNew[0] = (long) 0;
                sizeNew[1] = (long) 0;
            } else {

                int newWidth;
                if (vars.getStringParameter("imageWidthValue") != "") {
                    newWidth = Integer.parseInt(vars.getStringParameter("imageWidthValue"));
                } else {
                    newWidth = 0;
                }
                int newHeight;
                if (vars.getStringParameter("imageHeightValue") != "") {
                    newHeight = Integer.parseInt(vars.getStringParameter("imageHeightValue"));
                } else {
                    newHeight = 0;
                }

                if (imageSizeAction.equals("ALLOWED") || imageSizeAction.equals("ALLOWED_MINIMUM")
                        || imageSizeAction.equals("ALLOWED_MAXIMUM") || imageSizeAction.equals("RECOMMENDED")
                        || imageSizeAction.equals("RECOMMENDED_MINIMUM")
                        || imageSizeAction.equals("RECOMMENDED_MAXIMUM")) {
                    sizeOld[0] = (long) newWidth;
                    sizeOld[1] = (long) newHeight;
                    sizeNew = Utility.computeImageSize(bytea);
                } else if (imageSizeAction.equals("RESIZE_NOASPECTRATIO")) {
                    sizeOld = Utility.computeImageSize(bytea);
                    bytea = Utility.resizeImageByte(bytea, newWidth, newHeight, false, false);
                    sizeNew = Utility.computeImageSize(bytea);
                } else if (imageSizeAction.equals("RESIZE_ASPECTRATIO")) {
                    sizeOld = Utility.computeImageSize(bytea);
                    bytea = Utility.resizeImageByte(bytea, newWidth, newHeight, true, true);
                    sizeNew = Utility.computeImageSize(bytea);
                } else if (imageSizeAction.equals("RESIZE_ASPECTRATIONL")) {
                    sizeOld = Utility.computeImageSize(bytea);
                    bytea = Utility.resizeImageByte(bytea, newWidth, newHeight, true, false);
                    sizeNew = Utility.computeImageSize(bytea);
                } else {
                    sizeOld = Utility.computeImageSize(bytea);
                    sizeNew = sizeOld;
                }

                mimeType = MimeTypeUtil.getInstance().getMimeTypeName(bytea);
                // Using DAL to write the image data to the database
                Image image;

                image = OBProvider.getInstance().get(Image.class);
                Organization org = OBDal.getInstance().get(Organization.class, orgId);
                image.setOrganization(org);
                image.setBindaryData(bytea);
                image.setActive(true);
                image.setName("Image");
                image.setWidth(sizeNew[0]);
                image.setHeight(sizeNew[1]);
                image.setMimetype(mimeType);
                OBDal.getInstance().save(image);
                OBDal.getInstance().flush();

                imageId = image.getId();
            }
            response.setContentType("text/html; charset=UTF-8");
            PrintWriter writer = response.getWriter();
            String selectorId = orgId = vars.getStringParameter("inpSelectorId");
            writeRedirectOB3(writer, selectorId, imageId, imageSizeAction, sizeOld, sizeNew, null);
        } catch (Throwable t) {
            log4j.error("Error uploading image", t);
            response.setContentType("text/html; charset=UTF-8");
            PrintWriter writer = response.getWriter();
            String selectorId = orgId = vars.getStringParameter("inpSelectorId");
            writeRedirectOB3(writer, selectorId, "", "ERROR_UPLOADING", new Long[] { 0L, 0L },
                    new Long[] { 0L, 0L }, t.getMessage());
        } finally {
            OBContext.restorePreviousMode();
        }
    } else if (vars.getCommand().equals("DELETE")) {
        if (imageID != null && !imageID.equals("")) {
            OBContext.setAdminMode(true);
            try {
                Image image = OBDal.getInstance().get(Image.class, imageID);
                Table table = OBDal.getInstance().get(Table.class, tableId);
                Entity entity = ModelProvider.getInstance().getEntityByTableName(table.getDBTableName());
                String propertyName = entity.getPropertyByColumnName(columnName).getName();
                BaseOBObject parentObject = OBDal.getInstance().get(entity.getName(), parentObjectId);
                parentObject.set(propertyName, null);
                OBDal.getInstance().flush();
                OBDal.getInstance().remove(image);
            } finally {
                OBContext.restorePreviousMode();
            }
            response.setContentType("text/html; charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writeRedirect(writer, "", columnName);
        } else {
            printPageFrame(response, vars, imageID, tableId, columnName, parentObjectId, orgId);
        }
    } else if (vars.getCommand().startsWith("DELETE_OB3")) {
        if (imageID != null && !imageID.equals("")) {
            OBContext.setAdminMode(true);
            try {
                Image image = OBDal.getInstance().get(Image.class, imageID);
                OBDal.getInstance().flush();
                OBDal.getInstance().remove(image);
            } finally {
                OBContext.restorePreviousMode();
            }
        } else {
            printPageFrame(response, vars, imageID, tableId, columnName, parentObjectId, orgId);
        }
    } else {
        pageError(response);
    }
}

From source file:org.opencms.ade.sitemap.CmsAliasBulkEditHelper.java

/**
 * Imports uploaded aliases from a request.<p>
 *
 * @param request the request containing the uploaded aliases
 * @param response the response//from w  w w .  j ava  2 s  . c o m
 * @throws Exception if something goes wrong
 */
public void importAliases(HttpServletRequest request, HttpServletResponse response) throws Exception {

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    @SuppressWarnings("unchecked")
    List<FileItem> items = upload.parseRequest(request);
    byte[] data = null;
    String siteRoot = null;
    String separator = ",";
    for (FileItem fileItem : items) {
        String name = fileItem.getFieldName();
        if (PARAM_IMPORTFILE.equals(name)) {
            data = fileItem.get();
        } else if (PARAM_SITEROOT.equals(name)) {
            siteRoot = new String(fileItem.get(), request.getCharacterEncoding());
        } else if (PARAM_SEPARATOR.equals(name)) {
            separator = new String(fileItem.get(), request.getCharacterEncoding());
        }
    }
    List<CmsAliasImportResult> result = new ArrayList<CmsAliasImportResult>();
    if ((siteRoot != null) && (data != null)) {
        result = OpenCms.getAliasManager().importAliases(m_cms, data, siteRoot, separator);
    }
    String key = CmsVfsSitemapService.addAliasImportResult(result);
    // only respond with a key, then the client can get the data for the key via GWT-RPC
    response.getWriter().print(key);
}

From source file:org.opencms.ade.upload.CmsUploadBean.java

/**
 * Creates the resources.<p>// www  .j av a  2s  . c  o  m
 * @param listener the listener
 * 
 * @throws CmsException if something goes wrong 
 * @throws UnsupportedEncodingException 
 */
private void createResources(CmsUploadListener listener) throws CmsException, UnsupportedEncodingException {

    // get the target folder
    String targetFolder = getTargetFolder();

    List<String> filesToUnzip = getFilesToUnzip();

    // iterate over the list of files to upload and create each single resource
    for (FileItem fileItem : m_multiPartFileItems) {
        if ((fileItem != null) && (!fileItem.isFormField())) {
            // read the content of the file
            byte[] content = fileItem.get();
            fileItem.delete();

            // determine the new resource name
            String fileName = m_parameterMap
                    .get(fileItem.getFieldName() + I_CmsUploadConstants.UPLOAD_FILENAME_ENCODED_SUFFIX)[0];
            fileName = URLDecoder.decode(fileName, "UTF-8");

            if (filesToUnzip.contains(CmsResource.getName(fileName.replace('\\', '/')))) {
                // import the zip
                CmsImportFolder importZip = new CmsImportFolder();
                try {
                    importZip.importZip(content, targetFolder, getCmsObject(), false);
                } finally {
                    // get the created resource names
                    m_resourcesCreated.addAll(importZip.getCreatedResourceNames());
                }
            } else {
                // create the resource
                String newResname = createSingleResource(fileName, targetFolder, content);
                // add the name of the created resource to the list of successful created resources
                m_resourcesCreated.add(newResname);
            }

            if (listener.isCanceled()) {
                throw listener.getException();
            }
        }
    }
}

From source file:org.opencms.editors.fckeditor.CmsFCKEditorFileBrowser.java

/**
 * Uploads a file to the OpenCms VFS and returns the necessary JavaScript for the file browser.<p>
 * /*from www . java 2  s  . c  o m*/
 * @return the necessary JavaScript for the file browser
 */
protected String uploadFile() {

    String errorCode = ERROR_UPLOAD_OK;
    try {
        // get the file item from the multipart request
        Iterator i = m_multiPartFileItems.iterator();
        FileItem fi = null;
        while (i.hasNext()) {
            fi = (FileItem) i.next();
            if (fi.getName() != null) {
                // found the file object, leave iteration
                break;
            } else {
                // this is no file object, check next item
                continue;
            }
        }

        if (fi != null) {
            String fileName = fi.getName();
            long size = fi.getSize();
            long maxFileSizeBytes = OpenCms.getWorkplaceManager().getFileBytesMaxUploadSize(getCms());
            // check file size
            if ((maxFileSizeBytes > 0) && (size > maxFileSizeBytes)) {
                // file size is larger than maximum allowed file size, throw an error
                throw new Exception();
            }
            byte[] content = fi.get();
            fi.delete();

            // single file upload
            String newResname = CmsResource.getName(fileName.replace('\\', '/'));
            // determine Title property value to set on new resource
            String title = newResname;
            if (title.lastIndexOf('.') != -1) {
                title = title.substring(0, title.lastIndexOf('.'));
            }
            List properties = new ArrayList(1);
            CmsProperty titleProp = new CmsProperty();
            titleProp.setName(CmsPropertyDefinition.PROPERTY_TITLE);
            if (OpenCms.getWorkplaceManager().isDefaultPropertiesOnStructure()) {
                titleProp.setStructureValue(title);
            } else {
                titleProp.setResourceValue(title);
            }
            properties.add(titleProp);

            // determine the resource type id from the given information
            int resTypeId = OpenCms.getResourceManager().getDefaultTypeForName(newResname).getTypeId();

            // calculate absolute path of uploaded resource
            newResname = getParamCurrentFolder() + newResname;

            if (!getCms().existsResource(newResname, CmsResourceFilter.IGNORE_EXPIRATION)) {
                try {
                    // create the resource
                    getCms().createResource(newResname, resTypeId, content, properties);
                } catch (CmsDbSqlException sqlExc) {
                    // SQL error, probably the file is too large for the database settings, delete file
                    getCms().lockResource(newResname);
                    getCms().deleteResource(newResname, CmsResource.DELETE_PRESERVE_SIBLINGS);
                    throw sqlExc;
                }
            } else {
                // resource exists, overwrite existing resource
                checkLock(newResname);
                CmsFile file = getCms().readFile(newResname, CmsResourceFilter.IGNORE_EXPIRATION);
                byte[] contents = file.getContents();
                try {
                    getCms().replaceResource(newResname, resTypeId, content, null);
                } catch (CmsDbSqlException sqlExc) {
                    // SQL error, probably the file is too large for the database settings, restore content
                    file.setContents(contents);
                    getCms().writeFile(file);
                    throw sqlExc;
                }
            }
        } else {
            // no upload file found
            throw new Exception();
        }
    } catch (Throwable e) {
        // something went wrong, change error code
        errorCode = ERROR_UPLOAD_INVALID;
    }

    // create JavaScript to return to file browser
    StringBuffer result = new StringBuffer(256);
    result.append("<html><head><script type=\"text/javascript\">\n");
    result.append("window.parent.frames[\"frmUpload\"].OnUploadCompleted(");
    result.append(errorCode);
    result.append(");\n");
    result.append("</script></head></html>");
    return result.toString();
}