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

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

Introduction

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

Prototype

long getSize();

Source Link

Document

Returns the size of the file item.

Usage

From source file:org.netxilia.server.rest.WorkbookResource.java

@SuppressWarnings("unchecked")
@POST//from ww  w  .  j av a 2 s.  co m
@Path("/{workbook}/import")
@Produces({ MediaType.TEXT_HTML })
public ModelAndView<ImportSheetModel> importSheetsFromExcel(@PathParam("workbook") WorkbookId workbookId,
        @Context HttpServletRequest request) throws ImportException, IOException {

    long t1 = System.currentTimeMillis();
    List<SheetFullName> sheetNames = new ArrayList<SheetFullName>();
    StringBuilderProcessingConsole console = new StringBuilderProcessingConsole();

    if (ServletFileUpload.isMultipartContent(request)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();

        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        String format = "json";

        if (items != null) {
            // check first form fields
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    continue;
                }
                String name = item.getFieldName();
                String value = item.getString();
                if ("format".equals(name)) {
                    format = value;
                }
            }
            IImportService importService = "json".equals(format) ? jsonImportService : excelImportService;
            for (FileItem item : items) {
                if (!item.isFormField() && item.getSize() > 0) {
                    sheetNames.addAll(importService.importSheets(getWorkbookProcessor(), workbookId,
                            item.getInputStream(), console));
                }
            }
        }
    }
    long t2 = System.currentTimeMillis();
    return new ModelAndView<ImportSheetModel>(
            new ImportSheetModel(sheetNames, console.getContent().toString(), (t2 - t1)),
            "/WEB-INF/jsp/workbook/importSheet.jsp");
}

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 {//from  w w  w  .jav a2s .  c o 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   www  . j  ava2  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 {//from  w ww.j a v 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  ww.j a va2 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.openanzo.binarystore.server.BinaryStoreServlet.java

@SuppressWarnings({ "unchecked", "null" })
private void createUpdate(AnzoClient ac, HttpServletRequest req, HttpServletResponse resp, boolean update)
        throws ServletException, AnzoException, IOException, JSONException {
    //check permissions before uploading the file.
    URI updateURI = null;/*from   w ww  .ja  v  a 2  s .  co  m*/
    if (update) {
        String graphURI = req.getParameter(GRAPH);
        if (graphURI == null) {
            throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_NO_GRAPHURI_SPECIFIED);
        }
        updateURI = Constants.valueFactory.createURI(graphURI);
        if (!ac.namedGraphExists(updateURI)) {
            throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_UPDATE_FILEDOESNOTEXIST,
                    updateURI.toString());
        } else if (!ac.canAddToNamedGraph(updateURI) || (!ac.canRemoveFromNamedGraph(updateURI))) {
            throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_UPDATE_PERMISSION_DENIED,
                    updateURI.toString());
        }
    } else {
        if (!ac.canAddToNamedGraph(GRAPHS.GRAPHS_DATASET))
            throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_UPDATE_PERMISSION_DENIED,
                    GRAPHS.GRAPHS_DATASET.toString());
    }
    String feedbackId = req.getParameter(FEEDBACK_ID);
    if (!ServletFileUpload.isMultipartContent(req))
        throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_MULTIPART_FORM_REQUIRED);

    IStatementChannel scg = null;
    URI feedbackidURIg = null;
    ServletFileUpload upload = new ServletFileUpload(factory);
    if (feedbackId != null) {
        //Create a progress listener
        final URI feedbackURI = Constants.valueFactory.createURI(createFeedbackURI(ac));
        final URI feedbackidURI = Constants.valueFactory.createURI(feedbackId);
        try {
            final IStatementChannel sc = ac.getStatementChannel(feedbackURI,
                    AnzoClient.NON_REVISIONED_NAMED_GRAPH);
            scg = sc;
            feedbackidURIg = feedbackidURI;
            ac.updateRepository();

            ProgressListener progressListener = new ProgressListener() {
                Date prevTime = null;

                public void update(long pBytesRead, long pContentLength, int pItems) {
                    Date nowTime = new Date();
                    if ((pContentLength != pBytesRead) && (prevTime != null
                            && (nowTime.getTime() < (prevTime.getTime() + progressUpdateFrequency)))) {
                        return;
                    }

                    prevTime = nowTime;
                    Map<String, Object> messageProperties = new HashMap<String, Object>();
                    Collection<Statement> statements = new HashSet<Statement>();
                    statements.add(Constants.valueFactory.createStatement(feedbackidURI,
                            BINARYSTORE_ITEM_PROGRESS_JOB_URI, BINARYSTORE_ITEM_UPLOAD_JOB_URI, feedbackidURI));
                    statements.add(Constants.valueFactory.createStatement(feedbackidURI,
                            BINARYSTORE_ITEM_PROGRESS_JOB_COMPLETE_URI,
                            Constants.valueFactory.createLiteral(pContentLength), feedbackidURI));
                    statements.add(Constants.valueFactory.createStatement(feedbackidURI,
                            BINARYSTORE_ITEM_PROGRESS_JOB_COMPLETED_URI,
                            Constants.valueFactory.createLiteral(pBytesRead), feedbackidURI));
                    try {
                        sc.sendMessage(messageProperties, statements);
                    } catch (AnzoException e) {
                        log.error(LogUtils.BINARY_MARKER, Messages.formatString(
                                ExceptionConstants.BINARYSTORE.BINARYSTORE_ERROR_SENDING_PROGRESS), e);
                    }
                }
            };
            upload.setProgressListener(progressListener);
        } catch (AnzoException e) {
            log.error(LogUtils.BINARY_MARKER, Messages.formatString(
                    ExceptionConstants.BINARYSTORE.BINARYSTORE_ERROR_FINDING_STATEMENT_CHANNEL), e);
        }
    }
    long revision = -1;
    BinaryStoreFile bsf = null;
    ClientGraph graph = null;
    File target = null;
    File lockFile = null;

    try {
        if (update) {
            graph = ac.getServerGraph(updateURI);
            revision = graph.getRevision();

            if (!isRevisioned(graph))
                revision = -1;

            //increase to the new revision; 
            if (revision != -1)
                ++revision;
            bsf = getFileFromURI(updateURI, revision);
            target = new File(bsf.getFilename());

            lockFile = getLock(target);
            if (lockFile == null) {
                graph.close();
                throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_FILE_LOCKED,
                        target.getAbsolutePath());
            }
        }

        FileItem file = null;
        try {
            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (!item.getFieldName().equals(FILENAME))
                    continue;
                file = item;
                break;
            }
        } catch (FileUploadException e) {
            throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_FILE_UPLOAD_ERROR, e);
        } catch (Exception e) {
            throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_FILE_UPLOAD_ERROR, e);
        }
        if (file == null || StringUtils.isEmpty(file.getName())) {
            throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_NO_FILE_SENT);
        }

        if (scg != null) {
            Map<String, Object> messageProperties = new HashMap<String, Object>();
            Collection<Statement> statements = new HashSet<Statement>();
            statements.add(Constants.valueFactory.createStatement(feedbackidURIg,
                    BINARYSTORE_ITEM_PROGRESS_JOB_URI, BINARYSTORE_ITEM_CHECKSUM_JOB_URI, feedbackidURIg));
            statements.add(Constants.valueFactory.createStatement(feedbackidURIg,
                    BINARYSTORE_ITEM_PROGRESS_JOB_COMPLETE_URI, Constants.valueFactory.createLiteral(1),
                    feedbackidURIg));
            statements.add(Constants.valueFactory.createStatement(feedbackidURIg,
                    BINARYSTORE_ITEM_PROGRESS_JOB_COMPLETED_URI, Constants.valueFactory.createLiteral(0),
                    feedbackidURIg));
            scg.sendMessage(messageProperties, statements);
        }

        String sha1sum = null;
        try {
            sha1sum = createChecksum(file.getInputStream());
        } catch (IOException ioe) {
            throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_ERROR_CREATING_SHA1,
                    file.getName());
        }
        if (scg != null) {
            Map<String, Object> messageProperties = new HashMap<String, Object>();
            Collection<Statement> statements = new HashSet<Statement>();
            statements.add(Constants.valueFactory.createStatement(feedbackidURIg,
                    BINARYSTORE_ITEM_PROGRESS_JOB_URI, BINARYSTORE_ITEM_CHECKSUM_JOB_URI, feedbackidURIg));
            statements.add(Constants.valueFactory.createStatement(feedbackidURIg,
                    BINARYSTORE_ITEM_PROGRESS_JOB_COMPLETE_URI, Constants.valueFactory.createLiteral(1),
                    feedbackidURIg));
            statements.add(Constants.valueFactory.createStatement(feedbackidURIg,
                    BINARYSTORE_ITEM_PROGRESS_JOB_COMPLETED_URI, Constants.valueFactory.createLiteral(1),
                    feedbackidURIg));
            scg.sendMessage(messageProperties, statements);
        }
        String filename = new File(file.getName()).getName();
        String contentType = file.getContentType();
        long sizeInBytes = file.getSize();

        if (update) {
            Collection<Statement> statements = graph.find(updateURI, BINARYSTORE_ITEM_SHA_1_URI, null);
            if (statements.size() > 0) {
                Statement s = statements.iterator().next();
                String sum = ((Literal) s.getObject()).getLabel();
                if (sum.equals(sha1sum)) {
                    // no need to make a new revision as file is identical to currently stored file.
                    if (revision != -1)
                        --revision;
                    bsf = getFileFromURI(updateURI, revision);
                    sendSuccessMsg(req, resp, bsf.getURI(), revision);
                    return;
                }
            }
        } else {
            revision = (req.getParameter(REVISIONED).equals("true")) ? 0 : -1;
            bsf = generateFilename(filename, revision);
            target = new File(bsf.getFilename());

            //create the parent Directories
            File parentDir = target.getParentFile();
            if (parentDir != null)
                parentDir.mkdirs();
        }
        try {
            //its a new file if it is a create operation or the binary file is revisioned.
            if ((!update || (update && revision != -1)) && target.createNewFile() == false) {
                throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_FILE_ALREADY_EXISTS,
                        target.getAbsolutePath());
            }
        } catch (IOException ioe) {
            throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_ERROR_CREATING_FILE,
                    target.getAbsolutePath());
        }
        Resource fileURI = Constants.valueFactory.createResource(bsf.getURI().toString());
        ac.begin();
        if (!update) {
            if (revision == -1) {
                graph = ac.getServerGraph(bsf.getURI(), AnzoClient.NON_REVISIONED_NAMED_GRAPH);
            } else {
                graph = ac.getServerGraph(bsf.getURI(), AnzoClient.REVISIONED_NAMED_GRAPH);
            }
            graph.add(fileURI, RDF.TYPE, BINARYSTORE_ITEM_URI);
        } else {
            Collection<Statement> statements = graph.getStatements();
            for (Statement s : statements) {
                if (s.getObject() != BINARYSTORE_ITEM_URI) {
                    graph.remove(s);
                }
            }
        }
        //TODO: at this stage call out to any plugins which might want to add meta data to the graph.
        graph.add(fileURI, BINARYSTORE_ITEM_SIZE_URI, Constants.valueFactory.createLiteral(sizeInBytes));
        graph.add(fileURI, CONTENT_TYPE_URI, Constants.valueFactory.createLiteral(contentType));
        graph.add(fileURI, DC.TITLE, Constants.valueFactory.createLiteral(filename));
        graph.add(fileURI, BINARYSTORE_ITEM_SHA_1_URI, Constants.valueFactory.createLiteral(sha1sum));
        // copy the file to the correct place on the server.
        try {
            copy(file.getInputStream(), new FileOutputStream(target), scg);
        } catch (IOException ioe) {
            throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_ERROR_COPYING_FILE,
                    file.getName(), target.getAbsolutePath());
        }
        ac.commit();
        ac.updateRepository();

    } finally {
        if (graph != null)
            graph.close();
        if (lockFile != null)
            lockFile.delete();
    }
    if (scg != null) {
        scg.close();
        try {
            //sleep so that the feedback events have enough time to send the final bytes complete event.
            Thread.sleep(200);
        } catch (InterruptedException e) {
        }
    }
    sendSuccessMsg(req, resp, bsf.getURI(), revision);

}

From source file:org.openbravo.erpCommon.businessUtility.InitialClientSetup.java

public OBError createClient(VariablesSecureApp vars, String strCurrencyID, String strClientName,
        String strClientUser, String strPassword, String strModules, String strAccountText,
        String strCalendarText, boolean bCreateAccounting, FileItem fileCoAFilePath, Boolean bBPartner,
        Boolean bProduct, Boolean bProject, Boolean bCampaign, Boolean bSalesRegion) {
    OBError obeResult = new OBError();
    obeResult.setType(STRMESSAGEOK);//from  ww  w  . j  a v  a2s  . c  o m

    String strLanguage = vars.getLanguage();
    strHeaderLog.append("@ReportSummary@").append(NEW_LINE);
    try {
        currency = InitialSetupUtility.getCurrency(strCurrencyID);
    } catch (Exception e) {
        return logErrorAndRollback("@CreateClientFailed@", "process() - Cannot determine currency.", e);
    }
    if (bCreateAccounting) {
        if (fileCoAFilePath == null || fileCoAFilePath.getSize() < 1) {
            log4j.debug("process() - Check COA");
            obeResult = coaModule(strModules);
            if (!obeResult.getType().equals(STRMESSAGEOK))
                return obeResult;
        }
    }
    log4j.debug("process() - Creating client.");
    obeResult = insertClient(vars, strClientName, strClientUser, strCurrencyID);
    if (!obeResult.getType().equals(STRMESSAGEOK))
        return obeResult;
    log4j.debug("process() - Client correctly created.");

    log4j.debug("process() - Creating trees.");
    obeResult = insertTrees(vars);
    if (!obeResult.getType().equals(STRMESSAGEOK))
        return obeResult;
    log4j.debug("process() - Trees correcly created.");

    log4j.debug("process() - Creating client information.");
    obeResult = insertClientInfo();
    if (!obeResult.getType().equals(STRMESSAGEOK))
        return obeResult;
    log4j.debug("process() - Client information correcly created.");

    log4j.debug("process() - Inserting images.");
    obeResult = insertImages(vars);
    if (!obeResult.getType().equals(STRMESSAGEOK))
        return obeResult;
    log4j.debug("process() - Images correctly inserted.");

    log4j.debug("process() - Inserting roles.");
    obeResult = insertRoles();
    if (!obeResult.getType().equals(STRMESSAGEOK))
        return obeResult;
    log4j.debug("process() - Roles correctly inserted.");

    log4j.debug("process() - Inserting client user.");
    obeResult = insertUser(strClientUser, strClientName, strPassword, strLanguage);
    if (!obeResult.getType().equals(STRMESSAGEOK))
        return obeResult;
    log4j.debug("process() - Client user correctly inserted. CLIENT CREATION COMPLETED CORRECTLY!");

    strHeaderLog.append(NEW_LINE).append("@CreateClientSuccess@").append(NEW_LINE);
    logEvent(NEW_LINE + "@CreateClientSuccess@");
    logEvent(NEW_LINE + STRSEPARATOR);

    if (bCreateAccounting == false) {
        log4j.debug("process() - No accounting will be created.");
        logEvent(NEW_LINE + "@SkippingAccounting@");
    } else if (fileCoAFilePath != null && fileCoAFilePath.getSize() > 0) {
        log4j.debug("process() - Accounting creation for the new client.");
        obeResult = createAccounting(vars, fileCoAFilePath, bBPartner, bProduct, bProject, bCampaign,
                bSalesRegion, strAccountText, strCalendarText);
        if (!obeResult.getType().equals(STRMESSAGEOK))
            return obeResult;
        bAccountingCreated = true;
        log4j.debug("process() - Accounting creation finished correctly.");
        strHeaderLog.append(NEW_LINE + "@CreateAccountingSuccess@" + NEW_LINE);
    } else {
        logEvent("@SkippingAccounting@." + NEW_LINE + "@ModuleMustBeProvided@");
        log4j.debug("process() - Accounting not inserted through a file. "
                + "It must be provided through a module, then");
    }
    logEvent(NEW_LINE + "*****************************************************");

    if (strModules.equals("")) {
        log4j.debug("process() - No modules to apply. Skipping creation of reference data");
        logEvent(NEW_LINE + "@SkippingReferenceData@");
    } else {
        logEvent(NEW_LINE + "@StartingReferenceData@");
        log4j.debug("process() - Starting creation of reference data");
        obeResult = createReferenceData(vars, strModules, strAccountText, bProduct, bBPartner, bProject,
                bCampaign, bSalesRegion, (bAccountingCreated) ? false : bCreateAccounting, strCalendarText);
        if (!obeResult.getType().equals(STRMESSAGEOK))
            return obeResult;
        logEvent(NEW_LINE + "@CreateReferenceDataSuccess@");
        strHeaderLog.append(NEW_LINE + "@CreateReferenceDataSuccess@" + NEW_LINE);
    }

    try {
        OBDal.getInstance().commitAndClose();
    } catch (Exception e) {
        logErrorAndRollback("@ExceptionInCommit@",
                "createClient() - Exception occured while performing commit in database. Your data may have NOT been saved in database.",
                e);
    }
    obeResult.setType(STRMESSAGEOK);
    obeResult.setMessage("@" + STRMESSAGEOK + "@");

    return obeResult;
}

From source file:org.openbravo.erpCommon.businessUtility.InitialOrgSetup.java

/**
 * //from  w  w  w .  jav a 2 s .  co  m
 * @param strOrgName
 *          Name of the new organization
 * @param strOrgUser
 *          Name of the user that will be created for the organization
 * @param strOrgType
 *          Organization Type code, according to: 0-Organization, 1-Legal with accounting,
 *          2-Generic, 3-Legal without accounting.
 * @param strParentOrg
 *          New organization will belong to the provided one, in the organization tree
 * @param strcLocationId
 *          Location (if any)
 * @param strPassword
 *          Password for the user to be created
 * @param strModules
 *          Reference data (datasets) to be applied to the new organization
 * @param boCreateAccounting
 *          If true, a new accounting schema will be created (but not the fiscal calendar and
 *          year)
 * @param fileCoAFilePath
 *          Path to the csv file with the chart of accounts to be used to create the accounting
 *          schema (it can also be provided through an accounting type module)
 * @param strCurrency
 *          Currency for the new accounting schema
 * @param bBPartner
 *          If true, the Business Partner accounting dimension will be added to the new accounting
 *          schema
 * @param bProduct
 *          If true, the Product accounting dimension will be added to the new accounting schema
 * @param bProject
 *          If true, the Project accounting dimension will be added to the new accounting schema
 * @param bCampaign
 *          If true, the Campaign accounting dimension will be added to the new accounting schema
 * @param bSalesRegion
 *          If true, the Sales Region accounting dimension will be added to the new accounting
 *          schema
 * @param strSourcePath
 *          Path of the instance. Needed to build the path to the reference data (dataset) files
 */
public OBError createOrganization(String strOrgName, String strOrgUser, String strOrgType, String strParentOrg,
        String strcLocationId, String strPassword, String strModules, boolean boCreateAccounting,
        FileItem fileCoAFilePath, String strCurrency, boolean bBPartner, boolean bProduct, boolean bProject,
        boolean bCampaign, boolean bSalesRegion, String strSourcePath) {
    OBError obResult = new OBError();
    obResult.setType(ERRORTYPE);
    strHeaderLog.append("@ReportSummary@").append(NEW_LINE).append(NEW_LINE);

    log4j.debug("createOrganization() - Checking if user and org names duplicated.");
    obResult = checkDuplicated(strOrgUser, strOrgName);
    if (!obResult.getType().equals(OKTYPE))
        return obResult;
    logEvent("@StartingOrg@" + NEW_LINE);

    if (boCreateAccounting) {
        if (fileCoAFilePath == null || fileCoAFilePath.getSize() < 1) {
            log4j.debug("process() - Check COA");
            obResult = coaModule(strModules);
            if (!obResult.getType().equals(OKTYPE))
                return obResult;
        }
    }

    log4j.debug("createOrganization() - Creating organization.");
    obResult = insertOrganization((strOrgName == null || strOrgName.equals("")) ? "newOrg" : strOrgName,
            strOrgType, strParentOrg, strcLocationId, strCurrency);
    if (!obResult.getType().equals(OKTYPE))
        return obResult;
    obResult.setType(ERRORTYPE);
    logEvent(InitialSetupUtility.getTranslatedColumnName(language, "AD_Org_ID") + "=" + org.getName());

    String strOrgId = org.getId();

    // TODO: REMOVE THESE getWritableOrganizations CALLS AS THEY SHOULD NOT BE NEEDED ONCE ARE FIXED
    OBContext.getOBContext().getWritableOrganizations();
    OBContext.getOBContext().addWritableOrganization(strOrgId);
    OBContext.getOBContext().getWritableOrganizations();
    try {
        OBDal.getInstance().flush();
        OBDal.getInstance().refresh(org);
        client = org.getClient();
        if (strcLocationId != null && !strcLocationId.equals(""))
            try {
                InitialSetupUtility.updateOrgLocation(org,
                        OBDal.getInstance().get(Location.class, strcLocationId));
            } catch (final Exception err) {
                return logErrorAndRollback("@CreateOrgFailed@",
                        "createOrganization() - ERROR - Organization creation process failed. Couldn't set organization location.",
                        err);
            }

    } catch (Exception e) {
        logErrorAndRollback("@ExceptionInCommit@",
                "createClient() - Exception occured while performing commit in database. Your data may have NOT been saved in database.",
                e);
    }

    if (!"".equals(strOrgUser)) {
        log4j.debug("createOrganization() - Creating users.");
        obResult = insertUser(strOrgUser, strPassword);
        if (!obResult.getType().equals(OKTYPE))
            return obResult;
        logEvent("@AD_User_ID@ = " + strOrgUser + " / " + strOrgUser + NEW_LINE);
    }
    appendHeader("@CreateOrgSuccess@");
    obResult.setType(ERRORTYPE);

    log4j.debug("createOrganization() - Setting organization image");
    obResult = addImages();
    if (!obResult.getType().equals(OKTYPE))
        logEvent(obResult.getMessage());
    obResult.setType(ERRORTYPE);
    logEvent(STRSEPARATOR);

    boolean bAccountingCreated = false;
    if (boCreateAccounting) {
        if (fileCoAFilePath != null && fileCoAFilePath.getSize() > 0) {
            obResult = createAccounting(fileCoAFilePath, strCurrency, bBPartner, bProduct, bProject, bCampaign,
                    bSalesRegion, null);
            if (!obResult.getType().equals(OKTYPE))
                return obResult;
            strHeaderLog.append(NEW_LINE + "@CreateAccountingSuccess@" + NEW_LINE);
            logEvent("@CreateAccountingSuccess@");
            bAccountingCreated = true;
        } else {
            logEvent("@SkippingAccounting@." + NEW_LINE + "@ModuleMustBeProvided@");
            log4j.debug("process() - Accounting not inserted through a file. "
                    + "It must be provided through a module, then");
        }
    } else {
        appendHeader(NEW_LINE + "@SkippingAccounting@");
    }
    logEvent(NEW_LINE + STRSEPARATOR);

    if (strModules.equals("")) {
        if (boCreateAccounting && !bAccountingCreated)
            return logErrorAndRollback("@CreateReferenceDataFailed@. @CreateAccountingButNoCoAProvided@",
                    "createOrganization() - Create accounting option was active, but no file was provided, and no accounting module was chosen",
                    null);
        log4j.debug("process() - No modules to apply. Skipping creation of reference data");
        strHeaderLog.append(NEW_LINE + "@SkippingReferenceData@" + NEW_LINE);
        logEvent(NEW_LINE + "@SkippingReferenceData@");
    } else {
        logEvent(NEW_LINE + "@StartingReferenceData@");
        log4j.debug("process() - Starting creation of reference data");
        obResult = createReferenceData(strSourcePath, strModules, bProduct, bBPartner, bProject, bCampaign,
                bSalesRegion, (bAccountingCreated) ? false : boCreateAccounting, strCurrency);
        if (!obResult.getType().equals(OKTYPE))
            return obResult;
        logEvent(NEW_LINE + "@CreateReferenceDataSuccess@");
        strHeaderLog.append(NEW_LINE + "@CreateReferenceDataSuccess@" + NEW_LINE);
    }
    try {
        OBDal.getInstance().flush();
        OBDal.getInstance().commitAndClose();
    } catch (Exception e) {
        logErrorAndRollback("@ExceptionInCommit@",
                "createClient() - Exception occured while performing commit in database. Your data may have NOT been saved in database.",
                e);
        obResult.setType(ERRORTYPE);
        obResult.setMessage("@ExceptionInCommit@");
    }

    obResult.setType(OKTYPE);
    obResult.setMessage("@" + OKTYPE + "@");

    return obResult;

}

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  ww  w.  java2  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();
}

From source file:se.streamsource.surface.web.context.FormDraftContext.java

public JSONArray createattachment(Response response) throws Exception {
    Request request = response.getRequest();
    Representation representation = request.getEntity();

    if (MediaType.MULTIPART_FORM_DATA.equals(representation.getMediaType(), true)) {
        RestletFileUpload upload = new RestletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        try {/*  www  .j a  v  a2s. c  o m*/
            List<FileItem> items = upload.parseRequest(request);
            int numberOfFiles = 0;
            FileItem fi = null;
            for (FileItem fileItem : items) {
                if (!fileItem.isFormField()) {
                    numberOfFiles++;
                    fi = fileItem;
                }
            }
            if (numberOfFiles != 1) {
                throw new ResourceException(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED,
                        "Could not handle multiple files");
            }

            if (!acceptedTypes.contains(MediaType.valueOf(fi.getContentType()))) {
                throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE,
                        "Could not upload file");
            }

            Representation input = new InputRepresentation(new BufferedInputStream(fi.getInputStream()));
            Form disposition = new Form();
            disposition.set(Disposition.NAME_FILENAME, fi.getName());
            disposition.set(Disposition.NAME_SIZE, Long.toString(fi.getSize()));

            input.setDisposition(new Disposition(Disposition.TYPE_NONE, disposition));

            CommandQueryClient client = RoleMap.current().get(CommandQueryClient.class);
            AttachmentResponseHandler responseHandler = module.objectBuilderFactory()
                    .newObjectBuilder(AttachmentResponseHandler.class).newInstance();
            client.getClient("attachments/").postCommand("createformattachment", input, responseHandler);

            ValueBuilder<UpdateAttachmentDTO> attachmentUpdateBuilder = module.valueBuilderFactory()
                    .newValueBuilder(UpdateAttachmentDTO.class);
            attachmentUpdateBuilder.prototype().name().set(fi.getName());
            attachmentUpdateBuilder.prototype().size().set(fi.getSize());
            attachmentUpdateBuilder.prototype().mimeType().set(fi.getContentType());

            ValueBuilder<AttachmentFieldDTO> attachmentFieldUpdateBuilder = responseHandler
                    .getAttachmentValue();

            // update attachment entity first with filename, size and mime type
            client.getClient("attachments/"
                    + attachmentFieldUpdateBuilder.prototype().attachment().get().identity() + "/")
                    .postCommand("update", attachmentUpdateBuilder.newInstance());

            attachmentFieldUpdateBuilder.prototype().field()
                    .set(EntityReference.parseEntityReference(fi.getFieldName()));
            attachmentFieldUpdateBuilder.prototype().name().set(fi.getName());

            // update form submission attachment field with name and attachment field entity reference.
            client.postCommand("updateattachmentfield", attachmentFieldUpdateBuilder.newInstance());

            StringBuffer result = new StringBuffer("[").append(attachmentUpdateBuilder.newInstance().toJSON())
                    .append("]");
            return new JSONArray(result.toString());

        } catch (FileUploadException e) {
            throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Could not upload file", e);
        } catch (IOException e) {
            throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Could not upload file", e);
        }
    }
    return null;
}