List of usage examples for org.apache.commons.fileupload FileItem getInputStream
InputStream getInputStream() throws IOException;
From source file:org.ff4j.console.controller.FeaturesController.java
@RequestMapping(method = RequestMethod.POST) public ModelAndView executeThenShowPage(HttpServletRequest req, HttpServletResponse res) throws Exception { log.info("Page <FEATURES> on action <POST>"); // Environment de travail EnvironmenBean envBean = (EnvironmenBean) req.getSession().getAttribute(ATTR_ENVBEAN); // Access features through HTTP store (all parsing done) FeatureStore storeHTTP = new FeatureStoreHttp(envBean.getEnvUrl() + "/" + FF4jWebConstants.RESOURCE_FF4J); // Data in the target screen FeaturesBean featBean = new FeaturesBean(); try {/* www . j a va 2s . co m*/ // Import Features if (ServletFileUpload.isMultipartContent(req)) { List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req); for (FileItem item : items) { if (item.isFormField()) { if (OPERATION.equalsIgnoreCase(item.getFieldName())) { log.info("Processing action : " + item.getString()); } } else if (FLIPFILE.equalsIgnoreCase(item.getFieldName())) { String filename = FilenameUtils.getName(item.getName()); if (filename.toLowerCase().endsWith("xml")) { opImportFile(storeHTTP, item.getInputStream()); featBean.setMessage("The file <b>" + filename + "</b> has been successfully imported"); } else { featBean.setMessage("Invalid FILE, must be XML files"); featBean.setMessageType(MSG_ERROR); } } } } else { // Edit Operations String operation = req.getParameter(OPERATION); if (operation != null && !operation.isEmpty()) { if (OP_EDIT_FEATURE.equalsIgnoreCase(operation)) { opUpdateFeatureDescription(storeHTTP, req); featBean.setMessage(buildMessage(req.getParameter(FEATID), "UPDATED")); } else if (OP_CREATE_FEATURE.equalsIgnoreCase(operation)) { opCreateFeature(storeHTTP, req); featBean.setMessage(buildMessage(req.getParameter(FEATID), "ADDED")); } else if (OP_TOGGLE_GROUP.equalsIgnoreCase(operation)) { String groupName = req.getParameter(GROUPNAME); if (groupName != null && !groupName.isEmpty()) { String operationGroup = req.getParameter(SUBOPERATION); if (OP_ENABLE.equalsIgnoreCase(operationGroup)) { storeHTTP.enableGroup(groupName); featBean.setMessage(buildMessageGroup(groupName, "ENABLED")); log.info("Group '" + groupName + "' has been ENABLED."); } else if (OP_DISABLE.equalsIgnoreCase(operationGroup)) { storeHTTP.disableGroup(groupName); featBean.setMessage(buildMessageGroup(groupName, "DISABLED")); log.info("Group '" + groupName + "' has been DISABLED."); } } } else { log.error("Invalid POST OPERATION" + operation); featBean.setMessageType(MSG_ERROR); featBean.setMessage("Invalid REQUEST"); } } } } catch (Exception e) { featBean.setMessageType(MSG_ERROR); featBean.setMessage(e.getMessage()); e.printStackTrace(); } // Updating bean featBean.setListOfFeatures(new ArrayList<Feature>(storeHTTP.readAll().values())); featBean.setHtmlPermissions(populatePermissionList(envBean)); featBean.setGroupList(storeHTTP.readAllGroups()); // Create view ModelAndView mav = new ModelAndView(VIEW_FEATURES); mav.addObject(ATTR_ENVBEAN, envBean); mav.addObject(ATTR_FEATUREBEAN, featBean); return mav; }
From source file:org.ff4j.web.AdministrationConsoleServlet.java
/** {@inheritDoc} */ @Override/* ww w .j a v a 2 s.c o m*/ protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String message = null; String messagetype = "error"; try { List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req); for (FileItem item : items) { if (item.isFormField()) { if (OPERATION.equalsIgnoreCase(item.getFieldName())) { // String operation = item.getString(); // Proceed here action accessing through POST } } else if (FLIPFILE.equalsIgnoreCase(item.getFieldName())) { String filename = FilenameUtils.getName(item.getName()); if (filename.toLowerCase().endsWith("xml")) { opImportFile(item.getInputStream()); } else { messagetype = "error"; message = "Invalid FILE, must be CSV, XML or PROPERTIES files"; } } } } catch (Exception e) { message = e.getMessage(); } renderPage(req, res, message, messagetype); }
From source file:org.ff4j.web.controller.HomeController.java
/** {@inheritDoc} */ public void post(HttpServletRequest req, HttpServletResponse res, WebContext ctx) throws Exception { String msg = null;/* www .ja v a2s. com*/ String msgType = "success"; String operation = req.getParameter(WebConstants.OPERATION); // Upload XML File if (ServletFileUpload.isMultipartContent(req)) { List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req); for (FileItem item : items) { if (item.isFormField()) { if (OPERATION.equalsIgnoreCase(item.getFieldName())) { LOGGER.info("Processing action : " + item.getString()); } } else if (FLIPFILE.equalsIgnoreCase(item.getFieldName())) { String filename = FilenameUtils.getName(item.getName()); if (filename.toLowerCase().endsWith("xml")) { try { importFile(getFf4j(), item.getInputStream()); msg = "The file <b>" + filename + "</b> has been successfully imported"; } catch (RuntimeException re) { msgType = ERROR; msg = "Cannot Import XML:" + re.getMessage(); break; } } else { msgType = ERROR; msg = "Invalid FILE, must be CSV, XML or PROPERTIES files"; } } } ctx.setVariable("msgType", msgType); ctx.setVariable("msgInfo", msg); get(req, res, ctx); } else if (WebConstants.OP_CREATE_SCHEMA.equalsIgnoreCase(operation)) { try { getFf4j().createSchema(); msg = "Schema has been created in DB (if required)."; ctx.setVariable("msgType", msgType); ctx.setVariable("msgInfo", msg); get(req, res, ctx); } catch (RuntimeException re) { ctx.setVariable("msgType", ERROR); ctx.setVariable("msgInfo", "Cannot create Schema:" + re.getMessage()); ctx.setVariable(KEY_TITLE, "Home"); ctx.setVariable("today", Calendar.getInstance()); ctx.setVariable("homebean", new HomeBean()); } } else if (WebConstants.OP_CLEAR_CACHE.equalsIgnoreCase(operation)) { FF4jCacheProxy cacheProxy = getFf4j().getCacheProxy(); if (cacheProxy != null) { cacheProxy.getCacheManager().clearFeatures(); cacheProxy.getCacheManager().clearProperties(); msg = "Cache Cleared!"; } else { msg = "Cache not present: it cannot be cleared!"; } ctx.setVariable("msgType", msgType); ctx.setVariable("msgInfo", msg); get(req, res, ctx); } }
From source file:org.ff4j.web.embedded.ConsoleServlet.java
/** {@inheritDoc} */ @Override// w ww.ja v a2 s. c o m public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String message = null; String messagetype = "info"; try { if (ServletFileUpload.isMultipartContent(req)) { List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req); for (FileItem item : items) { if (item.isFormField()) { if (OPERATION.equalsIgnoreCase(item.getFieldName())) { LOGGER.info("Processing action : " + item.getString()); } } else if (FLIPFILE.equalsIgnoreCase(item.getFieldName())) { String filename = FilenameUtils.getName(item.getName()); if (filename.toLowerCase().endsWith("xml")) { importFile(getFf4j(), item.getInputStream()); message = "The file <b>" + filename + "</b> has been successfully imported"; } else { messagetype = ERROR; message = "Invalid FILE, must be CSV, XML or PROPERTIES files"; } } } } else { String operation = req.getParameter(OPERATION); String uid = req.getParameter(FEATID); LOGGER.info("POST - op=" + operation + " feat=" + uid); if (operation != null && !operation.isEmpty()) { if (OP_EDIT_FEATURE.equalsIgnoreCase(operation)) { updateFeatureDescription(getFf4j(), req); message = msg(uid, "UPDATED"); } else if (OP_EDIT_PROPERTY.equalsIgnoreCase(operation)) { updateProperty(getFf4j(), req); message = renderMsgProperty(uid, "UPDATED"); } else if (OP_CREATE_PROPERTY.equalsIgnoreCase(operation)) { createProperty(getFf4j(), req); message = renderMsgProperty(req.getParameter(NAME), "ADDED"); } else if (OP_CREATE_FEATURE.equalsIgnoreCase(operation)) { createFeature(getFf4j(), req); message = msg(uid, "ADDED"); } else if (OP_TOGGLE_GROUP.equalsIgnoreCase(operation)) { String groupName = req.getParameter(GROUPNAME); if (groupName != null && !groupName.isEmpty()) { String operationGroup = req.getParameter(SUBOPERATION); if (OP_ENABLE.equalsIgnoreCase(operationGroup)) { getFf4j().getFeatureStore().enableGroup(groupName); message = renderMsgGroup(groupName, "ENABLED"); LOGGER.info("Group '" + groupName + "' has been ENABLED."); } else if (OP_DISABLE.equalsIgnoreCase(operationGroup)) { getFf4j().getFeatureStore().disableGroup(groupName); message = renderMsgGroup(groupName, "DISABLED"); LOGGER.info("Group '" + groupName + "' has been DISABLED."); } } } else { LOGGER.error("Invalid POST OPERATION" + operation); messagetype = ERROR; message = "Invalid REQUEST"; } } else { LOGGER.error("No ID provided" + operation); messagetype = ERROR; message = "Invalid UID"; } } } catch (Exception e) { messagetype = ERROR; message = e.getMessage(); LOGGER.error("An error occured ", e); } // Update FF4J in Session (distributed) getServletContext().setAttribute(FF4J_SESSIONATTRIBUTE_NAME, ff4j); renderPage(ff4j, req, res, message, messagetype); }
From source file:org.fireflow.console.servlet.repository.UploadDefinitionsServlet.java
/** * ??1<br>/*ww w .jav a 2 s. co m*/ * ??Session??2??????? * * @param req * @param resp * @throws ServletException * @throws IOException */ protected void uploadSingleDefStep1(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1?request??session? FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> fileItems = null; try { fileItems = upload.parseRequest(req); } catch (FileUploadException e) { e.printStackTrace(); } InputStream inStreamTmp = null;// ? String fileName = null; Iterator<FileItem> i = fileItems.iterator(); while (i.hasNext()) { FileItem item = (FileItem) i.next(); if (!item.isFormField()) { inStreamTmp = item.getInputStream(); fileName = item.getName(); } else { // // System.out.println("==="+item.getFieldName()); } } // 2??? FPDLDeserializer des = new FPDLDeserializer(); WorkflowProcess process = null; try { process = des.deserialize(inStreamTmp); } catch (DeserializerException e) { req.setAttribute(Constants.ERROR_MESSAGE, "?????" + fileName); req.setAttribute(Constants.ERROR_STACK, Utils.exceptionStackToString(e)); RequestDispatcher dispatcher = req.getRequestDispatcher("/common/error_message.jsp"); dispatcher.forward(req, resp); return; } catch (InvalidModelException e) { req.setAttribute(Constants.ERROR_MESSAGE, "?????" + fileName); req.setAttribute(Constants.ERROR_STACK, Utils.exceptionStackToString(e)); RequestDispatcher dispatcher = req.getRequestDispatcher("/common/error_message"); dispatcher.forward(req, resp); return; } if (process == null) { req.setAttribute(Constants.ERROR_MESSAGE, "?????" + fileName); req.setAttribute(Constants.ERROR_STACK, "???WorkflowProcessnull"); RequestDispatcher dispatcher = req.getRequestDispatcher("/common/error_message"); dispatcher.forward(req, resp); return; } req.getSession().setAttribute(PROCESS_DEFINITION, process); // 3??ID? final org.fireflow.engine.modules.ousystem.User currentUser = WorkflowUtil .getCurrentWorkflowUser(req.getSession()); WorkflowSession fireSession = WorkflowSessionFactory.createWorkflowSession(fireContext, currentUser); WorkflowQuery<ProcessDescriptor> query = fireSession.createWorkflowQuery(ProcessDescriptor.class); List<ProcessDescriptor> existingProcessList = query .add(Restrictions.eq(ProcessDescriptorProperty.PROCESS_ID, process.getId())) .add(Restrictions.eq(ProcessDescriptorProperty.PROCESS_TYPE, FpdlConstants.PROCESS_TYPE_FPDL20)) .addOrder(Order.asc(ProcessDescriptorProperty.VERSION)).list(); req.setAttribute("EXISTING_PROCESS_LIST", existingProcessList); req.setAttribute(PROCESS_DEFINITION, process); // 5?step2? RequestDispatcher dispatcher = req .getRequestDispatcher("/fireflow_console/repository/upload_definition_step2.jsp"); dispatcher.forward(req, resp); }
From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java
private void mapRequestToObj(HashMap<String, Object> data, Class expectedClass, Object obj) throws Exception { if (obj == null) { throw new ApplicationException("mapRequestToObj called on NULL obj", "ERR9001"); }//from www .j a v a 2 s . co m try { Method versionMethod = expectedClass.getMethod("getVersion", (Class<?>[]) null); Long objVersion = (Long) versionMethod.invoke(obj, (Object[]) null); String clientVersion = (String) data.get("version"); if (objVersion != null && clientVersion != null) { try { long clientVersionLong = Long.parseLong(clientVersion); if (!objVersion.equals(clientVersionLong)) { throw makeApplicationException("Can't save object", "ERR9016", (Serializable[]) null); } } catch (NumberFormatException nfe) { // Version from client isn't number - ignore } } } catch (NoSuchMethodException nme) { // No version control } Method[] methods = expectedClass.getMethods(); for (Method m : methods) { Class<?>[] paramTypes = m.getParameterTypes(); Class persistentClass = null; if (paramTypes.length == 1) { if (paramTypes[0].getAnnotation(Entity.class) != null) { persistentClass = paramTypes[0]; } else if (paramTypes[0].getAnnotation(Embeddable.class) != null) { persistentClass = paramTypes[0]; } } ServiceDescription srvParam = paramTypes.length == 1 ? findServiceByClassName(paramTypes[0].getName()) : null; if ((m.getName().startsWith(SET_PREFIX) && paramTypes.length == 1 && (paramTypes[0].isAssignableFrom(String.class) || paramTypes[0].equals(Integer.class) || paramTypes[0].equals(Integer.TYPE) || paramTypes[0].equals(Long.class) || paramTypes[0].equals(Long.TYPE) || paramTypes[0].equals(Float.class) || paramTypes[0].equals(Float.TYPE) || paramTypes[0].equals(Boolean.class) || paramTypes[0].equals(Boolean.TYPE) || paramTypes[0].equals(Double.class) || paramTypes[0].equals(Double.TYPE) || paramTypes[0].equals(Date.class) || Enum.class.isAssignableFrom(paramTypes[0]) || (srvParam != null && srvParam.getFindById() != null) || persistentClass != null)) || (m.getName().startsWith(GET_PREFIX) && paramTypes.length == 0 && (Set.class.isAssignableFrom(m.getReturnType()) || List.class.isAssignableFrom(m.getReturnType())))) { String fldName; if (m.getName().startsWith(GET_TRANSLATE)) { fldName = m.getName().substring(GET_TRANSLATE_LENGTH, GET_TRANSLATE_LENGTH + 1).toLowerCase() + m.getName().substring(GET_TRANSLATE_LENGTH + 1); } else { fldName = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4); } Object value = data.get(fldName); if (value == null) { fldName = m.getName().substring(3); value = data.get(fldName); } if (value != null) { Object typedVal; String val = null; if (value instanceof String) { val = (String) value; } log.log(Level.FINER, " value = " + value); if (m.getName().startsWith(GET_PREFIX) && paramTypes.length == 0 && (Set.class.isAssignableFrom(m.getReturnType()) || List.class.isAssignableFrom(m.getReturnType()))) { log.log(Level.FINER, "GET"); String attrName = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4); Type[] actualTypeArguments = null; Class iterClass = expectedClass; while (iterClass != null) { try { Field field = iterClass.getDeclaredField(attrName); ParameterizedType genericType = (ParameterizedType) field.getGenericType(); actualTypeArguments = genericType.getActualTypeArguments(); break; } catch (NoSuchFieldException nsfe) { // do nothing iterate again } iterClass = iterClass.getSuperclass(); iterClass = iterClass.equals(Object.class) ? null : iterClass; } if (actualTypeArguments != null && actualTypeArguments.length == 1 && actualTypeArguments[0] instanceof Class) { Class assocClass = (Class) actualTypeArguments[0]; ServiceDescription assocService = findServiceByClassName(assocClass.getName()); Collection dbValueSet = (Collection) m.invoke(obj, (Object[]) null); if (value == null || !(value instanceof HashMap)) { log.log(Level.FINE, "No data for db property {0}", attrName); } else if (assocService != null) { HashMap<String, Object> guiValueMap = (HashMap<String, Object>) value; ArrayList<Object> removeIt = new ArrayList<Object>(); Iterator dbIterator = dbValueSet.iterator(); while (dbIterator.hasNext()) { Object dbVal = dbIterator.next(); String dbValId = getIdFromObj(dbVal); if (dbValId != null) { boolean wasMatchingGuiVal = false; ArrayList<String> removeKeys = new ArrayList<String>(); for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { Object guiValue = ((HashMap<String, Object>) object).get("id"); if (guiValue.equals(dbValId)) { removeKeys.add(key); wasMatchingGuiVal = true; mapRequestToObj((HashMap<String, Object>) guiValue, assocClass, dbVal); break; } } else if (object instanceof String) { // Association if (dbValId.equals(object)) { removeKeys.add(key); wasMatchingGuiVal = true; } } else { log.log(Level.WARNING, "Wrong object type from GUI under key {0}", key); } } // Remove processed elements // Direct remove is firing concurrent modification exception for (String removeKey : removeKeys) { guiValueMap.remove(removeKey); } if (!wasMatchingGuiVal) { // Is not in list comming from GUI - delete removeIt.add(dbVal); } } else { log.log(Level.WARNING, "No ID in object {0}", dbVal); } } dbValueSet.removeAll(removeIt); // Rest are new records for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { Object subObj = makeNewInstance(assocClass, (HashMap<String, Object>) object); mapRequestToObj((HashMap<String, Object>) object, assocClass, subObj); dbValueSet.add(subObj); } else if (object instanceof String) { // Association try { Long id = new Long((String) object); Object assocObj = assocService.getFindById().invoke( assocService.getInstance(), ServiceContextStore.get(), id); if (assocObj != null) { dbValueSet.add(assocObj); } else { log.log(Level.WARNING, "Object with ID {0} not availabla via service {1}", new Object[] { id, assocService.getName() }); } } catch (Exception ex) { log.log(Level.WARNING, "No ID parsable from value {0} under key {1}", new Object[] { object, key }); } } else { log.log(Level.WARNING, "Wrong sub type {0}", attrName); } } } else if (assocClass != null) { HashMap<String, Object> guiValueMap = (HashMap<String, Object>) value; ArrayList<Object> removeIt = new ArrayList<Object>(); Iterator dbIterator = dbValueSet.iterator(); while (dbIterator.hasNext()) { Object dbVal = dbIterator.next(); String dbValId = getIdFromObj(dbVal); if (dbValId != null) { Object matchingGuiVal = null; for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { HashMap<String, Object> guiVal = (HashMap<String, Object>) object; if (dbValId.equals(guiVal.get("id"))) { guiValueMap.remove(key); matchingGuiVal = guiVal; break; } } else { log.log(Level.WARNING, "Wrong object type from GUI under key {0}", key); } } if (matchingGuiVal != null) { // Coming from GUI - update mapRequestToObj((HashMap<String, Object>) matchingGuiVal, assocClass, dbVal); } else { // Not in GUI - delete removeIt.add(dbVal); } } else { log.log(Level.WARNING, "No ID in object {0}", dbVal); } } dbValueSet.removeAll(removeIt); // Rest are new records for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { Object subObj = makeNewInstance(assocClass, (HashMap<String, Object>) object); mapRequestToObj((HashMap<String, Object>) object, assocClass, subObj); dbValueSet.add(subObj); } else { log.log(Level.WARNING, "Wrong sub type {0}", attrName); } } } } else { log.log(Level.WARNING, "No DB mapping or not of collection type: {0}", attrName); } typedVal = null; } else if (paramTypes[0].isAssignableFrom(String.class)) { typedVal = val; } else if (paramTypes[0].equals(Integer.class) || paramTypes[0].equals(Integer.TYPE)) { typedVal = Integer.parseInt(val); } else if (paramTypes[0].equals(Long.class) || paramTypes[0].equals(Long.TYPE)) { typedVal = Long.parseLong(val); } else if (paramTypes[0].equals(Double.class) || paramTypes[0].equals(Double.TYPE)) { typedVal = Double.parseDouble(val); } else if (paramTypes[0].equals(Float.class) || paramTypes[0].equals(Float.TYPE)) { typedVal = Float.parseFloat(val); } else if (paramTypes[0].equals(Boolean.class) || paramTypes[0].equals(Boolean.TYPE)) { typedVal = "true".equalsIgnoreCase(val) || "t".equalsIgnoreCase(val) || "y".equalsIgnoreCase(val); } else if (paramTypes[0].isAssignableFrom(Date.class)) { typedVal = dateFormat.parse(val); } else if (Enum.class.isAssignableFrom(paramTypes[0])) { try { Method fromValueMethod = paramTypes[0].getMethod("fromValue", String.class); typedVal = fromValueMethod.invoke(null, val); } catch (Exception ex) { typedVal = null; } try { if (typedVal == null) { Method valueOfMethod = paramTypes[0].getMethod("valueOf", String.class); typedVal = valueOfMethod.invoke(null, val); } } catch (Exception ex) { typedVal = null; } } else if (persistentClass != null && persistentClass.equals(FileUpload.class)) { FileItem fileItem = uploadServlet.getFileItem(sessionId.get(), fldName, val); if (fileItem != null) { typedVal = fileUploadService.uploadFile(ServiceContextStore.get(), fileItem.getName(), fileItem.getContentType(), fileItem.getInputStream()); } else { typedVal = null; } } else if (srvParam != null && srvParam.getFindById() != null) { if (value instanceof HashMap) { HashMap<String, Object> embeddedObj = (HashMap<String, Object>) value; typedVal = srvParam.getFindById().invoke(srvParam.getInstance(), ServiceContextStore.get(), new Long((String) embeddedObj.get("id"))); mapRequestToObj(embeddedObj, srvParam.getExpectedClass(), typedVal); } else { try { Long parsedId = new Long(val); typedVal = srvParam.getFindById().invoke(srvParam.getInstance(), ServiceContextStore.get(), parsedId); } catch (NumberFormatException nfe) { // wrong value typedVal = null; } } } else if (persistentClass != null) { String getMethodName = "g" + m.getName().substring(1); try { Method getMethod = obj.getClass().getMethod(getMethodName, (Class[]) null); typedVal = getMethod.invoke(obj, (Object[]) null); } catch (NoSuchMethodException nsme) { typedVal = null; } if (typedVal == null) { typedVal = makeNewInstance(persistentClass, (HashMap<String, Object>) value); } mapRequestToObj((HashMap<String, Object>) value, typedVal.getClass(), typedVal); } else { log.log(Level.WARNING, "Can't convert value for: {0}.{1} ({2})", new Object[] { expectedClass.getName(), m.getName(), (paramTypes.length == 1 ? paramTypes[0].getName() : paramTypes.toString()) }); typedVal = null; } if (typedVal != null) { m.invoke(obj, typedVal); } } } else if (m.getName().startsWith(SET_PREFIX)) { log.log(Level.WARNING, "Unusable setter method: {0}.{1} ({2})", new Object[] { expectedClass.getName(), m.getName(), (paramTypes.length == 1 ? paramTypes[0].getName() : paramTypes.toString()) }); } } }
From source file:org.forumj.web.servlet.post.SetAvatar.java
private Image getImage(FileItem file) throws IOException { Image image = null;/*from ww w. jav a 2 s.c o m*/ InputStream imageStream = null; InputStream in = null; try { in = file.getInputStream(); imageStream = new BufferedInputStream(in); image = (Image) ImageIO.read(imageStream); } finally { if (imageStream != null) { try { imageStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return image; }
From source file:org.foxbpm.web.service.impl.FlowManageServiceImpl.java
public void deployByZip(Map<String, Object> params) { ZipInputStream zipInputStream = null; try {/*from w w w . java 2 s . c o m*/ FileItem file = (FileItem) params.get("processFile"); if (null != file) { zipInputStream = new ZipInputStream(file.getInputStream()); String deploymentId = StringUtil.getString(params.get("deploymentId")); DeploymentBuilder deploymentBuilder = modelService.createDeployment(); deploymentBuilder.addZipInputStream(zipInputStream); // deploymentID? if (StringUtil.isNotEmpty(deploymentId)) { deploymentBuilder.updateDeploymentId(deploymentId); } deploymentBuilder.deploy(); } } catch (IOException e) { throw new FoxbpmWebException(e); } finally { if (null != zipInputStream) { try { zipInputStream.close(); } catch (IOException e) { throw new FoxbpmWebException(e); } } } }
From source file:org.gatein.wcm.portlet.editor.views.ManagerActions.java
public String actionNewImport(ActionRequest request, ActionResponse response, UserWcm userWcm) { log.info("WCM Import: STARTED"); String tmpDir = System.getProperty(Wcm.UPLOADS.TMP_DIR); FileItemFactory factory = new DiskFileItemFactory(Wcm.UPLOADS.MAX_FILE_SIZE, new File(tmpDir)); PortletFileUpload importUpload = new PortletFileUpload(factory); try {/*from ww w.java2 s. com*/ List<FileItem> items = importUpload.parseRequest(request); FileItem file = null; String importStrategy = String.valueOf(Wcm.IMPORT.STRATEGY.NEW); for (FileItem item : items) { if (!item.isFormField()) { file = item; } else { importStrategy = item.getString(); } } // .zip validation if (file != null && file.getContentType() != null && !"application/zip".equalsIgnoreCase(file.getContentType())) { throw new WcmException("File: " + file.getName() + " is not application/zip."); } // log.info("Importing ... " + file.getName() + " with strategy " + importStrategy); wcm.importRepository(file.getInputStream(), importStrategy.charAt(0), userWcm); } catch (Exception e) { log.warning("Error importing file"); e.printStackTrace(); response.setRenderParameter("errorWcm", "Error importing file: " + e.toString()); } log.info("WCM Import: FINISHED"); return Wcm.VIEWS.MANAGER; }
From source file:org.gatein.wcm.portlet.editor.views.UploadsActions.java
public String actionNewUpload(ActionRequest request, ActionResponse response, UserWcm userWcm) { String tmpDir = System.getProperty(Wcm.UPLOADS.TMP_DIR); FileItemFactory factory = new DiskFileItemFactory(Wcm.UPLOADS.MAX_FILE_SIZE, new File(tmpDir)); PortletFileUpload upload = new PortletFileUpload(factory); try {/* w w w. j av a 2 s . com*/ List<FileItem> items = upload.parseRequest(request); FileItem file = null; String description = ""; for (FileItem item : items) { if (!item.isFormField()) { file = item; } else { description = item.getString(); } } Upload newUpload = new Upload(); newUpload.setFileName(file.getName()); newUpload.setMimeType(file.getContentType()); newUpload.setDescription(description); wcm.create(newUpload, file.getInputStream(), userWcm); return Wcm.VIEWS.UPLOADS; } catch (Exception e) { log.warning("Error uploading file"); e.printStackTrace(); response.setRenderParameter("errorWcm", "Error uploading file " + e.toString()); } return Wcm.VIEWS.UPLOADS; }