List of usage examples for org.apache.commons.fileupload FileItem getInputStream
InputStream getInputStream() throws IOException;
From source file:org.kuali.rice.edl.impl.components.NoteConfigComponent.java
public void saveNote(NoteForm form, EDLContext edlContext, Document dom) throws Exception { Note noteToSave = null;/*from w ww . j a v a 2s.co m*/ if (form.getShowEdit() != null && form.getShowEdit().equals("yes")) { //LOG.debug(form.getNoteIdNumber()); noteToSave = getNoteService().getNoteByNoteId(form.getNoteIdNumber()); String noteText = form.getNoteText(); if (noteText != null) { noteToSave.setNoteText(noteText); } //LOG.debug(noteToSave); //LOG.debug(noteToSave.getNoteCreateDate()); //noteToSave.setNoteCreateDate(new Timestamp(noteToSave.getNoteCreateLongDate().longValue())); } else { noteToSave = new Note(); noteToSave.setNoteId(null); noteToSave.setDocumentId(form.getDocId()); noteToSave.setNoteCreateDate(new Timestamp((new Date()).getTime())); noteToSave.setNoteAuthorWorkflowId(edlContext.getUserSession().getPrincipalId()); noteToSave.setNoteText(form.getAddText()); } CustomNoteAttribute customNoteAttribute = null; DocumentRouteHeaderValue routeHeader = getRouteHeaderService().getRouteHeader(noteToSave.getDocumentId()); boolean canEditNote = false; boolean canAddNotes = false; if (routeHeader != null) { customNoteAttribute = routeHeader.getCustomNoteAttribute(); if (customNoteAttribute != null) { customNoteAttribute.setUserSession(edlContext.getUserSession()); canAddNotes = customNoteAttribute.isAuthorizedToAddNotes(); canEditNote = customNoteAttribute.isAuthorizedToEditNote(noteToSave); } } if ((form.getShowEdit() != null && form.getShowEdit().equals("yes") && canEditNote) || ((form.getShowEdit() == null || !form.getShowEdit().equals("yes")) && canAddNotes)) { FileItem uploadedFile = (FileItem) form.getFile(); if (uploadedFile != null && org.apache.commons.lang.StringUtils.isNotBlank(uploadedFile.getName())) { Attachment attachment = new Attachment(); attachment.setAttachedObject(uploadedFile.getInputStream()); String internalFileIndicator = uploadedFile.getName(); int indexOfSlash = internalFileIndicator.lastIndexOf("/"); int indexOfBackSlash = internalFileIndicator.lastIndexOf("\\"); if (indexOfSlash >= 0) { internalFileIndicator = internalFileIndicator.substring(indexOfSlash + 1); } else { if (indexOfBackSlash >= 0) { internalFileIndicator = internalFileIndicator.substring(indexOfBackSlash + 1); } } attachment.setFileName(internalFileIndicator); LOG.debug(internalFileIndicator); attachment.setMimeType(uploadedFile.getContentType()); attachment.setNote(noteToSave); noteToSave.getAttachments().add(attachment); } if (org.apache.commons.lang.StringUtils.isEmpty(noteToSave.getNoteText()) && noteToSave.getAttachments().size() == 0) { if (form.getShowEdit() != null && form.getShowEdit().equals("yes")) { form.setNote(new Note()); } else { form.setAddText(null); } form.setShowEdit("no"); form.setNoteIdNumber(null); // throw new Exception("Note has empty content"); EDLXmlUtils.addGlobalErrorMessage(dom, "Note has empty content"); return; } getNoteService().saveNote(noteToSave); // add ability to send emails when a note is saved. boolean sendEmailOnNoteSave = false; // Check if edoclite specifies <param name="sendEmailOnNoteSave"> Document edlDom = EdlServiceLocator.getEDocLiteService() .getDefinitionXml(edlContext.getEdocLiteAssociation()); XPath xpath = edlContext.getXpath(); String xpathExpression = "//config/param[@name='sendEmailOnNoteSave']"; try { String match = (String) xpath.evaluate(xpathExpression, edlDom, XPathConstants.STRING); if (!StringUtils.isBlank(match) && match.equals("true")) { sendEmailOnNoteSave = true; } } catch (XPathExpressionException e) { throw new WorkflowRuntimeException( "Unable to evaluate sendEmailOnNoteSave xpath expression in NoteConfigComponent saveNote method" + xpathExpression, e); } if (sendEmailOnNoteSave) { xpathExpression = "//data/version[@current='true']/field[@name='emailTo']/value"; String emailTo = xpath.evaluate(xpathExpression, dom); if (StringUtils.isBlank(emailTo)) { EDLXmlUtils.addGlobalErrorMessage(dom, "No email notifications were sent because EmailTo field was empty."); return; } // Actually send the emails. if (isProduction()) { this.to = stringToList(emailTo); } else { String testAddress = getTestAddress(edlDom); if (StringUtils.isBlank(testAddress)) { EDLXmlUtils.addGlobalErrorMessage(dom, "No email notifications were sent because testAddress edl param was empty or not specified in a non production environment"); return; } this.to = stringToList(getTestAddress(edlDom)); } if (!isEmailListValid(this.to)) { EDLXmlUtils.addGlobalErrorMessage(dom, "No email notifications were sent because emailTo field contains invalid email address."); return; } String noteEmailStylesheet = ""; xpathExpression = "//config/param[@name='noteEmailStylesheet']"; try { noteEmailStylesheet = (String) xpath.evaluate(xpathExpression, edlDom, XPathConstants.STRING); if (StringUtils.isBlank(noteEmailStylesheet)) { EDLXmlUtils.addGlobalErrorMessage(dom, "No email notifications were sent because noteEmailStylesheet edl param was empty or not specified."); return; } } catch (XPathExpressionException e) { throw new WorkflowRuntimeException( "Unable to evaluate noteEmailStylesheet xpath expression in NoteConfigComponent method" + xpathExpression, e); } this.styleName = noteEmailStylesheet; this.from = DEFAULT_EMAIL_FROM_ADDRESS; Document document = generateXmlInput(form, edlContext, edlDom); if (LOG.isDebugEnabled()) { LOG.debug("XML input for email tranformation:\n" + XmlJotter.jotNode(document)); } Templates style = loadStyleSheet(styleName); EmailContent emailContent = emailStyleHelper.generateEmailContent(style, document); if (!this.to.isEmpty()) { CoreApiServiceLocator.getMailer().sendEmail(new EmailFrom(from), new EmailToList(this.to), new EmailSubject(emailContent.getSubject()), new EmailBody(emailContent.getBody()), new EmailCcList(this.cc), new EmailBcList(this.bc), emailContent.isHtml()); } } } if (form.getShowEdit() != null && form.getShowEdit().equals("yes")) { form.setNote(new Note()); } else { form.setAddText(null); } form.setShowEdit("no"); form.setNoteIdNumber(null); }
From source file:org.logomattic.portlet.LogomatticContext.java
/** * Saves the specified image in the repository. * * @param image the image to save/* ww w. j a v a2 s . com*/ * @throws IOException any IOException */ public void save(FileItem image) throws IOException { getRoot().saveDocument(image.getName(), image.getContentType(), image.getInputStream()); save(); }
From source file:org.madsonic.controller.ImportPlaylistController.java
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); try {// w w w. ja v a2 s.c om if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<?> items = upload.parseRequest(request); for (Object o : items) { FileItem item = (FileItem) o; if ("file".equals(item.getFieldName()) && !StringUtils.isBlank(item.getName())) { if (item.getSize() > MAX_PLAYLIST_SIZE_MB * 1024L * 1024L) { throw new Exception("The playlist file is too large. Max file size is " + MAX_PLAYLIST_SIZE_MB + " MB."); } String playlistName = FilenameUtils.getBaseName(item.getName()); String fileName = FilenameUtils.getName(item.getName()); String format = StringUtils.lowerCase(FilenameUtils.getExtension(item.getName())); String username = securityService.getCurrentUsername(request); Playlist playlist = playlistService.importPlaylist(username, playlistName, fileName, format, item.getInputStream(), null); map.put("playlist", playlist); } } } } catch (Exception e) { map.put("error", e.getMessage()); } ModelAndView result = super.handleRequestInternal(request, response); result.addObject("model", map); return result; }
From source file:org.mhi.imageutilities.FileHandler.java
public InputStream getFile(String file_field) throws IOException { InputStream blob = null;//w w w . ja v a 2 s . com Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.getFieldName().equals(file_field)) { blob = item.getInputStream(); setContentType(item.getContentType()); setFileSize(item.getSize()); setFileName(item.getName()); } } return blob; }
From source file:org.mifos.dmt.ui.DMTExcelUpload.java
@SuppressWarnings("rawtypes") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DMTLock migrationLock = DMTLock.getInstance(); if (!migrationLock.isLocked()) { migrationLock.getLock();/*from w w w .j a v a 2 s . c o m*/ clearLogs(); response.setContentType("text/plain"); DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(5 * 1024 * 1024); fileItemFactory.setRepository(tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); try { List items = uploadHandler.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); File file = new File(destinationDir, "MigrationTemplate.xlsx"); /*System.out.println("i got here " + destinationDir.toString());*/ Workbook workbook = WorkbookFactory.create(item.getInputStream()); SheetStructure sheetStructure = new SheetStructure(workbook); if (!sheetStructure.processWorkbook()) { logger.error( "Excel upload failed!!Please check if necessary sheets are present in the excel"); throw new DMTException( "Excel upload failed!!Please check if necessary sheets are present in the excel"); } String baseTemplate = DMTConfig.DMT_CONFIG_DIR + "\\DMTMigrationTemplateBase.xlsx"; ColumnStructure columnstructure = new ColumnStructure(workbook, baseTemplate); workbook = columnstructure.processSheetStructure(); PurgeEmptyRows excessrows = new PurgeEmptyRows(workbook); workbook = excessrows.processEmptyRows(); FileOutputStream fileoutputstream = new FileOutputStream(file); workbook.write(fileoutputstream); logger.info("Uploading of Excel has been successful!!"); migrationLock.releaseLock(); } } catch (FileUploadException ex) { logger.error("Error encountered while parsing the request", ex); logger.error("Uploading of Excel has not been successful!!"); migrationLock.releaseLock(); ex.printStackTrace(); } catch (Exception ex) { logger.error("Error encountered while uploading file", ex); logger.error("Uploading of Excel has not been successful!!"); migrationLock.releaseLock(); ex.printStackTrace(); } } else { request.setAttribute("action", "info"); RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/x"); requestDispatcher.forward(request, response); } }
From source file:org.modeshape.web.BackupUploadServlet.java
/** * Gets uploaded file as stream./*from www . jav a 2 s . co m*/ * * @param items * @return the stream * @throws IOException */ private InputStream getStream(List<FileItem> items) throws IOException { for (FileItem i : items) { if (!i.isFormField() && i.getFieldName().equals(CONTENT_PARAMETER)) { return i.getInputStream(); } } return null; }
From source file:org.mojavemvc.core.HttpParameterMapSource.java
private void processUploadedFile(FileItem item, Map<String, Object> paramMap) throws IOException { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); InputStream uploadedStream = item.getInputStream(); paramMap.put(fieldName, new UploadedFile(fileName, uploadedStream, contentType, isInMemory, sizeInBytes)); }
From source file:org.ms123.common.data.JdoLayerImpl.java
public void populate(SessionContext sessionContext, Map from, Object to, Map hintsMap) { PersistenceManager pm = sessionContext.getPM(); if (hintsMap == null) { hintsMap = new HashMap(); }// w w w . j a v a 2 s . c o m Map<String, String> expressions = (Map) hintsMap.get("__expressions"); if (expressions == null) expressions = new HashMap(); BeanMap beanMap = new BeanMap(to); String entityName = m_inflector.getEntityName(to.getClass().getSimpleName()); debug("populate.from:" + from + ",to:" + to + ",BeanMap:" + beanMap + "/hintsMap:" + hintsMap + "/entityName:" + entityName); if (from == null) { return; } Map permittedFields = sessionContext.getPermittedFields(entityName, "write"); Iterator<String> it = from.keySet().iterator(); while (it.hasNext()) { String key = it.next(); Object oldValue = beanMap.get(key); boolean permitted = m_permissionService.hasAdminRole() || "team".equals(entityName) || sessionContext.isFieldPermitted(key, entityName, "write"); if (!key.startsWith("_") && !permitted) { debug("---->populate:field(" + key + ") no write permission"); continue; } else { debug("++++>populate:field(" + key + ") write permitted"); } String datatype = null; String edittype = null; if (!key.startsWith("_")) { Map config = (Map) permittedFields.get(key); if (config != null) { datatype = (String) config.get("datatype"); edittype = (String) config.get("edittype"); } } if (key.equals(STATE_FIELD) && !m_permissionService.hasAdminRole()) { continue; } if ("auto".equals(edittype)) continue; String mode = null; Map hm = (Map) hintsMap.get(key); if (hm != null) { Object m = hm.get("mode"); if (m != null && m instanceof String) { mode = (String) m; } if (mode == null) { m = hm.get("useit"); if (m != null && m instanceof String) { mode = (String) m; } } } if (mode == null) { mode = "replace"; } Class clazz = beanMap.getType(key); debug("\ttype:" + clazz + "(" + key + "=" + from.get(key) + ")"); if ("_ignore_".equals(from.get(key))) { continue; } if (clazz == null) { debug("\t--- Warning property not found:" + key); } else if (clazz.equals(java.util.Date.class)) { String value = Utils.getString(from.get(key), beanMap.get(key), mode); debug("\tDate found:" + key + "=>" + value); Date date = null; if (value != null) { try { Long val = Long.valueOf(value); date = (Date) ConvertUtils.convert(val, Date.class); debug("\tdate1:" + date); } catch (Exception e) { try { DateTime dt = new DateTime(value); date = new Date(dt.getMillis()); debug("\tdate2:" + date); } catch (Exception e1) { try { int space = value.indexOf(" "); if (space != -1) { value = value.substring(0, space) + "T" + value.substring(space + 1); DateTime dt = new DateTime(value); date = new Date(dt.getMillis()); } debug("\tdate3:" + date); } catch (Exception e2) { debug("\terror setting date:" + e); } } } } debug("\tsetting date:" + date); beanMap.put(key, date); } else if (clazz.equals(java.util.Map.class)) { info("!!!!!!!!!!!!!!!!!!!Map not implemented"); } else if (clazz.equals(java.util.List.class) || clazz.equals(java.util.Set.class)) { boolean isList = clazz.equals(java.util.List.class); boolean isSimple = false; if (datatype != null && datatype.startsWith("list_")) { isSimple = true; } try { Class type = TypeUtils.getTypeForField(to, key); debug("type:" + type + " fill with: " + from.get(key) + ",list:" + beanMap.get(key) + "/mode:" + mode); Collection valList = isList ? new ArrayList() : new HashSet(); Object fromVal = from.get(key); if (fromVal instanceof String && ((String) fromVal).length() > 0) { info("FromVal is StringSchrott, ignore"); continue; } if (from.get(key) instanceof Collection) { valList = (Collection) from.get(key); } if (valList == null) { valList = isList ? new ArrayList() : new HashSet(); } Collection toList = (Collection) PropertyUtils.getProperty(to, key); debug("toList:" + toList); debug("valList:" + valList); if (toList == null) { toList = isList ? new ArrayList() : new HashSet(); PropertyUtils.setProperty(to, key, toList); } if ("replace".equals(mode)) { boolean isEqual = false; if (isSimple) { isEqual = Utils.isCollectionEqual(toList, valList); if (!isEqual) { toList.clear(); } debug("\tisEqual:" + isEqual); } else { List deleteList = new ArrayList(); String namespace = sessionContext.getStoreDesc().getNamespace(); for (Object o : toList) { if (type.getName().endsWith(".Team")) { int status = m_teamService.getTeamStatus(namespace, new BeanMap(o), null, sessionContext.getUserName()); debug("populate.replace.teamStatus:" + status + "/" + new HashMap(new BeanMap(o))); if (status != -1) { pm.deletePersistent(o); deleteList.add(o); } } else { pm.deletePersistent(o); deleteList.add(o); } } for (Object o : deleteList) { toList.remove(o); } } debug("populate.replace.toList:" + toList + "/" + type.getName()); if (isSimple) { if (!isEqual) { for (Object o : valList) { toList.add(o); } } } else { for (Object o : valList) { Map valMap = (Map) o; Object n = type.newInstance(); if (type.getName().endsWith(".Team")) { valMap.remove("id"); Object desc = valMap.get("description"); Object name = valMap.get("name"); Object dis = valMap.get("disabled"); String teamid = (String) valMap.get("teamid"); Object ti = Utils.getTeamintern(sessionContext, teamid); if (desc == null) { valMap.put("description", PropertyUtils.getProperty(ti, "description")); } if (name == null) { valMap.put("name", PropertyUtils.getProperty(ti, "name")); } if (dis == null) { valMap.put("disabled", false); } pm.makePersistent(n); populate(sessionContext, valMap, n, null); PropertyUtils.setProperty(n, "teamintern", ti); } else { pm.makePersistent(n); populate(sessionContext, valMap, n, null); } debug("populated.add:" + new HashMap(new BeanMap(n))); toList.add(n); } } } else if ("remove".equals(mode)) { if (isSimple) { for (Object o : valList) { if (toList.contains(o)) { toList.remove(o); } } } else { for (Object ol : valList) { Map map = (Map) ol; Object o = Utils.listContainsId(toList, map, "teamid"); if (o != null) { toList.remove(o); pm.deletePersistent(o); } } } } else if ("add".equals(mode)) { if (isSimple) { for (Object o : valList) { toList.add(o); } } else { for (Object ol : valList) { Map map = (Map) ol; Object o = Utils.listContainsId(toList, map, "teamid"); if (o != null) { populate(sessionContext, map, o, null); } else { o = type.newInstance(); if (type.getName().endsWith(".Team")) { Object desc = map.get("description"); Object name = map.get("name"); Object dis = map.get("disabled"); String teamid = (String) map.get("teamid"); Object ti = Utils.getTeamintern(sessionContext, teamid); if (desc == null) { map.put("description", PropertyUtils.getProperty(ti, "description")); } if (name == null) { map.put("name", PropertyUtils.getProperty(ti, "name")); } if (dis == null) { map.put("disabled", false); } pm.makePersistent(o); populate(sessionContext, map, o, null); PropertyUtils.setProperty(o, "teamintern", ti); } else { pm.makePersistent(o); populate(sessionContext, map, o, null); } toList.add(o); } } } } else if ("assign".equals(mode)) { if (!isSimple) { for (Object ol : valList) { Map map = (Map) ol; Object o = Utils.listContainsId(toList, map); if (o != null) { debug("id:" + map + " already assigned"); } else { Object id = map.get("id"); Boolean assign = Utils.getBoolean(map.get("assign")); Object obj = pm.getObjectById(type, id); if (assign) { toList.add(obj); } else { toList.remove(obj); } } } } } } catch (Exception e) { e.printStackTrace(); debug("populate.list.failed:" + key + "=>" + from.get(key) + ";" + e); } } else if (clazz.equals(java.lang.Boolean.class)) { try { beanMap.put(key, ConvertUtils.convert(from.get(key), Boolean.class)); } catch (Exception e) { debug("populate.boolean.failed:" + key + "=>" + from.get(key) + ";" + e); } } else if (clazz.equals(java.lang.Double.class)) { String value = Utils.getString(from.get(key), beanMap.get(key), mode); try { beanMap.put(key, Double.valueOf(value)); } catch (Exception e) { debug("populate.double.failed:" + key + "=>" + value + ";" + e); } } else if (clazz.equals(java.lang.Long.class)) { try { beanMap.put(key, ConvertUtils.convert(from.get(key), Long.class)); } catch (Exception e) { debug("populate.long.failed:" + key + "=>" + from.get(key) + ";" + e); } } else if (clazz.equals(java.lang.Integer.class)) { debug("Integer:" + ConvertUtils.convert(from.get(key), Integer.class)); try { beanMap.put(key, ConvertUtils.convert(from.get(key), Integer.class)); } catch (Exception e) { debug("populate.integer.failed:" + key + "=>" + from.get(key) + ";" + e); } } else if ("binary".equals(datatype) || clazz.equals(byte[].class)) { InputStream is = null; InputStream is2 = null; try { if (from.get(key) instanceof FileItem) { FileItem fi = (FileItem) from.get(key); String name = fi.getName(); byte[] bytes = IOUtils.toByteArray(fi.getInputStream()); if (bytes != null) { debug("bytes:" + bytes.length); } beanMap.put(key, bytes); is = fi.getInputStream(); is2 = fi.getInputStream(); } else if (from.get(key) instanceof Map) { Map map = (Map) from.get(key); String storeLocation = (String) map.get("storeLocation"); is = new FileInputStream(new File(storeLocation)); is2 = new FileInputStream(new File(storeLocation)); byte[] bytes = IOUtils.toByteArray(is); if (bytes != null) { debug("bytes2:" + bytes.length); } is.close(); beanMap.put(key, bytes); is = new FileInputStream(new File(storeLocation)); } else if (from.get(key) instanceof String) { String value = (String) from.get(key); if ("ignore".equals(value)) { debug("ignore:"); return; } if (value.startsWith("data:")) { int ind = value.indexOf(";base64,"); byte b[] = Base64.decode(value.substring(ind + 8)); beanMap.put(key, b); is = new ByteArrayInputStream(b); is2 = new ByteArrayInputStream(b); } else { byte b[] = value.getBytes(); beanMap.put(key, b); is = new ByteArrayInputStream(b); is2 = new ByteArrayInputStream(b); } } else { debug("populate.byte[].no a FileItem:" + key + "=>" + from.get(key)); continue; } Tika tika = new Tika(); TikaInputStream stream = TikaInputStream.get(is); TikaInputStream stream2 = TikaInputStream.get(is2); String text = tika.parseToString(is); debug("Text:" + text); try { beanMap.put("text", text); } catch (Exception e) { beanMap.put("text", text.getBytes()); } //@@@MS Hardcoded try { Detector detector = new DefaultDetector(); MediaType mime = detector.detect(stream2, new Metadata()); debug("Mime:" + mime.getType() + "|" + mime.getSubtype() + "|" + mime.toString()); beanMap.put("type", mime.toString()); from.put("type", mime.toString()); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); debug("populate.byte[].failed:" + key + "=>" + from.get(key) + ";" + e); } finally { try { is.close(); is2.close(); } catch (Exception e) { } } } else { boolean ok = false; try { Class type = TypeUtils.getTypeForField(to, key); if (type != null) { Object o = type.newInstance(); boolean hasAnn = type.isAnnotationPresent(PersistenceCapable.class); debug("hasAnnotation:" + hasAnn); if (o instanceof javax.jdo.spi.PersistenceCapable || hasAnn) { Object id = null; try { Object _id = from.get(key); if (_id != null) { if (_id instanceof Map) { id = ((Map) _id).get("id"); } else { String s = String.valueOf(_id); if (s.indexOf("/") >= 0) { _id = Utils.extractId(s); } Class idClass = PropertyUtils.getPropertyType(o, "id"); id = (idClass.equals(Long.class)) ? Long.valueOf(_id + "") : _id; } } } catch (Exception e) { } if (id != null && !"".equals(id) && !"null".equals(id)) { debug("\tId2:" + id); Object relatedObject = pm.getObjectById(type, id); List<Collection> candidates = TypeUtils.getCandidateLists(relatedObject, to, null); if (candidates.size() == 1) { Collection l = candidates.get(0); debug("list.contains:" + l.contains(to)); if (!l.contains(to)) { l.add(to); } } beanMap.put(key, relatedObject); } else { Object relatedObject = beanMap.get(key); debug("\trelatedObject:" + relatedObject); if (relatedObject != null) { List<Collection> candidates = TypeUtils.getCandidateLists(relatedObject, to, null); if (candidates.size() == 1) { Collection l = candidates.get(0); debug("list.contains:" + l.contains(to)); if (l.contains(to)) { l.remove(to); } } } beanMap.put(key, null); } ok = true; } } } catch (Exception e) { e.printStackTrace(); } if (!ok) { String value = Utils.getString(from.get(key), beanMap.get(key), mode); // debug("populate:" + key + "=>" + value); // debug("String:" + ConvertUtils.convert(from.get(key), String.class)); try { beanMap.put(key, value); } catch (Exception e) { debug("populate.failed:" + key + "=>" + value + ";" + e); } } } String expression = expressions.get(key); if (!isEmpty(expression)) { beanMap.put(key, oldValue); Map scriptCache = (Map) sessionContext.getProperty("scriptCache"); if (scriptCache == null) { scriptCache = new HashMap(); sessionContext.setProperty("scriptCache", scriptCache); } Object result = Utils.eval(expression, beanMap, scriptCache); try { if ("string".equals(datatype) && !(result instanceof String)) { beanMap.put(key, ConvertUtils.convert(result, String.class)); } else { beanMap.put(key, result); } } catch (Exception e) { info("Cannot set value for(" + key + "):" + result + "/" + e.getMessage()); } } } }
From source file:org.ms123.common.data.MultiOperations.java
public static void populate(SessionContext sessionContext, Map sourceMap, Object destinationObj, Map hintsMap) { PersistenceManager pm = sessionContext.getPM(); if (hintsMap == null) { hintsMap = new HashMap(); }//from w w w . j a v a 2 s. com boolean noUpdate = Utils.getBoolean(hintsMap, "noUpdate", false); BeanMap destinationMap = new BeanMap(destinationObj); String entityName = m_inflector.getEntityName(destinationObj.getClass().getSimpleName()); debug("populate.sourceMap:" + sourceMap + ",destinationObj:" + destinationObj + ",destinationMap:" + destinationMap + "/hintsMap:" + hintsMap + "/entityName:" + entityName); if (sourceMap == null) { return; } debug("populate(" + entityName + ") is a persistObject:" + javax.jdo.JDOHelper.isPersistent(destinationObj) + "/" + javax.jdo.JDOHelper.isNew(destinationObj)); if (sourceMap.get("id") != null) { debug("populate(" + entityName + ") has id:" + sourceMap.get("id")); return; } Map permittedFields = sessionContext.getPermittedFields(entityName, "write"); Iterator<String> it = sourceMap.keySet().iterator(); while (it.hasNext()) { String propertyName = it.next(); boolean permitted = sessionContext.getPermissionService().hasAdminRole() || "team".equals(entityName) || sessionContext.isFieldPermitted(propertyName, entityName, "write"); if (!propertyName.startsWith("_") && !permitted) { debug("---->populate:field(" + propertyName + ") no write permission"); continue; } else { debug("++++>populate:field(" + propertyName + ") write permitted"); } String datatype = null; String edittype = null; if (!propertyName.startsWith("_")) { Map config = (Map) permittedFields.get(propertyName); if (config != null) { datatype = (String) config.get("datatype"); edittype = (String) config.get("edittype"); } } if (propertyName.equals(STATE_FIELD) && !sessionContext.getPermissionService().hasAdminRole()) { continue; } if ("auto".equals(edittype)) continue; String mode = null; Map hm = (Map) hintsMap.get(propertyName); if (hm != null) { Object m = hm.get("mode"); if (m != null && m instanceof String) { mode = (String) m; } if (mode == null) { m = hm.get("useit"); if (m != null && m instanceof String) { mode = (String) m; } } } if (mode == null) { mode = "replace"; } Class propertyClass = destinationMap.getType(propertyName); debug("\ttype:" + propertyClass + "(" + propertyName + "=" + sourceMap.get(propertyName) + ")"); if ("_ignore_".equals(sourceMap.get(propertyName))) { continue; } if (propertyClass == null) { debug("\t--- Warning property not found:" + propertyName); } else if (propertyClass.equals(java.util.Date.class)) { String value = Utils.getString(sourceMap.get(propertyName), destinationMap.get(propertyName), mode); debug("\tDate found:" + propertyName + "=>" + value); Date date = null; if (value != null) { try { Long val = Long.valueOf(value); date = (Date) ConvertUtils.convert(val, Date.class); debug("\tdate1:" + date); } catch (Exception e) { try { DateTime dt = new DateTime(value); date = new Date(dt.getMillis()); debug("\tdate2:" + date); } catch (Exception e1) { try { int space = value.indexOf(" "); if (space != -1) { value = value.substring(0, space) + "T" + value.substring(space + 1); DateTime dt = new DateTime(value); date = new Date(dt.getMillis()); } debug("\tdate3:" + date); } catch (Exception e2) { debug("\terror setting date:" + e); } } } } debug("\tsetting date:" + date); destinationMap.put(propertyName, date); } else if (propertyClass.equals(java.util.Map.class)) { info("!!!!!!!!!!!!!!!!!!!Map not implemented"); } else if (propertyClass.equals(java.util.List.class) || propertyClass.equals(java.util.Set.class)) { boolean isList = propertyClass.equals(java.util.List.class); boolean isSimple = false; if (datatype != null && datatype.startsWith("list_")) { isSimple = true; } try { Class propertyType = TypeUtils.getTypeForField(destinationObj, propertyName); debug("propertyType:" + propertyType + " fill with: " + sourceMap.get(propertyName) + ",list:" + destinationMap.get(propertyName) + "/mode:" + mode); Collection sourceList = isList ? new ArrayList() : new HashSet(); Object fromVal = sourceMap.get(propertyName); if (fromVal instanceof String && ((String) fromVal).length() > 0) { info("FromVal is StringSchrott, ignore"); continue; } if (sourceMap.get(propertyName) instanceof Collection) { sourceList = (Collection) sourceMap.get(propertyName); } if (sourceList == null) { sourceList = isList ? new ArrayList() : new HashSet(); } Collection destinationList = (Collection) PropertyUtils.getProperty(destinationObj, propertyName); debug("destinationList:" + destinationList); debug("sourceList:" + sourceList); if (destinationList == null) { destinationList = isList ? new ArrayList() : new HashSet(); PropertyUtils.setProperty(destinationObj, propertyName, destinationList); } if ("replace".equals(mode)) { boolean isEqual = false; if (isSimple) { isEqual = Utils.isCollectionEqual(destinationList, sourceList); if (!isEqual) { destinationList.clear(); } debug("\tisEqual:" + isEqual); } else { List deleteList = new ArrayList(); String namespace = sessionContext.getStoreDesc().getNamespace(); for (Object o : destinationList) { if (propertyType.getName().endsWith(".Team")) { int status = sessionContext.getTeamService().getTeamStatus(namespace, new BeanMap(o), null, sessionContext.getUserName()); debug("populate.replace.teamStatus:" + status + "/" + new HashMap(new BeanMap(o))); if (status != -1) { pm.deletePersistent(o); deleteList.add(o); } } else { pm.deletePersistent(o); deleteList.add(o); } } for (Object o : deleteList) { destinationList.remove(o); } } debug("populate.replace.destinationList:" + destinationList + "/" + propertyType.getName()); if (isSimple) { if (!isEqual) { for (Object o : sourceList) { destinationList.add(o); } } } else { for (Object o : sourceList) { Map childSourceMap = (Map) o; Object childDestinationObj = propertyType.newInstance(); if (propertyType.getName().endsWith(".Team")) { childSourceMap.remove("id"); Object desc = childSourceMap.get("description"); Object name = childSourceMap.get("name"); Object dis = childSourceMap.get("disabled"); String teamid = (String) childSourceMap.get("teamid"); Object ti = Utils.getTeamintern(sessionContext, teamid); if (desc == null) { childSourceMap.put("description", PropertyUtils.getProperty(ti, "description")); } if (name == null) { childSourceMap.put("name", PropertyUtils.getProperty(ti, "name")); } if (dis == null) { childSourceMap.put("disabled", false); } pm.makePersistent(childDestinationObj); populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); PropertyUtils.setProperty(childDestinationObj, "teamintern", ti); } else { pm.makePersistent(childDestinationObj); populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); } debug("populated.add:" + new HashMap(new BeanMap(childDestinationObj))); destinationList.add(childDestinationObj); } } } else if ("remove".equals(mode)) { if (isSimple) { for (Object o : sourceList) { if (destinationList.contains(o)) { destinationList.remove(o); } } } else { for (Object ol : sourceList) { Map childSourceMap = (Map) ol; Object o = Utils.listContainsId(destinationList, childSourceMap, "teamid"); if (o != null) { destinationList.remove(o); pm.deletePersistent(o); } } } } else if ("add".equals(mode)) { if (isSimple) { for (Object o : sourceList) { destinationList.add(o); } } else { for (Object ol : sourceList) { Map childSourceMap = (Map) ol; Object childDestinationObj = Utils.listContainsId(destinationList, childSourceMap, "teamid"); if (childDestinationObj != null) { populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); } else { childDestinationObj = propertyType.newInstance(); if (propertyType.getName().endsWith(".Team")) { Object desc = childSourceMap.get("description"); Object name = childSourceMap.get("name"); Object dis = childSourceMap.get("disabled"); String teamid = (String) childSourceMap.get("teamid"); Object ti = Utils.getTeamintern(sessionContext, teamid); if (desc == null) { childSourceMap.put("description", PropertyUtils.getProperty(ti, "description")); } if (name == null) { childSourceMap.put("name", PropertyUtils.getProperty(ti, "name")); } if (dis == null) { childSourceMap.put("disabled", false); } pm.makePersistent(childDestinationObj); populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); PropertyUtils.setProperty(childDestinationObj, "teamintern", ti); } else { pm.makePersistent(childDestinationObj); populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); } destinationList.add(childDestinationObj); } } } } else if ("assign".equals(mode)) { if (!isSimple) { for (Object ol : sourceList) { Map childSourceMap = (Map) ol; Object childDestinationObj = Utils.listContainsId(destinationList, childSourceMap); if (childDestinationObj != null) { debug("id:" + childSourceMap + " already assigned"); } else { Object id = childSourceMap.get("id"); Boolean assign = Utils.getBoolean(childSourceMap.get("assign")); Object obj = pm.getObjectById(propertyType, id); if (assign) { destinationList.add(obj); } else { destinationList.remove(obj); } } } } } } catch (Exception e) { e.printStackTrace(); debug("populate.list.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } } else if (propertyClass.equals(java.lang.Boolean.class)) { try { destinationMap.put(propertyName, ConvertUtils.convert(sourceMap.get(propertyName), Boolean.class)); } catch (Exception e) { debug("populate.boolean.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } } else if (propertyClass.equals(java.lang.Double.class)) { String value = Utils.getString(sourceMap.get(propertyName), destinationMap.get(propertyName), mode); try { destinationMap.put(propertyName, Double.valueOf(value)); } catch (Exception e) { debug("populate.double.failed:" + propertyName + "=>" + value + ";" + e); } } else if (propertyClass.equals(java.lang.Long.class)) { try { destinationMap.put(propertyName, ConvertUtils.convert(sourceMap.get(propertyName), Long.class)); } catch (Exception e) { debug("populate.long.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } } else if (propertyClass.equals(java.lang.Integer.class)) { debug("Integer:" + ConvertUtils.convert(sourceMap.get(propertyName), Integer.class)); try { destinationMap.put(propertyName, ConvertUtils.convert(sourceMap.get(propertyName), Integer.class)); } catch (Exception e) { debug("populate.integer.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } } else if ("binary".equals(datatype) || propertyClass.equals(byte[].class)) { InputStream is = null; InputStream is2 = null; try { if (sourceMap.get(propertyName) instanceof FileItem) { FileItem fi = (FileItem) sourceMap.get(propertyName); String name = fi.getName(); byte[] bytes = IOUtils.toByteArray(fi.getInputStream()); if (bytes != null) { debug("bytes:" + bytes.length); } destinationMap.put(propertyName, bytes); is = fi.getInputStream(); is2 = fi.getInputStream(); } else if (sourceMap.get(propertyName) instanceof Map) { Map map = (Map) sourceMap.get(propertyName); String storeLocation = (String) map.get("storeLocation"); is = new FileInputStream(new File(storeLocation)); is2 = new FileInputStream(new File(storeLocation)); byte[] bytes = IOUtils.toByteArray(is); if (bytes != null) { debug("bytes2:" + bytes.length); } is.close(); destinationMap.put(propertyName, bytes); is = new FileInputStream(new File(storeLocation)); } else if (sourceMap.get(propertyName) instanceof String) { String value = (String) sourceMap.get(propertyName); if (value.startsWith("data:")) { int ind = value.indexOf(";base64,"); byte b[] = Base64.decode(value.substring(ind + 8)); destinationMap.put(propertyName, b); is = new ByteArrayInputStream(b); is2 = new ByteArrayInputStream(b); } else { } } else { debug("populate.byte[].no a FileItem:" + propertyName + "=>" + sourceMap.get(propertyName)); continue; } Tika tika = new Tika(); TikaInputStream stream = TikaInputStream.get(is); TikaInputStream stream2 = TikaInputStream.get(is2); String text = tika.parseToString(is); debug("Text:" + text); try { destinationMap.put("text", text); } catch (Exception e) { destinationMap.put("text", text.getBytes()); } //@@@MS Hardcoded try { Detector detector = new DefaultDetector(); MediaType mime = detector.detect(stream2, new Metadata()); debug("Mime:" + mime.getType() + "|" + mime.getSubtype() + "|" + mime.toString()); destinationMap.put("type", mime.toString()); sourceMap.put("type", mime.toString()); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); debug("populate.byte[].failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } finally { try { is.close(); is2.close(); } catch (Exception e) { } } } else { boolean ok = false; try { Class propertyType = TypeUtils.getTypeForField(destinationObj, propertyName); debug("propertyType:" + propertyType + "/" + propertyName); if (propertyType != null) { boolean hasAnn = propertyType.isAnnotationPresent(PersistenceCapable.class); debug("hasAnnotation:" + hasAnn); if (propertyType.newInstance() instanceof javax.jdo.spi.PersistenceCapable || hasAnn) { handleRelatedTo(sessionContext, sourceMap, propertyName, destinationMap, destinationObj, propertyType); Object obj = sourceMap.get(propertyName); if (obj != null && obj instanceof Map) { Map childSourceMap = (Map) obj; Object childDestinationObj = destinationMap.get(propertyName); if (childDestinationObj == null) { childDestinationObj = propertyType.newInstance(); destinationMap.put(propertyName, childDestinationObj); } populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); } else { if (obj == null) { destinationMap.put(propertyName, null); } } ok = true; } } } catch (Exception e) { e.printStackTrace(); } if (!ok) { String value = Utils.getString(sourceMap.get(propertyName), destinationMap.get(propertyName), mode); try { if (noUpdate) { if (Utils.isEmptyObj(destinationMap.get(propertyName))) { destinationMap.put(propertyName, value); } } else { destinationMap.put(propertyName, value); } } catch (Exception e) { debug("populate.failed:" + propertyName + "=>" + value + ";" + e); } } } } }
From source file:org.mskcc.cbio.portal.servlet.EchoFile.java
/** * * If you specify the `str` parameter in the request, the servlet echoes back the string as is. * * If you specify files in the request, each file gets echoed back as a json object * { name -> string (content of file)} * * @param request/*from w w w . j a v a 2s .c o m*/ * @param response * @throws ServletException * @throws IOException */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Writer writer = response.getWriter(); try { String str = request.getParameter("str"); if (str != null) { writer.write(request.getParameter("str")); return; } Map fieldName2fileContent = new HashMap<String, String>(); List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (item.getSize() == 0) { // skip empty files continue; } InputStream contentStream = item.getInputStream(); String fieldName = item.getFieldName(); // slurp the file as a string String encoding = "UTF-8"; StringWriter stringWriter = new StringWriter(); IOUtils.copy(contentStream, stringWriter, encoding); String contentString = stringWriter.toString(); fieldName2fileContent.put(fieldName, contentString); } // write the objects out as json response.setContentType("application/json"); ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(writer, fieldName2fileContent); } // catch all exceptions catch (Exception e) { // "log" it System.out.println(e); // hide details from user throw new ServletException("there was an error processing your request"); } }