List of usage examples for java.lang NumberFormatException toString
public String toString()
From source file:com.cloud.hypervisor.xen.resource.CitrixResourceBase.java
protected String getLowestAvailableVIFDeviceNum(Connection conn, VM vm) { String vmName = ""; try {//from w w w . j a va 2 s. c om vmName = vm.getNameLabel(conn); List<Integer> usedDeviceNums = new ArrayList<Integer>(); Set<VIF> vifs = vm.getVIFs(conn); Iterator<VIF> vifIter = vifs.iterator(); while (vifIter.hasNext()) { VIF vif = vifIter.next(); try { usedDeviceNums.add(Integer.valueOf(vif.getDevice(conn))); } catch (NumberFormatException e) { String msg = "Obtained an invalid value for an allocated VIF device number for VM: " + vmName; s_logger.debug(msg, e); throw new CloudRuntimeException(msg); } } for (Integer i = 0; i < _maxNics; i++) { if (!usedDeviceNums.contains(i)) { s_logger.debug("Lowest available Vif device number: " + i + " for VM: " + vmName); return i.toString(); } } } catch (XmlRpcException e) { String msg = "Caught XmlRpcException: " + e.getMessage(); s_logger.warn(msg, e); } catch (XenAPIException e) { String msg = "Caught XenAPIException: " + e.toString(); s_logger.warn(msg, e); } throw new CloudRuntimeException("Could not find available VIF slot in VM with name: " + vmName); }
From source file:org.etudes.jforum.view.admin.ImportExportAction.java
/** * creates forum for a category/*w ww .j a v a 2s . c o m*/ * * @param forumEle */ /*private Forum createForum(Element forumEle, Category category) throws Exception { if (logger.isDebugEnabled()) logger.debug("Entering createForum......"); List eleForumTitles = (List) forumEle.elements("title"); if (eleForumTitles == null || eleForumTitles.size() == 0) return null; // create the forum Element titleEle = (Element) forumEle.elements("title").get(0); int forumType = 0, forumAccessType = 0, forumGradeType = 0; float gradePoints = 0f; Date startDate = null, endDate = null; int lockEndDate = 0; int addToGradebook = 0; int minPosts = 0, minPostsRequired = 0; String parameters = forumEle.attributeValue("parameters"); if (parameters != null && parameters.trim().length() > 0) { String param[] = parameters.split("&"); for (int i = 0; i < param.length; i++) { if (param[i].startsWith("forumtype")) { try { if (param[i].indexOf('=') != -1) forumType = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("accesstype")) { try { if (param[i].indexOf('=') != -1) forumAccessType = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("gradetype")) { try { if (param[i].indexOf('=') != -1) forumGradeType = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("gradepoints")) { try { if (param[i].indexOf('=') != -1) gradePoints = Float.parseFloat(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("startdate")) { try { if (param[i].indexOf('=') != -1) { try { startDate = getDateFromString(param[i].substring(param[i].indexOf('=') + 1)); } catch (ParseException e) { } } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("enddate")) { try { if (param[i].indexOf('=') != -1) { try { endDate = getDateFromString(param[i].substring(param[i].indexOf('=') + 1)); } catch (ParseException e) { } } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("lockenddate")) { try { if (param[i].indexOf('=') != -1) lockEndDate = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("addtogradebook")) { try { if (param[i].indexOf('=') != -1) addToGradebook = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("minpostsrequired")) { try { if (param[i].indexOf('=') != -1) minPostsRequired = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("minposts")) { try { if (param[i].indexOf('=') != -1) minPosts = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } } } // forum types are 0,1,2 and access types are 0,1,2 if (forumType > 2) forumType = Forum.TYPE_NORMAL; if (forumAccessType > 2) forumAccessType = Forum.ACCESS_SITE; Forum f = new Forum(); if ((category.getStartDate()) == null && (category.getEndDate() == null)) { f.setStartDate(startDate); f.setEndDate(endDate); if (endDate != null) { f.setLockForum((lockEndDate == 1) ? true : false); } } else { f.setStartDate(null); f.setEndDate(null); } f.setIdCategories(category.getId()); f.setName(titleEle.getTextTrim()); f.setModerated(false); f.setType(forumType); f.setAccessType(forumAccessType); if (forumGradeType == Forum.GRADE_BY_FORUM || forumGradeType == Forum.GRADE_BY_TOPIC) f.setGradeType(forumGradeType); else f.setGradeType(Forum.GRADE_DISABLED); // description List genElements = forumEle.selectNodes("./imsmd:lom/imsmd:general"); if (genElements != null && genElements.size() > 0) { Element generalElement = (Element) genElements.get(0); Element descElement = generalElement.element("description"); String description = descElement.selectSingleNode(".//imsmd:langstring").getText(); if (description != null) f.setDescription(description.trim()); } int forumId = DataAccessDriver.getInstance().newForumDAO().addNew(f); f.setId(forumId); ForumRepository.addForum(f); // create grade if forum is grade by forum if (f.getGradeType() == Forum.GRADE_BY_FORUM) { Grade grade = new Grade(); grade.setContext(ToolManager.getCurrentPlacement().getContext()); grade.setForumId(forumId); try { grade.setPoints(gradePoints); } catch (NumberFormatException ne) { grade.setPoints(0f); } grade.setType(Forum.GRADE_BY_FORUM); Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext()); if (site.getToolForCommonId(SakaiSystemGlobals.getValue(ConfigKeys.GRADEBOOK_TOOL_ID)) != null) { grade.setAddToGradeBook((addToGradebook == 1) ? true : false); } else { grade.setAddToGradeBook(false); } if (minPostsRequired == 1) { grade.setMinimumPostsRequired(true); grade.setMinimumPosts(minPosts); } int gradeId = DataAccessDriver.getInstance().newGradeDAO().addNew(grade); grade.setId(gradeId); // add to gradebook if (grade.isAddToGradeBook()) { String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); JForumGBService jForumGBService = null; jForumGBService = (JForumGBService)ComponentManager.get("org.etudes.api.app.jforum.JForumGBService"); if (!jForumGBService.isAssignmentDefined(gradebookUid, f.getName())) { String url = null; Date gbItemEndDate = null; if ((f.getStartDate() != null) || (f.getEndDate() != null)) { gbItemEndDate = f.getEndDate(); } else if ((category.getStartDate() != null) || (category.getEndDate() != null)) { gbItemEndDate = category.getEndDate(); } jForumGBService.addExternalAssessment(gradebookUid, "discussions-" + String.valueOf(grade.getId()), url, f.getName(), grade.getPoints(), gbItemEndDate, I18n.getMessage("Grade.sendToGradebook.description")); } } }*/ private org.etudes.api.app.jforum.Forum createForum(Element forumEle, org.etudes.api.app.jforum.Category category) throws Exception { if (logger.isDebugEnabled()) { logger.debug("Entering createForum......"); } List eleForumTitles = (List) forumEle.elements("title"); if (eleForumTitles == null || eleForumTitles.size() == 0) { return null; } // create the forum Element titleEle = (Element) forumEle.elements("title").get(0); int forumType = 0, forumAccessType = 0, forumGradeType = 0; float gradePoints = 0f; Date startDate = null, endDate = null, allowUntilDate = null; ; //int lockEndDate = 0; int hideUntilOpen = 0; int addToGradebook = 0; int minPosts = 0, minPostsRequired = 0; String parameters = forumEle.attributeValue("parameters"); if (parameters != null && parameters.trim().length() > 0) { String param[] = parameters.split("&"); for (int i = 0; i < param.length; i++) { if (param[i].startsWith("forumtype")) { try { if (param[i].indexOf('=') != -1) forumType = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("accesstype")) { try { if (param[i].indexOf('=') != -1) forumAccessType = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("gradetype")) { try { if (param[i].indexOf('=') != -1) forumGradeType = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("gradepoints")) { try { if (param[i].indexOf('=') != -1) gradePoints = Float.parseFloat(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("startdate")) { try { if (param[i].indexOf('=') != -1) { try { startDate = getDateFromString(param[i].substring(param[i].indexOf('=') + 1)); } catch (ParseException e) { } } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("hideuntilopen")) { try { if (param[i].indexOf('=') != -1) hideUntilOpen = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("enddate")) { try { if (param[i].indexOf('=') != -1) { try { endDate = getDateFromString(param[i].substring(param[i].indexOf('=') + 1)); } catch (ParseException e) { } } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } /*else if (param[i].startsWith("lockenddate")) { try { if (param[i].indexOf('=') != -1) lockEndDate = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } }*/ else if (param[i].startsWith("allowuntildate")) { try { if (param[i].indexOf('=') != -1) { try { allowUntilDate = getDateFromString(param[i].substring(param[i].indexOf('=') + 1)); } catch (ParseException e) { } } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("addtogradebook")) { try { if (param[i].indexOf('=') != -1) addToGradebook = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("minpostsrequired")) { try { if (param[i].indexOf('=') != -1) minPostsRequired = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("minposts")) { try { if (param[i].indexOf('=') != -1) minPosts = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) { logger.error(e.toString(), e); } } } } } // forum types are 0,1,2 and access types are 0,1,2 if (forumType > 2) { forumType = Forum.TYPE_NORMAL; } if (forumAccessType > 2) { forumAccessType = Forum.ACCESS_SITE; } JForumForumService jforumForumService = (JForumForumService) ComponentManager .get("org.etudes.api.app.jforum.JForumForumService"); org.etudes.api.app.jforum.Forum forum = jforumForumService.newForum(); if ((category.getAccessDates().getOpenDate()) == null && (category.getAccessDates().getDueDate() == null) && (category.getAccessDates().getAllowUntilDate() == null)) { forum.getAccessDates().setOpenDate(startDate); if (startDate != null) { forum.getAccessDates().setHideUntilOpen((hideUntilOpen == 1) ? true : false); } forum.getAccessDates().setDueDate(endDate); forum.getAccessDates().setAllowUntilDate(allowUntilDate); /*if (endDate != null) { forum.getAccessDates().setLocked((lockEndDate == 1) ? true : false); }*/ } else { forum.getAccessDates().setOpenDate(null); forum.getAccessDates().setDueDate(null); } forum.setCategoryId(category.getId()); forum.setName(titleEle.getTextTrim()); //f.setModerated(false); forum.setType(forumType); forum.setAccessType(forumAccessType); forum.setCreatedBySakaiUserId(UserDirectoryService.getCurrentUser().getId()); if (forumGradeType == Forum.GRADE_BY_FORUM || forumGradeType == Forum.GRADE_BY_TOPIC) { forum.setGradeType(forumGradeType); } else { forum.setGradeType(Forum.GRADE_DISABLED); } // description List genElements = forumEle.selectNodes("./imsmd:lom/imsmd:general"); if (genElements != null && genElements.size() > 0) { Element generalElement = (Element) genElements.get(0); Element descElement = generalElement.element("description"); String description = descElement.selectSingleNode(".//imsmd:langstring").getText(); if (description != null) { forum.setDescription(description.trim()); } } // create grade if forum is grade by forum if (forum.getGradeType() == org.etudes.api.app.jforum.Grade.GradeType.FORUM.getType()) { // grade org.etudes.api.app.jforum.Grade grade = forum.getGrade(); grade.setContext(ToolManager.getCurrentPlacement().getContext()); try { grade.setPoints(gradePoints); } catch (NumberFormatException ne) { grade.setPoints(0f); } grade.setType(Forum.GRADE_BY_FORUM); Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext()); if (site.getToolForCommonId(SakaiSystemGlobals.getValue(ConfigKeys.GRADEBOOK_TOOL_ID)) != null) { grade.setAddToGradeBook((addToGradebook == 1) ? true : false); } else { grade.setAddToGradeBook(false); } if (minPostsRequired == 1) { grade.setMinimumPostsRequired(true); grade.setMinimumPosts(minPosts); } } try { jforumForumService.createForum(forum); } catch (JForumAccessException e) { // already verified access } if (logger.isDebugEnabled()) { logger.debug("Exiting createForum......"); } return forum; }
From source file:org.etudes.jforum.view.admin.ImportExportAction.java
/** * creates forum category/* www . j a v a 2 s . co m*/ * * @param titleEle * @throws Exception */ /*private Category createCategory(Element eleCatItem, Element titleEle) throws Exception { // create category, forums and topics if (logger.isDebugEnabled()) logger.debug("Creating category......"); create category CategoryDAO cm = DataAccessDriver.getInstance().newCategoryDAO(); Category c = new Category(); c.setName(titleEle.getText()); c.setModerated(false); // grade category int catGradeType = 0; float gradePoints = 0f; Date startDate = null, endDate = null; int lockEndDate = 0; int addToGradebook = 0; int minPosts = 0, minPostsRequired = 0; String parameters = eleCatItem.attributeValue("parameters"); if (parameters != null && parameters.trim().length() > 0) { String param[] = parameters.split("&"); for (int i = 0; i < param.length; i++) { if (param[i].startsWith("gradetype")) { try { if (param[i].indexOf('=') != -1) catGradeType = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("gradepoints")) { try { if (param[i].indexOf('=') != -1) gradePoints = Float.parseFloat(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("startdate")) { try { if (param[i].indexOf('=') != -1) { try { startDate = getDateFromString(param[i].substring(param[i].indexOf('=') + 1)); } catch (ParseException e) { } } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("enddate")) { try { if (param[i].indexOf('=') != -1) { try { endDate = getDateFromString(param[i].substring(param[i].indexOf('=') + 1)); } catch (ParseException e) { } } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("lockenddate")) { try { if (param[i].indexOf('=') != -1) lockEndDate = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("addtogradebook")) { try { if (param[i].indexOf('=') != -1) addToGradebook = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("minpostsrequired")) { try { if (param[i].indexOf('=') != -1) minPostsRequired = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("minposts")) { try { if (param[i].indexOf('=') != -1) minPosts = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } } } if (catGradeType == Forum.GRADE_BY_CATEGORY) { c.setGradeCategory(true); } c.setStartDate(startDate); c.setEndDate(endDate); if (endDate != null) { c.setLockCategory((lockEndDate == 1) ? true : false); } int categoryId = cm.addNew(c); c.setId(categoryId); // add to cache // ForumRepository.addCategory(c); ForumRepository.addCourseCategoryToCache(c); if (catGradeType == Forum.GRADE_BY_CATEGORY) { Grade grade = new Grade(); grade.setContext(ToolManager.getCurrentPlacement().getContext()); grade.setCategoryId(c.getId()); try { grade.setPoints(gradePoints); } catch (NumberFormatException ne) { grade.setPoints(0f); } grade.setType(Forum.GRADE_BY_CATEGORY); Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext()); if (site.getToolForCommonId(SakaiSystemGlobals.getValue(ConfigKeys.GRADEBOOK_TOOL_ID)) != null) { grade.setAddToGradeBook((addToGradebook == 1) ? true : false); } else { grade.setAddToGradeBook(false); } if (minPostsRequired == 1) { grade.setMinimumPostsRequired(true); grade.setMinimumPosts(minPosts); } int gradeId = DataAccessDriver.getInstance().newGradeDAO().addNew(grade); grade.setId(gradeId); // add to gradebook if (grade.isAddToGradeBook()) { String gradebookUid = ToolManager.getInstance().getCurrentPlacement().getContext(); JForumGBService jForumGBService = null; jForumGBService = (JForumGBService)ComponentManager.get("org.etudes.api.app.jforum.JForumGBService"); if (!jForumGBService.isAssignmentDefined(gradebookUid, c.getName())) { String url = null; Date gbItemEndDate = c.getEndDate(); jForumGBService.addExternalAssessment(gradebookUid, "discussions-" + String.valueOf(grade.getId()), url, c.getName(), grade.getPoints(), gbItemEndDate, I18n.getMessage("Grade.sendToGradebook.description")); } } } * associate category with groups(Facilitator, Participant) * //Facilitator GroupSecurityDAO gmodel = * DataAccessDriver.getInstance().newGroupSecurityDAO(); * PermissionControl pc = new PermissionControl(); * pc.setSecurityModel(gmodel); Role role = new Role(); * role.setName(SecurityConstants.PERM_CATEGORY); GroupDAO gm = * DataAccessDriver.getInstance().newGroupDAO(); Group facGroup = * gm.selectGroupByName("Facilitator"); int groupId = facGroup.getId(); * RoleValueCollection roleValues = new RoleValueCollection(); * * RoleValue rv = new RoleValue(); * rv.setType(PermissionControl.ROLE_ALLOW); * rv.setValue(Integer.toString(categoryId)); * * roleValues.add(rv); * * pc.addRoleValue(groupId, role, roleValues); * * //Participant Group parGroup = gm.selectGroupByName("Participant"); * int parGroupId = parGroup.getId(); RoleValueCollection parRoleValues * = new RoleValueCollection(); * * RoleValue parrv = new RoleValue(); * parrv.setType(PermissionControl.ROLE_ALLOW); * parrv.setValue(Integer.toString(categoryId)); * * parRoleValues.add(rv); * * pc.addRoleValue(parGroupId, role, parRoleValues); * * SecurityRepository.clean(); return c; }*/ private org.etudes.api.app.jforum.Category createCategory(Element eleCatItem, Element titleEle) throws Exception { // create category, forums and topics if (logger.isDebugEnabled()) { logger.debug("Creating category......"); } /* create category */ JForumCategoryService jforumCategoryService = (JForumCategoryService) ComponentManager .get("org.etudes.api.app.jforum.JForumCategoryService"); org.etudes.api.app.jforum.Category category = jforumCategoryService.newCategory(); category.setTitle(titleEle.getText()); category.setContext(ToolManager.getCurrentPlacement().getContext()); category.setCreatedBySakaiUserId(UserDirectoryService.getCurrentUser().getId()); // grade category int catGradeType = 0; float gradePoints = 0f; Date startDate = null, endDate = null, allowUntilDate = null; int hideUntilOpen = 0; //int lockEndDate = 0; int addToGradebook = 0; int minPosts = 0, minPostsRequired = 0; String parameters = eleCatItem.attributeValue("parameters"); if (parameters != null && parameters.trim().length() > 0) { String param[] = parameters.split("&"); for (int i = 0; i < param.length; i++) { if (param[i].startsWith("gradetype")) { try { if (param[i].indexOf('=') != -1) catGradeType = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("gradepoints")) { try { if (param[i].indexOf('=') != -1) gradePoints = Float.parseFloat(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("startdate")) { try { if (param[i].indexOf('=') != -1) { try { startDate = getDateFromString(param[i].substring(param[i].indexOf('=') + 1)); } catch (ParseException e) { } } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("hideuntilopen")) { try { if (param[i].indexOf('=') != -1) hideUntilOpen = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("enddate")) { try { if (param[i].indexOf('=') != -1) { try { endDate = getDateFromString(param[i].substring(param[i].indexOf('=') + 1)); } catch (ParseException e) { } } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } /*else if (param[i].startsWith("lockenddate")) { try { if (param[i].indexOf('=') != -1) lockEndDate = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } }*/ else if (param[i].startsWith("allowuntildate")) { try { if (param[i].indexOf('=') != -1) { try { allowUntilDate = getDateFromString(param[i].substring(param[i].indexOf('=') + 1)); } catch (ParseException e) { } } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("addtogradebook")) { try { if (param[i].indexOf('=') != -1) addToGradebook = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("minpostsrequired")) { try { if (param[i].indexOf('=') != -1) minPostsRequired = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } else if (param[i].startsWith("minposts")) { try { if (param[i].indexOf('=') != -1) minPosts = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } catch (NumberFormatException e) { if (logger.isErrorEnabled()) logger.error(e); } } } } if (catGradeType == Forum.GRADE_BY_CATEGORY) { category.setGradable(Boolean.TRUE); } category.getAccessDates().setOpenDate(startDate); category.getAccessDates().setDueDate(endDate); category.getAccessDates().setAllowUntilDate(allowUntilDate); /*if (endDate != null) { category.getAccessDates().setLocked((lockEndDate == 1) ? true : false); }*/ if (startDate != null) { category.getAccessDates().setHideUntilOpen((hideUntilOpen == 1) ? true : false); } if (catGradeType == Forum.GRADE_BY_CATEGORY) { org.etudes.api.app.jforum.Grade grade = category.getGrade(); grade.setContext(ToolManager.getCurrentPlacement().getContext()); try { grade.setPoints(gradePoints); } catch (NumberFormatException ne) { grade.setPoints(0f); } grade.setType(Forum.GRADE_BY_CATEGORY); Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext()); if (site.getToolForCommonId(SakaiSystemGlobals.getValue(ConfigKeys.GRADEBOOK_TOOL_ID)) != null) { grade.setAddToGradeBook((addToGradebook == 1) ? true : false); } else { grade.setAddToGradeBook(false); } if (minPostsRequired == 1) { grade.setMinimumPostsRequired(true); grade.setMinimumPosts(minPosts); } } try { jforumCategoryService.createCategory(category); } catch (JForumAccessException e) { if (logger.isErrorEnabled()) { logger.warn(e.toString(), e); } } return category; }
From source file:org.etudes.jforum.view.admin.ImportExportAction.java
/** * create topic and first post//w ww. ja v a 2 s . com * * @param topicEle * @param forum */ //private void createTopic(Element topicEle, Category category, Forum forum, Document document, String unZippedDirPath) throws Exception private void createTopic(Element topicEle, org.etudes.api.app.jforum.Category category, org.etudes.api.app.jforum.Forum forum, Document document, String unZippedDirPath) throws Exception { if (logger.isDebugEnabled()) { logger.debug("Entering createTopic......"); } List eleTopicTitles = (List) topicEle.elements("title"); if (eleTopicTitles == null || eleTopicTitles.size() == 0) { return; } Element titleEle = (Element) topicEle.elements("title").get(0); int topicGrade = 0; float gradePoints = 0f; int topicType = 0; Date startDate = null, endDate = null, allowUntilDate = null; //int lockEndDate = 0; int hideUntilOpen = 0; int addToGradebook = 0; int minPostsRequired = 0; int minPosts = 0; String parameters = topicEle.attributeValue("parameters"); if (parameters != null && parameters.trim().length() > 0) { String param[] = parameters.split("&"); for (int i = 0; i < param.length; i++) { if (param[i].startsWith("topictype")) { try { if (param[i].indexOf('=') != -1) { topicType = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) { logger.error(e, e); } } } else if (param[i].startsWith("gradetopic")) { try { if (param[i].indexOf('=') != -1) { topicGrade = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) { logger.error(e); } } } else if (param[i].startsWith("gradepoints")) { try { if (param[i].indexOf('=') != -1) { gradePoints = Float.parseFloat(param[i].substring(param[i].indexOf('=') + 1)); } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) { logger.error(e, e); } } } else if (param[i].startsWith("startdate")) { try { if (param[i].indexOf('=') != -1) { try { startDate = getDateFromString(param[i].substring(param[i].indexOf('=') + 1)); } catch (ParseException e) { } } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) { logger.error(e, e); } } } else if (param[i].startsWith("hideuntilopen")) { try { if (param[i].indexOf('=') != -1) { hideUntilOpen = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) { logger.error(e, e); } } } else if (param[i].startsWith("enddate")) { try { if (param[i].indexOf('=') != -1) { try { endDate = getDateFromString(param[i].substring(param[i].indexOf('=') + 1)); } catch (ParseException e) { } } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) { logger.error(e, e); } } } /*else if (param[i].startsWith("lockenddate")) { try { if (param[i].indexOf('=') != -1) { lockEndDate = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) { logger.error(e, e); } } }*/ else if (param[i].startsWith("allowuntildate")) { try { if (param[i].indexOf('=') != -1) { try { allowUntilDate = getDateFromString(param[i].substring(param[i].indexOf('=') + 1)); } catch (ParseException e) { } } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) { logger.error(e, e); } } } else if (param[i].startsWith("addtogradebook")) { try { if (param[i].indexOf('=') != -1) { addToGradebook = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) { logger.error(e, e); } } } else if (param[i].startsWith("minpostsrequired")) { try { if (param[i].indexOf('=') != -1) { minPostsRequired = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) { logger.error(e, e); } } } else if (param[i].startsWith("minposts")) { try { if (param[i].indexOf('=') != -1) { minPosts = Integer.parseInt(param[i].substring(param[i].indexOf('=') + 1)); } } catch (NumberFormatException e) { if (logger.isErrorEnabled()) { logger.error(e, e); } } } } } /* create new topic and it is a first post */ JForumPostService jforumPostService = (JForumPostService) ComponentManager .get("org.etudes.api.app.jforum.JForumPostService"); org.etudes.api.app.jforum.Topic t = jforumPostService.newTopic(); t.setTitle(titleEle.getText()); t.setForumId(forum.getId()); if (topicType == org.etudes.api.app.jforum.Topic.TopicType.NORMAL.getType() || topicType == org.etudes.api.app.jforum.Topic.TopicType.ANNOUNCE.getType() || topicType == org.etudes.api.app.jforum.Topic.TopicType.STICKY.getType()) { t.setType(topicType); } else { t.setType(org.etudes.api.app.jforum.Topic.TopicType.NORMAL.getType()); } t.setGradeTopic((topicGrade == 1) ? true : false); t.setExportTopic(true); if ((category.getAccessDates().getOpenDate() == null && category.getAccessDates().getDueDate() == null && category.getAccessDates().getAllowUntilDate() == null) && (forum.getAccessDates().getOpenDate() == null && forum.getAccessDates().getDueDate() == null && forum.getAccessDates().getAllowUntilDate() == null)) { t.getAccessDates().setOpenDate(startDate); if (startDate != null) { t.getAccessDates().setHideUntilOpen((hideUntilOpen == 1) ? true : false); } t.getAccessDates().setDueDate(endDate); t.getAccessDates().setAllowUntilDate(allowUntilDate); /*if (endDate != null) { t.getAccessDates().setLocked((lockEndDate == 1) ? true : false); }*/ } else { t.getAccessDates().setOpenDate(null); t.getAccessDates().setDueDate(null); } JForumUserService jforumUserService = (JForumUserService) ComponentManager .get("org.etudes.api.app.jforum.JForumUserService"); org.etudes.api.app.jforum.User postedBy = jforumUserService .getBySakaiUserId(SessionFacade.getUserSession().getSakaiUserId()); t.setPostedBy(postedBy); // TODO: topic grades // create grade if forum is grade by topic and topic is grade topic if (forum.getGradeType() == Forum.GRADE_BY_TOPIC && t.isGradeTopic()) { org.etudes.api.app.jforum.Grade grade = t.getGrade(); grade.setContext(ToolManager.getCurrentPlacement().getContext()); grade.setForumId(forum.getId()); grade.setTopicId(t.getId()); try { grade.setPoints(gradePoints); } catch (NumberFormatException ne) { grade.setPoints(0f); } grade.setType(Forum.GRADE_BY_TOPIC); Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext()); if (site.getToolForCommonId(SakaiSystemGlobals.getValue(ConfigKeys.GRADEBOOK_TOOL_ID)) != null) { if (forum.getAccessType() != Forum.ACCESS_DENY) { grade.setAddToGradeBook((addToGradebook == 1) ? true : false); } else { grade.setAddToGradeBook(false); } } else { grade.setAddToGradeBook(false); } if (minPostsRequired == 1) { grade.setMinimumPostsRequired(true); grade.setMinimumPosts(minPosts); } } // Set the Post org.etudes.api.app.jforum.Post p = jforumPostService.newPost(); p.setTime(new Date()); p.setSubject(titleEle.getText()); p.setBbCodeEnabled(false); p.setSmiliesEnabled(true); p.setSignatureEnabled(true); p.setUserIp(JForum.getRequest().getRemoteAddr()); p.setUserId(SessionFacade.getUserSession().getUserId()); p.setPostedBy(postedBy); p.setHtmlEnabled(false); // get text Attribute identifierref = topicEle.attribute("identifierref"); Element eleRes = getResource(identifierref.getValue(), document); String hrefVal = eleRes.attributeValue("href"); String message = null; try { message = readFromFile(new File(unZippedDirPath + File.separator + hrefVal)); } catch (Exception e1) { if (logger.isWarnEnabled()) { logger.warn("site : " + ToolManager.getCurrentPlacement().getContext() + " : " + e1.toString(), e1); } return; } // parse and update embedded references path and save the embedded references if not in the resource tool message = parseAndUpdateImportUrls(message, unZippedDirPath); if (p.isHtmlEnabled()) { p.setText(SafeHtml.makeSafe(message)); } else { p.setText(message); } t.getPosts().clear(); t.getPosts().add(p); try { //processAttachments(eleRes, forum, document, unZippedDirPath, postId); processAttachments(eleRes, document, unZippedDirPath, p, jforumPostService); } catch (Exception e) { if (logger.isWarnEnabled()) { logger.warn("site : " + ToolManager.getCurrentPlacement().getContext() + " : " + e.toString(), e); } } try { jforumPostService.createTopicWithAttachments(t); } catch (JForumAccessException e) { if (logger.isWarnEnabled()) { logger.warn("site : " + ToolManager.getCurrentPlacement().getContext() + " : " + e.toString(), e); } } catch (JForumAttachmentOverQuotaException e) { if (logger.isWarnEnabled()) { logger.warn("site : " + ToolManager.getCurrentPlacement().getContext() + " : " + e.toString(), e); } } catch (JForumAttachmentBadExtensionException e) { if (logger.isWarnEnabled()) { logger.warn("site : " + ToolManager.getCurrentPlacement().getContext() + " : " + e.toString(), e); } } if (logger.isDebugEnabled()) { logger.debug("Exiting createTopic......"); } }
From source file:ispyb.client.mx.results.ViewResultsAction.java
/** * To display all the parameters linked to a dataCollectionId. * //from w w w . j a v a 2 s .c om * @param mapping * @param actForm * @param request * @param in_reponse * @return */ public ActionForward display(ActionMapping mapping, ActionForm actForm, HttpServletRequest request, HttpServletResponse in_reponse) { ActionMessages errors = new ActionMessages(); boolean redirectToError = true; boolean displayOutputParam = false; try { dataCollectionIdst = request.getParameter(Constants.DATA_COLLECTION_ID); Integer dataCollectionId = null; if (dataCollectionIdst != null) { try { dataCollectionId = new Integer(dataCollectionIdst); } catch (NumberFormatException e) { } } if (dataCollectionId == null && BreadCrumbsForm.getIt(request).getSelectedDataCollection() != null) { dataCollectionId = BreadCrumbsForm.getIt(request).getSelectedDataCollection().getDataCollectionId(); } request.getSession().setAttribute(Constants.DATA_COLLECTION_ID, dataCollectionId); ViewResultsForm form = (ViewResultsForm) actForm; form.setDataCollectionId(dataCollectionId); DataCollection3VO dc = dataCollectionService.findByPk(dataCollectionId, false, true); DataCollectionGroup3VO dataCollectionGroup = null; if (dc != null) { dataCollectionGroup = dataCollectionGroupService.findByPk(dc.getDataCollectionGroupVOId(), false, true); } Screening3VO[] screeningList = null; Integer sessionId = null; if (dataCollectionGroup != null) sessionId = new Integer(dataCollectionGroup.getSessionVOId()); Session3VO sessionlv = null; if (sessionId != null) sessionlv = sessionService.findByPk(sessionId, false, false, false); form.setSession(sessionlv); if (sessionlv == null) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", "No session retrieved")); saveErrors(request, errors); return (mapping.findForward("error")); } // Confidentiality (check if object proposalId and session proposalId match) if (!Confidentiality.isAccessAllowed(request, sessionlv.getProposalVO().getProposalId())) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", "Access denied")); saveErrors(request, errors); return (mapping.findForward("error")); } if (sessionlv.getBeamLineSetupVOId() != null && sessionlv.getBeamLineSetupVOId().intValue() != 0) { Integer beamLineId = new Integer(sessionlv.getBeamLineSetupVOId()); BeamLineSetup3VO beamLinelv = beamLineSetupService.findByPk(beamLineId); form.setBeamLine(beamLinelv); form.setUndulatorTypes(beamLinelv.getUndulatorType1(), beamLinelv.getUndulatorType2(), beamLinelv.getUndulatorType3()); } String rMerge = request.getParameter(Constants.RSYMM); String iSigma = request.getParameter(Constants.ISIGMA); request.getSession().setAttribute(Constants.RSYMM, rMerge); request.getSession().setAttribute(Constants.ISIGMA, iSigma); Screening3VO[] screenings = dataCollectionGroup.getScreeningsTab(); if (screenings.length > 0) { displayOutputParam = true;// there is at least 1 screening so we display the output params int length = screenings.length; screeningList = screenings; // if many screenings, only use the last one ScreeningRank3VO srlv = new ScreeningRank3VO(); ScreeningOutput3VO sov = new ScreeningOutput3VO(); ScreeningRankSet3VO srsv = new ScreeningRankSet3VO(); ScreeningOutputLattice3VO solav = new ScreeningOutputLattice3VO(); ScreeningStrategy3VO[] screeningStrategyList; List<ScreeningStrategyValueInfo> screeningInfoList = new ArrayList<ScreeningStrategyValueInfo>(); // ScreeningValue sv = screening.findByPrimaryKey(screeningId); Screening3VO sv = screeningList[length - 1]; // sv = screeningService.loadEager(sv); ScreeningRank3VO[] screeningRanks = sv.getScreeningRanksTab(); if (screeningRanks.length > 0) { srlv = screeningRanks[0]; srsv = srlv.getScreeningRankSetVO(); } ScreeningOutput3VO[] screeningOutputs = sv.getScreeningOutputsTab(); if (screeningOutputs.length > 0) { sov = screeningOutputs[0]; // sov = screeningOutputService.loadEager(sov); } ScreeningOutputLattice3VO[] screeningOutputLattices = sov.getScreeningOutputLatticesTab(); if (screeningOutputLattices != null && screeningOutputLattices.length > 0) { solav = screeningOutputLattices[0]; form.setScreeningOutputLattice(solav); } ScreeningStrategy3VO[] screeningStrategys = sov.getScreeningStrategysTab(); if (screeningStrategys.length > 0) { screeningStrategyList = screeningStrategys; List<ScreeningStrategyWedge3VO> wedgeList = new ArrayList<ScreeningStrategyWedge3VO>(); for (int j = 0; j < screeningStrategyList.length; j++) { ScreeningStrategy3VO ss = screeningStrategyService .findByPk(screeningStrategyList[j].getScreeningStrategyId(), true); ScreeningStrategyValueInfo ssvi = new ScreeningStrategyValueInfo(ss); ssvi.setProgramLog(dc); screeningInfoList.add(ssvi); ArrayList<ScreeningStrategyWedge3VO> list = ss.getScreeningStrategyWedgesList(); if (list != null) wedgeList.addAll(list); } form.setScreeningStrategyList(screeningStrategyList); form.setListStrategiesInfo(screeningInfoList); // strategy wedge ScreeningStrategyWedge3VO[] screeningStrategyWedgeList; List<ScreeningStrategyWedgeValueInfo> screeningWedgeInfoList; int nb = wedgeList.size(); screeningStrategyWedgeList = new ScreeningStrategyWedge3VO[nb]; for (int j = 0; j < nb; j++) { screeningStrategyWedgeList[j] = wedgeList.get(j); } screeningWedgeInfoList = new ArrayList<ScreeningStrategyWedgeValueInfo>(); for (int k = 0; k < screeningStrategyWedgeList.length; k++) { ScreeningStrategyWedgeValueInfo sw = new ScreeningStrategyWedgeValueInfo( screeningStrategyWedgeService.findByPk( screeningStrategyWedgeList[k].getScreeningStrategyWedgeId(), true)); screeningWedgeInfoList.add(sw); } form.setScreeningStrategyWedgeList(screeningStrategyWedgeList); form.setListStrategiesWedgeInfo(screeningWedgeInfoList); // strategy sub wedge ScreeningStrategySubWedge3VO[][] screeningStrategySubWedgeListAll; List<ScreeningStrategySubWedgeValueInfo>[] screeningSubWedgeInfoListAll; screeningStrategySubWedgeListAll = new ScreeningStrategySubWedge3VO[screeningStrategyWedgeList.length][]; screeningSubWedgeInfoListAll = new ArrayList[screeningStrategyWedgeList.length]; for (int j = 0; j < screeningStrategyWedgeList.length; j++) { ScreeningStrategySubWedge3VO[] screeningStrategysSubWedge = screeningStrategyWedgeService .findByPk(screeningStrategyWedgeList[j].getScreeningStrategyWedgeId(), true) .getScreeningStrategySubWedgesTab(); screeningStrategySubWedgeListAll[j] = screeningStrategysSubWedge; screeningSubWedgeInfoListAll[j] = new ArrayList<ScreeningStrategySubWedgeValueInfo>(); if (screeningStrategySubWedgeListAll[j] != null) { for (int k = 0; k < screeningStrategySubWedgeListAll[j].length; k++) { ScreeningStrategySubWedgeValueInfo ssw = new ScreeningStrategySubWedgeValueInfo( screeningStrategySubWedgeService .findByPk(screeningStrategySubWedgeListAll[j][k] .getScreeningStrategySubWedgeId())); screeningSubWedgeInfoListAll[j].add(ssw); } } } form.setScreeningStrategySubWedgeListAll(screeningStrategySubWedgeListAll); form.setListStrategiesSubWedgeInfoAll(screeningSubWedgeInfoListAll); // strategy sub wedge String screeningStrategyWedgeSelIdst = request.getParameter("screeningStrategyWedgeSel"); Integer screeningStrategyWedgeSelId = -1; try { screeningStrategyWedgeSelId = new Integer(screeningStrategyWedgeSelIdst); } catch (NumberFormatException ex) { } ScreeningStrategySubWedge3VO[] screeningStrategySubWedgeList; screeningStrategySubWedgeList = new ScreeningStrategySubWedge3VO[0]; List<ScreeningStrategySubWedgeValueInfo> screeningSubWedgeInfoList; screeningSubWedgeInfoList = new ArrayList<ScreeningStrategySubWedgeValueInfo>(); if (screeningStrategyWedgeSelId != -1) { ScreeningStrategySubWedge3VO[] screeningStrategysSubWedge = new ScreeningStrategyWedgeValueInfo( screeningStrategyWedgeService .findByPk(screeningStrategyWedgeList[screeningStrategyWedgeSelId] .getScreeningStrategyWedgeId(), true)) .getScreeningStrategySubWedgesTab(); screeningStrategySubWedgeList = screeningStrategysSubWedge; for (int k = 0; k < screeningStrategySubWedgeList.length; k++) { ScreeningStrategySubWedgeValueInfo sw = new ScreeningStrategySubWedgeValueInfo( screeningStrategySubWedgeService.findByPk( screeningStrategySubWedgeList[k].getScreeningStrategySubWedgeId())); screeningSubWedgeInfoList.add(sw); } } form.setScreeningStrategySubWedgeList(screeningStrategySubWedgeList); form.setListStrategiesSubWedgeInfo(screeningSubWedgeInfoList); } // Populate form form.setScreeningRank(srlv); form.setScreeningRankSet(srsv); form.setScreeningOutput(sov); } if (dataCollectionGroup.getBlSampleVOId() != null && dataCollectionGroup.getBlSampleVOId().intValue() != 0) { BLSample3VO bslv = sampleService.findByPk(dataCollectionGroup.getBlSampleVOId(), false, false); BreadCrumbsForm.getIt(request).setSelectedSample(bslv); Crystal3VO clv = bslv.getCrystalVO(); Protein3VO plv = clv.getProteinVO(); form.setCrystal(clv); form.setProtein(plv); form.setSample(bslv); } else { BreadCrumbsForm.getIt(request).setSelectedSample(null); } // --- Get Image List LOG.debug("get image list"); List<ImageValueInfo> imageList = FileUtil.GetImageList(dataCollectionId, null, null, null, null, request); LOG.debug("get image list done"); // Snapshot Image present ? // DataCollection3VO dcValue = dataCollectionService.findByPk(dataCollectionId, false, false, false, false); List<SnapshotInfo> listSnapshots = FileUtil.GetFullSnapshotPath(dc); String expectedSnapshotPath = (listSnapshots.get(SNAPSHOT_EXPECTED_NUMBER)).getFileLocation(); form.setListSnapshots(listSnapshots); form.setExpectedSnapshotPath(expectedSnapshotPath); // --- Populate Form --- form.setDisplayOutputParam(displayOutputParam); form.setDataCollectionId(dataCollectionId); form.setDataCollection(dc); form.setListInfo(imageList); FormUtils.setFormDisplayMode(request, actForm, FormUtils.INSPECT_MODE); // Fill the BreadCrumbs BreadCrumbsForm.getIt(request).setSelectedImage(null); BreadCrumbsForm.getIt(request).setSelectedDataCollection(dc); BreadCrumbsForm.getIt(request).setSelectedDataCollectionGroup(dc.getDataCollectionGroupVO()); if (dc.getDataCollectionGroupVO().getWorkflowVO() != null) { BreadCrumbsForm.getIt(request).setSelectedWorkflow(dc.getDataCollectionGroupVO().getWorkflowVO()); } displayEDNA(mapping, actForm, request, in_reponse, errors); } catch (Exception e) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.results.view")); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString())); e.printStackTrace(); } if (!errors.isEmpty() && redirectToError) { saveErrors(request, errors); return (mapping.findForward("error")); } else { // return mapping.findForward("success"); RoleDO roleObject = (RoleDO) request.getSession().getAttribute(Constants.CURRENT_ROLE); String role = roleObject.getName(); if (role.equals(Constants.FXMANAGE_ROLE_NAME)) { return mapping.findForward("fedexmanagerResultsViewPage"); } else if (role.equals(Constants.ROLE_MANAGER)) { return mapping.findForward("managerResultsViewPage"); } else if (role.equals(Constants.ROLE_LOCALCONTACT)) { return mapping.findForward("localcontactResultsViewPage"); } else { return mapping.findForward("success"); } } }
From source file:com.bringcommunications.etherpay.Payment_Processor.java
public void handle_http_rsp(String callback, String rsp) { long now_sec = System.currentTimeMillis() / 1000; int next_idx = callback.indexOf("-"); String next_callback = (next_idx >= 0) ? callback.substring(next_idx + 1) : ""; System.out//from w w w .j a v a 2 s . c o m .println("Payment_Processor::handle_http_rsp got " + callback + " callback, now_sec = " + now_sec); // // -- deal with gas price if (callback.startsWith("gas")) { long gas_price = 0; if (rsp.contains("gasPriceHex")) { String gas_price_str = Util.json_parse(rsp, "gasPriceHex"); if (!gas_price_str.isEmpty()) { if (gas_price_str.startsWith("0x")) gas_price_str = gas_price_str.substring(2); try { gas_price = Long.parseLong(gas_price_str, 16); } catch (NumberFormatException e) { System.out.println("payment_processor: eror parsing gas price: " + gas_price_str); } if (gas_price > 0) { long max_price = 0; long min_price = Long.MAX_VALUE; for (int i = 0; i < gas_price_history.length; ++i) { gas_price_history[i] = (i < gas_price_history.length - 1) ? gas_price_history[i + 1] : gas_price; if (gas_price_history[i] > max_price) max_price = gas_price_history[i]; if (gas_price_history[i] < min_price) min_price = gas_price_history[i]; } SharedPreferences.Editor preferences_editor = preferences.edit(); preferences_editor.putLong("gas_price", min_price); //only update timestamp after we have collected several samples. that way we initially collect samples for //every payment if (max_price < Long.MAX_VALUE) preferences_editor.putLong("gas_price_refresh_sec", now_sec); preferences_editor.apply(); call_next_callback(next_callback, 0); return; } } } System.out.println("payment_processor: eror retrieving gas price"); call_next_callback(next_callback, 0); //we can continue on using the default or historical gas price //dispose_current_message(next_callback, false, "", 0, "error retrieving gas price!", true); return; } // // -- deal with nonce // { "status": 1, "data": [ { "accountNonce": "16" } ] } // if (callback.startsWith("nonce")) { //note that first payment nonce is 0; so if you've never made a payment then we have a convention that our "last-used-nonce" is -1. //lt -1 means we've never even tried to update long nonce = -2; if (rsp.contains("accountNonce")) { String nonce_str = Util.json_parse(rsp, "accountNonce"); if (!nonce_str.isEmpty()) nonce = Long.valueOf(nonce_str); } else if (rsp.contains("status")) { String status_str = Util.json_parse(rsp, "status"); if (status_str.equals("1")) { //no error, but no nonce data.... the account has never been used nonce = -1; } System.out.println("status = \"" + status_str + "\"; nonce = " + nonce); } if (nonce != -2) { update_nonce_logic(nonce, next_callback, false); return; } System.out.println("payment_processor: eror retrieving nonce"); dispose_current_message(next_callback, false, "", 0, "error retrieving nonce!", true); return; } // // -- deal with transactions (to extract nonce) // { "status": 1, "data": [ // { "hash": "0x1b3dca103e0605b45f81eede754401df4082b87c4faf3f1205755b36f1b34ddf", // "sender": "0x8b8a571730b631f58e7965d78582eae1b0417ab6", // "recipient": "0x85d9147b0ec6d60390c8897244d039fb55b087c6", // "accountNonce": "76", // "price": 25000000000, "gasLimit": 35000, "amount": 2000000108199936, "block_id": 2721132, // "time": "2016-11-30T09:58:07.000Z", "newContract": 0, "isContractTx": null, // "blockHash": "0x5c1118c94176902cab1783f8d4f8d17544c7a16c8ef377f674fa89693eb3ab0c", // "parentHash": "0x1b3dca103e0605b45f81eede754401df4082b87c4faf3f1205755b36f1b34ddf", // "txIndex": null, "gasUsed": 21000, "type": "tx" // }, // ..... // } if (callback.startsWith("transactions")) { String status_str = ""; if (rsp.contains("status")) { status_str = Util.json_parse(rsp, "status"); int idx = rsp.indexOf("status") + "status".length(); rsp = rsp.substring(idx); } if (!status_str.equals("1")) { System.out.println("payment_processor: error retrieving transactions: " + rsp); dispose_current_message(next_callback, false, "", 0, "error retrieving transactions!", true); return; } long best_nonce = -1; long gas_price = -1; String acct_addr = preferences.getString("acct_addr", ""); for (int i = 0, idx = 0; i < 100; ++i) { if (rsp.contains("{")) { idx = rsp.indexOf('{') + 1; rsp = rsp.substring(idx); } else { break; } if (rsp.contains("sender")) { String sender = Util.json_parse(rsp, "sender"); if (!sender.equals(acct_addr)) continue; } //while we're here, we can update gas price if (gas_price < 0 && rsp.contains("price")) { String price_str = Util.json_parse(rsp, "price"); if (!price_str.isEmpty()) { gas_price = Long.valueOf(price_str); long max_price = 0; long min_price = Long.MAX_VALUE; for (int pi = 0; pi < gas_price_history.length; ++pi) { gas_price_history[pi] = (pi < gas_price_history.length - 1) ? gas_price_history[pi + 1] : gas_price; if (gas_price_history[pi] > max_price) max_price = gas_price_history[pi]; if (gas_price_history[pi] < min_price) min_price = gas_price_history[pi]; } System.out.println( "read new gas price, " + gas_price + "; saving min gas price = " + min_price); SharedPreferences.Editor preferences_editor = preferences.edit(); preferences_editor.putLong("gas_price", min_price); //only update timestamp after we have collected several samples. that way we initially collect samples for //every payment if (max_price < Long.MAX_VALUE) preferences_editor.putLong("gas_price_refresh_sec", now_sec); preferences_editor.apply(); } } if (rsp.contains("accountNonce")) { String nonce_str = Util.json_parse(rsp, "accountNonce"); if (!nonce_str.isEmpty()) { long nonce = Long.valueOf(nonce_str); if (nonce > best_nonce) best_nonce = nonce; } } if (rsp.contains("}")) { idx = rsp.indexOf('}') + 1; rsp = rsp.substring(idx); } else { break; } } //have best nonce... see if it beats out current verified nonce update_nonce_logic(best_nonce, next_callback, true); return; } // // -- deal with broadcast // { "jsonrpc": "2.0", "result": "0xd22456131597cff2297d1034f9e6f790e9678d85c041591949ab5a8de5f73f04", "id": 1 } // alternately: // { "jsonrpc":"2.0","error": {"code":-32010, "message": "Transaction nonce is too low. Try incrementing the nonce.","data": null},"id":1 } // if (callback.startsWith("broadcast")) { String txid = ""; if (rsp.contains("result")) { txid = Util.json_parse(rsp, "result"); if (BuildConfig.DEBUG) System.out.println("txid: " + txid); if (!txid.isEmpty()) { long balance = preferences.getLong("balance", 0); long gas_price = preferences.getLong("gas_price", Util.DEFAULT_GAS_PRICE); long est_cost = current_send_message.size_wei + (current_send_message.gas_limit * gas_price); SharedPreferences.Editor preferences_editor = preferences.edit(); preferences_editor.putLong("last_tx_nonce", current_send_message.nonce); preferences_editor.putLong("last_pay_sec", now_sec); long oldest_unverified_tx = preferences.getLong("oldest_unverified_tx", 0); long verified_nonce_changed_sec = preferences.getLong("verified_nonce_changed_sec", 0); //oldest-verified-tx isn't really the oldest-*verified*-tx; it's actually the oldest tx since the verified nonce last changed. //it's useful to indicate how long the nonce has been stuck. if (oldest_unverified_tx < verified_nonce_changed_sec) preferences_editor.putLong("oldest_unverified_tx", now_sec); balance -= est_cost; preferences_editor.putLong("balance", balance); preferences_editor.putBoolean("refresh_mode", true); preferences_editor.apply(); dispose_current_message(next_callback, true, txid, balance, "", false); return; } } if (rsp.contains("error")) { String err_msg = Util.json_parse(rsp, "message"); System.out.println(rsp + "; msg: " + err_msg); if (err_msg.contains("nonce is too low")) { SharedPreferences.Editor preferences_editor = preferences.edit(); //during developement i managed to set the last_tx_nonce incorrectly. that should be a condition that we should be able to recover //from.... so here if we get a nonce-too-low message, and the verified nonce is gt. our last-tx-nonce, then just inc. the verified //nonce. this corrects the case in which the nonce api reurns an incorrect nonce (cuz of rapid-fire tx's) -- you can't correct that //unless you get the nonce from transactions -- and we won't do that unless the last-tx-nonce is gt. the verified nonce. //if the verified nonce is not eq. to last nonce, then just reset to initial value. long last_tx_nonce = preferences.getLong("last_tx_nonce", -1); long verified_nonce = preferences.getLong("verified_nonce", -2); verified_nonce = (last_tx_nonce == verified_nonce) ? last_tx_nonce + 1 : -2; preferences_editor.putLong("verified_nonce", verified_nonce); preferences_editor.putLong("verified_nonce_changed_sec", now_sec); preferences_editor.apply(); System.out.println("force check nonce..."); call_next_callback(next_callback, 0); return; } } System.out.println("payment_processor: eror broadcasting transaction: " + rsp); dispose_current_message(next_callback, false, "", 0, "error broadcasting transaction!", true); return; } // // -- deal with balance // { "status": 1, "data": [ // { "address": "0x7223efbf783eba259451a89e8e84c26611df8c4f", "balance": 40038159108626850000, "nonce": null, "code": "0x", "name": null, "storage": null, "firstSeen": null } // ] } // if (callback.startsWith("balance")) { long new_balance = -1; boolean got_balance = false; String balance_str = Util.json_parse(rsp, "balance"); if (BuildConfig.DEBUG) System.out.println("balance: " + balance_str); if (!balance_str.isEmpty() && !balance_str.equals("null")) { new_balance = Long.valueOf(balance_str); } else if (rsp.contains("status")) { String status_str = Util.json_parse(rsp, "status"); if (status_str.equals("1")) { //no error, but no balance data.... the account has never been used new_balance = 0; } } if (new_balance >= 0) { long verified_balance = preferences.getLong("verified_balance", 0); long verified_balance_changed_sec = preferences.getLong("verified_balance_changed_sec", 0); SharedPreferences.Editor preferences_editor = preferences.edit(); if (verified_balance != new_balance) { System.out.println("changing verified_balance from " + verified_balance + " to " + new_balance); verified_balance = new_balance; verified_balance_changed_sec = now_sec; preferences_editor.putLong("verified_balance", verified_balance); preferences_editor.putLong("verified_balance_changed_sec", verified_balance_changed_sec); preferences_editor.apply(); } long balance = preferences.getLong("balance", 0); long last_tx_nonce = preferences.getLong("last_tx_nonce", -1); long verified_nonce = preferences.getLong("verified_nonce", -2); long balance_diff = Math.abs(verified_balance - balance); long balance_refresh_sec = preferences.getLong("balance_refresh_sec", 0); if (last_tx_nonce == verified_nonce && verified_balance > balance) { System.out.println( "last_tx_nonce = verified_nonce = " + verified_nonce + ", and balance has gone up"); System.out.println("adopting verified_balance"); preferences_editor.putLong("balance", verified_balance); preferences_editor.apply(); balance = verified_balance; } else if (now_sec - verified_balance_changed_sec > BALANCE_FORCED_ADOPTION_SEC || balance_diff <= BALANCE_ESTIMATE_SLOP && now_sec - balance_refresh_sec < BALANCE_FORCED_ADOPTION_SEC / 2) { if (balance_diff > BALANCE_ESTIMATE_SLOP) { //balance has not changed in a long time... and it still is not equal to our estimated balance... apparently someone //has deposited funds, or otherwise used this acct external to our program; so we just adopt the verified balance. System.out.println("hey! estimated balance = " + balance + ", but verified_balance = " + verified_balance + "; hasn't changed in " + (now_sec - verified_balance_changed_sec) + " sec"); System.out.println("adopting verified_balance"); } preferences_editor.putLong("balance", verified_balance); preferences_editor.apply(); balance = verified_balance; } preferences_editor.putLong("balance_refresh_sec", now_sec); preferences_editor.apply(); if (balance == verified_balance) { call_next_callback(next_callback, 0); } else { System.out.println("check balance again in 5 sec"); call_next_callback(next_callback, 5); } return; } System.out.println("payment_processor: eror retrieving balance: " + rsp); dispose_current_message(next_callback, false, "", 0, "error retrieving balance!", true); return; } // // -- deal with price // { // "difficulty": { "number": 2953280, "coinbase": "0xea674fdde714fd979de3edf0f56aa9716b898ec8", "time": "2017-01-07T17:25:54.000Z", // "difficulty": 92850780236842, "gasUsed": 538482, "uncle_count": 0, "blockTime": 21, "name": "ethermine", "gasLimit": 4015639 }, // "txCount": { "count": 1673 }, // "blockCount": { "number": 2953280, "coinbase": "0xea674fdde714fd979de3edf0f56aa9716b898ec8", "time": "2017-01-07T17:25:54.000Z", "difficulty": 92850780236842, // "gasUsed": 538482, "uncle_count": 0, "blockTime": 21, "name": "ethermine", "gasLimit": 4015639 }, // "blocks": [ // { "number": 2953280, "coinbase": "0xea674fdde714fd979de3edf0f56aa9716b898ec8", "time": "2017-01-07T17:25:54.000Z", "difficulty": 92850780236842, // "gasUsed": 538482, "uncle_count": 0, "blockTime": 21, "name": "ethermine", "gasLimit": 4015639 }, // .... // ] // "txs": [ // { "hash": "0x30c10a0a80907c7117826e4b0b3a3c175a86a2b4cc39bb1df0d242b8999185bb", "parentHash": "0x30c10a0a80907c7117826e4b0b3a3c175a86a2b4cc39bb1df0d242b8999185bb", // "block_id": 2953280, "sender": "0x563133f772e3ee25708153b629efce0f13610862", "senderName": null, "recipient": "0x209c4784ab1e8183cf58ca33cb740efbf3fc18ef", // "recipientName": null, "amount": 1089969320000000000, "time": "2017-01-07T17:25:54.000Z" }, // .... // ] // "price": { "usd": 9.71, "btc": 0.01291 }, // "stats": { "blockTime": 14.0749, "difficulty": 71472687483186.2, "hashRate": 5270984772944.684, "uncle_rate": 0.0686 } // } // if (callback.startsWith("price")) { float usd_price = -1; if (rsp.contains("price")) { int price_field_idx = rsp.indexOf("price") + "price".length(); rsp = rsp.substring(price_field_idx); String price_str = Util.json_parse(rsp, "usd"); if (BuildConfig.DEBUG) System.out.println("price: " + price_str); if (!price_str.isEmpty() && !price_str.equals("null")) { try { usd_price = Float.valueOf(price_str); } catch (NumberFormatException e) { System.out.println(e.toString()); } } } if (usd_price >= 0) { SharedPreferences.Editor preferences_editor = preferences.edit(); preferences_editor.putFloat("usd_price", usd_price); preferences_editor.putLong("price_refresh_sec", now_sec); preferences_editor.apply(); refresh_balance_guts(); return; } System.out.println("payment_processor: eror retrieving price: " + rsp); dispose_current_message(next_callback, false, "", 0, "error retrieving price!", true); return; } // // -- huh? what is this? // System.out .println("Payment_Processor::handle_http_rsp: Hey! should never get here. callback = " + callback); }
From source file:ispyb.client.common.shipping.CreateShippingFileAction.java
/** * uploadCsvFile// w w w . j a va 2 s .c o m * * @param mapping * @param actForm * @param request * @param in_reponse * @return */ @SuppressWarnings({ "deprecation", "unchecked" }) public ActionForward uploadCsvFile(ActionMapping mapping, ActionForm actForm, HttpServletRequest request, HttpServletResponse in_reponse) { ActionMessages errors = new ActionMessages(); ActionMessages messages = new ActionMessages(); try { CreateShippingFileForm form = (CreateShippingFileForm) actForm; // Parameters submitted by form String currentProposalCode = (String) request.getSession().getAttribute(Constants.PROPOSAL_CODE); String currentProposalNumber = (String) request.getSession().getAttribute(Constants.PROPOSAL_NUMBER); Integer proposalId = (Integer) request.getSession().getAttribute(Constants.PROPOSAL_ID); boolean errorFile = false; Proposal3VO proposalVO = proposalService.findByPk(proposalId); List<LabContact3VO> listLabContacts = labContactService.findFiltered(proposalId, null); LabContact3VO shippingLabContactVO = null; if (listLabContacts != null && listLabContacts.size() > 0) { shippingLabContactVO = listLabContacts.get(0); } else { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.upload", "No labConctact found")); errorFile = true; } List<String> allowedSpaceGroups = (List<String>) request.getSession() .getAttribute(Constants.ISPYB_ALLOWED_SPACEGROUPS_LIST); String fieldSeparator = form.getFieldSeparator(); String textSeparator = form.getTextSeparator(); char fieldSep = fieldSeparator.charAt(0); char textSep = ' '; if (textSeparator.length() > 0) textSep = textSeparator.charAt(0); String uploadedFileName; String realCSVPath; List<Shipping3VO> listShippingCreated = new ArrayList<Shipping3VO>(); List<Dewar3VO> listDewarCreated = new ArrayList<Dewar3VO>(); List<Container3VO> listContainerCreated = new ArrayList<Container3VO>(); // List<Crystal3VO> listCrystalCreated = new ArrayList<Crystal3VO>(); List<Crystal3VO> listCrystalCreated = crystalService.findByProposalId(proposalId); List<DiffractionPlan3VO> listDifPlanCreated = new ArrayList<DiffractionPlan3VO>(); List<BLSample3VO> listSampleCreated = new ArrayList<BLSample3VO>(); if (request != null) { uploadedFileName = form.getRequestFile().getFileName(); if (uploadedFileName.equals("")) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.empty")); errorFile = true; } else if (!uploadedFileName.endsWith(".csv")) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.format")); errorFile = true; } if (!errorFile) { realCSVPath = request.getRealPath("/") + "/tmp/" + uploadedFileName; // Write the received file to tmp directory FormFile f = form.getRequestFile(); InputStream in = f.getInputStream(); File outputFile = new File(realCSVPath); if (outputFile.exists()) outputFile.delete(); FileOutputStream out = new FileOutputStream(outputFile); while (in.available() != 0) { out.write(in.read()); out.flush(); } out.flush(); out.close(); // received file Reader inFile = new FileReader(realCSVPath); LOG.info(" ---[uploadFile] Upload Shipment csv "); CSVStrategy csvStrategy = new CSVStrategy(fieldSep, textSep, CSVStrategy.COMMENTS_DISABLED); CSVParser parser = new CSVParser(inFile, csvStrategy); String[][] values = parser.getAllValues(); int nbRows = values.length; boolean isError = false; for (int i = 0; i < nbRows; i++) { int nbCol = values[i].length; if (nbCol != NB_COL) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "The number of columns is incorrect (" + nbCol + " instead of " + NB_COL + ")")); isError = true; break; } int j = 0; // proposalCode & proposalNumber String proposalCode = values[i][j++]; String proposalNumber = values[i][j++]; if (proposalCode == null || proposalNumber == null || !(proposalCode.equalsIgnoreCase(currentProposalCode)) || !(proposalNumber.equals(currentProposalNumber))) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "The proposal is incorrect line " + (i + 1))); isError = true; break; } // visitNumber j++; // shippingName String shippingName = values[i][j++]; if (shippingName == null || shippingName.trim().length() == 0 || shippingName.length() > MAX_SHIPPING_NAME) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "The shipping name is incorrect line " + (i + 1) + " (required and < " + MAX_SHIPPING_NAME + " characters)")); isError = true; break; } // dewarCode String dewarCode = values[i][j++]; if (dewarCode == null || dewarCode.trim().length() == 0 || dewarCode.length() > MAX_DEWAR_CODE) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "The dewar code is incorrect line " + (i + 1) + " (required and < " + MAX_DEWAR_CODE + " characters)")); isError = true; break; } // containerCode String containerCode = values[i][j++]; if (containerCode == null || containerCode.trim().length() == 0 || containerCode.length() > MAX_CONTAINER_CODE) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "The container code is incorrect line " + (i + 1) + " (required and < " + MAX_CONTAINER_CODE + " characters)")); isError = true; break; } // preObsResolution String preObsResolutionS = values[i][j++]; Double preObsResolution = null; if (preObsResolutionS == null || preObsResolutionS.trim().length() != 0) { try { preObsResolution = Double.parseDouble(preObsResolutionS); } catch (NumberFormatException e) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "Wrong fromat for preObsResolution line " + (i + 1))); isError = true; break; } } // neededResolution String neededResolutionS = values[i][j++]; Double neededResolution = null; if (neededResolutionS == null || neededResolutionS.trim().length() != 0) { try { neededResolution = Double.parseDouble(neededResolutionS); } catch (NumberFormatException e) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "Wrong fromat for neededResolution line " + (i + 1))); isError = true; break; } } // oscillationRange String oscillationRangeS = values[i][j++]; Double oscillationRange = null; if (oscillationRangeS == null || oscillationRangeS.trim().length() != 0) { try { oscillationRange = Double.parseDouble(oscillationRangeS); } catch (NumberFormatException e) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "Wrong fromat for oscillationRange line " + (i + 1))); isError = true; break; } } // proteinAcronym String proteinAcronym = values[i][j++]; Protein3VO protein = null; if (proteinAcronym == null || proteinAcronym.trim().length() == 0) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "The protein Acronym is required line " + (i + 1))); isError = true; break; } List<Protein3VO> proteinTab = proteinService.findByAcronymAndProposalId(proposalId, proteinAcronym); if (proteinTab == null || proteinTab.size() == 0) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "error.user.shipping.upload.file.data", "Protein " + proteinAcronym + " can not be found in ISPyB, line " + (i + 1))); isError = true; break; } else { protein = proteinTab.get(0); } // proteinName String proteinName = values[i][j++]; if (proteinName == null || proteinName.trim().length() == 0 || !protein.getName().equalsIgnoreCase(proteinName)) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "error.user.shipping.upload.file.data", "The protein name is incorrect line " + (i + 1) + " (required and must correspond to the proteinAcronym). The expected proteinName is " + protein.getName())); isError = true; break; } // spaceGroup String spaceGroup = values[i][j++]; if (spaceGroup != null && !spaceGroup.equals("") && !allowedSpaceGroups.contains(spaceGroup.toUpperCase())) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "The space group can not be found in ISPyB line " + (i + 1))); isError = true; break; } // sampleBarcode String sampleBarcode = values[i][j++]; if (sampleBarcode != null && sampleBarcode.length() > MAX_SAMPLE_BARCODE) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "The sample barcode is incorrect line " + (i + 1) + " (< " + MAX_SAMPLE_BARCODE + " characters)")); isError = true; break; } // sampleName String sampleName = values[i][j++]; if (sampleName == null || sampleName.trim().length() == 0 || sampleName.length() > MAX_SAMPLE_NAME || !sampleName .matches(Constants.MASK_BASIC_CHARACTERS_WITH_DASH_UNDERSCORE_NO_SPACE)) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "error.user.shipping.upload.file.data", "The sample name is incorrect line " + (i + 1) + " (required and < " + MAX_SAMPLE_NAME + " characters, unique name for the protein acronym, must contain only a-z, A-Z or 0-9 or - or _ characters.)")); isError = true; break; } // samplePosition String samplePos = values[i][j++]; int samplePosition = 0; try { samplePosition = Integer.parseInt(samplePos); } catch (NumberFormatException e) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "The sample position is incorrect: " + samplePos + ", line " + (i + 1) + " (required number between 1 and 10)")); isError = true; break; } if (samplePosition < 1 || samplePosition > Constants.BASKET_SAMPLE_CAPACITY) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "The sample position is incorrect: " + samplePos + ", line " + (i + 1) + " (required number between 1 and 10)")); isError = true; break; } // sample comments String sampleComments = values[i][j++]; if (sampleComments != null && sampleComments.length() > MAX_SAMPLE_COMMENTS) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "The sample comments is incorrect line " + (i + 1) + " ( < " + MAX_SAMPLE_COMMENTS + " characters)")); isError = true; break; } // cell_a String cellA = values[i][j++]; Double cell_a = null; if (cellA == null || cellA.trim().length() != 0) { try { cell_a = Double.parseDouble(cellA); } catch (NumberFormatException e) { isError = true; errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "Wrong fromat for cell_a line " + (i + 1))); break; } } // cell_b String cellB = values[i][j++]; Double cell_b = null; if (cellB == null || cellB.trim().length() != 0) { try { cell_b = Double.parseDouble(cellB); } catch (NumberFormatException e) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "Wrong fromat for cell_b line " + (i + 1))); isError = true; break; } } // cell_c String cellC = values[i][j++]; Double cell_c = null; if (cellC == null || cellC.trim().length() != 0) { try { cell_c = Double.parseDouble(cellC); } catch (NumberFormatException e) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "Wrong fromat for cell_c line " + (i + 1))); isError = true; break; } } // cell_alpha String cellAlpha = values[i][j++]; Double cell_alpha = null; if (cellAlpha == null || cellAlpha.trim().length() != 0) { try { cell_alpha = Double.parseDouble(cellAlpha); } catch (NumberFormatException e) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "Wrong fromat for cell_alpha line " + (i + 1))); isError = true; break; } } // cell_beta String cellBeta = values[i][j++]; Double cell_beta = null; if (cellBeta == null || cellBeta.trim().length() != 0) { try { cell_beta = Double.parseDouble(cellBeta); } catch (NumberFormatException e) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "Wrong fromat for cell_beta line " + (i + 1))); isError = true; break; } } // cell_gamma String cellGamma = values[i][j++]; Double cell_gamma = null; if (cellGamma == null || cellGamma.trim().length() != 0) { try { cell_gamma = Double.parseDouble(cellGamma); } catch (NumberFormatException e) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "Wrong fromat for cell_gamma line " + (i + 1))); isError = true; break; } } // creation of the objects // Shipping Shipping3VO shippingVO = new Shipping3VO(); shippingVO.setProposalVO(proposalVO); shippingVO.setShippingName(shippingName); shippingVO.setCreationDate(new Date()); shippingVO.setShippingStatus(Constants.SHIPPING_STATUS_OPENED); shippingVO.setTimeStamp(StringUtils.getCurrentTimeStamp()); shippingVO.setShippingType(Constants.DEWAR_TRACKING_SHIPPING_TYPE); shippingVO.setSendingLabContactVO(shippingLabContactVO); shippingVO.setReturnLabContactVO(shippingLabContactVO); Shipping3VO shipment = getShipment(listShippingCreated, shippingVO); if (shipment == null) { shippingVO = shippingService.create(shippingVO); listShippingCreated.add(shippingVO); } else { shippingVO = shipment; } // Dewar Dewar3VO dewarVO = new Dewar3VO(); dewarVO.setShippingVO(shippingVO); dewarVO.setCode(dewarCode); dewarVO.setType(Constants.PARCEL_DEWAR_TYPE); dewarVO.setDewarStatus(Constants.SHIPPING_STATUS_OPENED); dewarVO.setTimeStamp(StringUtils.getCurrentTimeStamp()); dewarVO.setCustomsValue(shippingLabContactVO.getDewarAvgCustomsValue()); dewarVO.setTransportValue(shippingLabContactVO.getDewarAvgTransportValue()); Dewar3VO dewar = getDewar(listDewarCreated, dewarVO); if (dewar == null) { dewarVO = dewarService.create(dewarVO); listDewarCreated.add(dewarVO); } else { dewarVO = dewar; } // Container Container3VO containerVO = new Container3VO(); containerVO.setContainerType("Puck"); containerVO.setCode(containerCode); containerVO.setCapacity(Constants.BASKET_SAMPLE_CAPACITY); containerVO.setTimeStamp(StringUtils.getCurrentTimeStamp()); containerVO.setDewarVO(dewarVO); Container3VO container = getContainer(listContainerCreated, containerVO); if (container == null) { containerVO = containerService.create(containerVO); listContainerCreated.add(containerVO); } else { containerVO = container; } if (isLocationOccInContainer(samplePosition, listSampleCreated, containerVO)) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "error.user.shipping.upload.file.data", "The sample position is incorrect: " + samplePos + ", line " + (i + 1))); isError = true; break; } // DiffractionPlan DiffractionPlan3VO difPlan = new DiffractionPlan3VO(); difPlan.setObservedResolution(preObsResolution); difPlan.setRequiredResolution(neededResolution); difPlan.setExposureTime((double) 0); difPlan.setOscillationRange(oscillationRange); difPlan.setExperimentKind(DEFAULT_EXPERIMENT_TYPE); difPlan = difPlanService.create(difPlan); listDifPlanCreated.add(difPlan); // Crystal Crystal3VO crystalVO = new Crystal3VO(); String crystalID = UUID.randomUUID().toString(); crystalVO.setProteinVO(protein); crystalVO.setCrystalUUID(crystalID); crystalVO.setSpaceGroup(spaceGroup); crystalVO.setName(crystalID); crystalVO.setCellA(cell_a); crystalVO.setCellB(cell_b); crystalVO.setCellC(cell_c); crystalVO.setCellAlpha(cell_alpha); crystalVO.setCellBeta(cell_beta); crystalVO.setCellGamma(cell_gamma); crystalVO.setDiffractionPlanVO(difPlan); if ((crystalVO.getSpaceGroup() == null) || (crystalVO.getSpaceGroup().equals(""))) { crystalVO.setSpaceGroup(DEFAULT_SPACE_GROUP); } Crystal3VO crystal = getCrystal(listCrystalCreated, crystalVO); if (crystal == null) { crystalVO = crystalService.create(crystalVO); listCrystalCreated.add(crystalVO); } else { crystalVO = crystal; } if (!crystalVO.hasCellInfo()) { messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", "Warning: the unit cell parameters are not filled for the spaceGroup " + crystalVO.getSpaceGroup() + "!")); } // BLSample BLSample3VO sample = new BLSample3VO(); sample.setCrystalVO(crystalVO); sample.setDiffractionPlanVO(difPlan); sample.setName(sampleName); sample.setCode(sampleBarcode); sample.setLocation("" + samplePosition); sample.setHolderLength(DEFAULT_HOLDER_LENGTH); sample.setLoopLength(DEFAULT_LOOP_LENGTH); sample.setLoopType(DEFAULT_LOOP_TYPE); sample.setWireWidth(DEFAULT_WIRE_WIDTH); sample.setComments(sampleComments); sample.setContainerVO(containerVO); if (isSampleNameAlreadyExist(sampleName, protein, listSampleCreated)) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.shipping.upload.file.data", "The sample name already exists: " + sampleName + ", line " + (i + 1))); isError = true; break; } sample = sampleService.create(sample); listSampleCreated.add(sample); } if (isError) { // remove created in db for (Iterator<Shipping3VO> ship = listShippingCreated.iterator(); ship.hasNext();) { Shipping3VO shipVO = ship.next(); shippingService.delete(shipVO); } } else { messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.upload.shipping")); } } } } catch (Exception e) { errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString())); LOG.error(e.toString()); saveErrors(request, errors); return mapping.findForward("error"); } if (!messages.isEmpty()) saveMessages(request, messages); if (!errors.isEmpty()) saveErrors(request, errors); return display(mapping, actForm, request, in_reponse); }
From source file:at.gv.egiz.pdfas.lib.impl.signing.pdfbox.PADESPDFBOXSigner.java
public void signPDF(PDFObject genericPdfObject, RequestedSignature requestedSignature, PDFASSignatureInterface genericSigner) throws PdfAsException { String fisTmpFile = null;/*from ww w . ja va 2 s. c o m*/ PDFAsVisualSignatureProperties properties = null; if (!(genericPdfObject instanceof PDFBOXObject)) { // tODO: throw new PdfAsException(); } PDFBOXObject pdfObject = (PDFBOXObject) genericPdfObject; if (!(genericSigner instanceof PDFASPDFBOXSignatureInterface)) { // tODO: throw new PdfAsException(); } PDFASPDFBOXSignatureInterface signer = (PDFASPDFBOXSignatureInterface) genericSigner; TempFileHelper helper = pdfObject.getStatus().getTempFileHelper(); PDDocument doc = pdfObject.getDocument(); SignatureOptions options = new SignatureOptions(); COSDocument visualSignatureDocumentGuard = null; try { fisTmpFile = helper.getStaticFilename(); FileOutputStream tmpOutputStream = null; try { // write to temporary file tmpOutputStream = new FileOutputStream(new File(fisTmpFile)); InputStream tmpis = null; try { tmpis = pdfObject.getOriginalDocument().getInputStream(); IOUtils.copy(tmpis, tmpOutputStream); tmpis.close(); } finally { IOUtils.closeQuietly(tmpis); } SignaturePlaceholderData signaturePlaceholderData = PlaceholderFilter .checkPlaceholderSignature(pdfObject.getStatus(), pdfObject.getStatus().getSettings()); TablePos tablePos = null; if (signaturePlaceholderData != null) { // Placeholder found! logger.info("Placeholder data found."); if (signaturePlaceholderData.getProfile() != null) { logger.debug("Placeholder Profile set to: " + signaturePlaceholderData.getProfile()); requestedSignature.setSignatureProfileID(signaturePlaceholderData.getProfile()); } tablePos = signaturePlaceholderData.getTablePos(); if (tablePos != null) { SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus() .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID()); float minWidth = signatureProfileConfiguration.getMinWidth(); if (minWidth > 0) { if (tablePos.getWidth() < minWidth) { tablePos.width = minWidth; logger.debug("Correcting placeholder with to minimum width {}", minWidth); } } logger.debug("Placeholder Position set to: " + tablePos.toString()); } } PDSignature signature = new PDSignature(); signature.setFilter(COSName.getPDFName(signer.getPDFFilter())); // default // filter signature.setSubFilter(COSName.getPDFName(signer.getPDFSubFilter())); SignatureProfileSettings signatureProfileSettings = TableFactory.createProfile( requestedSignature.getSignatureProfileID(), pdfObject.getStatus().getSettings()); ValueResolver resolver = new ValueResolver(requestedSignature, pdfObject.getStatus()); String signerName = resolver.resolve("SIG_SUBJECT", signatureProfileSettings.getValue("SIG_SUBJECT"), signatureProfileSettings); signature.setName(signerName); // take signing time from provided signer... signature.setSignDate(signer.getSigningDate()); // ...and update operation status in order to use exactly this date for the complete signing process requestedSignature.getStatus().setSigningDate(signer.getSigningDate()); String signerReason = signatureProfileSettings.getSigningReason(); if (signerReason == null) { signerReason = "PAdES Signature"; } signature.setReason(signerReason); logger.debug("Signing reason: " + signerReason); logger.debug("Signing @ " + signer.getSigningDate().getTime().toString()); // the signing date, needed for valid signature // signature.setSignDate(signer.getSigningDate()); signer.setPDSignature(signature); int signatureSize = 0x1000; try { String reservedSignatureSizeString = signatureProfileSettings.getValue(SIG_RESERVED_SIZE); if (reservedSignatureSizeString != null) { signatureSize = Integer.parseInt(reservedSignatureSizeString); } logger.debug("Reserving {} bytes for signature", signatureSize); } catch (NumberFormatException e) { logger.warn("Invalid configuration value: {} should be a number using 0x1000", SIG_RESERVED_SIZE); } options.setPreferedSignatureSize(signatureSize); // Is visible Signature if (requestedSignature.isVisual()) { logger.debug("Creating visual signature block"); SignatureProfileConfiguration signatureProfileConfiguration = pdfObject.getStatus() .getSignatureProfileConfiguration(requestedSignature.getSignatureProfileID()); if (tablePos == null) { // ================================================================ // PositioningStage (visual) -> find position or use // fixed // position String posString = pdfObject.getStatus().getSignParamter().getSignaturePosition(); TablePos signaturePos = null; String signaturePosString = signatureProfileConfiguration.getDefaultPositioning(); if (signaturePosString != null) { logger.debug("using signature Positioning: " + signaturePos); signaturePos = new TablePos(signaturePosString); } logger.debug("using Positioning: " + posString); if (posString != null) { // Merge Signature Position tablePos = new TablePos(posString, signaturePos); } else { // Fallback to signature Position! tablePos = signaturePos; } if (tablePos == null) { // Last Fallback default position tablePos = new TablePos(); } } boolean legacy32Position = signatureProfileConfiguration.getLegacy32Positioning(); boolean legacy40Position = signatureProfileConfiguration.getLegacy40Positioning(); // create Table describtion Table main = TableFactory.createSigTable(signatureProfileSettings, MAIN, pdfObject.getStatus(), requestedSignature); IPDFStamper stamper = StamperFactory.createDefaultStamper(pdfObject.getStatus().getSettings()); IPDFVisualObject visualObject = stamper.createVisualPDFObject(pdfObject, main); /* * PDDocument originalDocument = PDDocument .load(new * ByteArrayInputStream(pdfObject.getStatus() * .getPdfObject().getOriginalDocument())); */ PositioningInstruction positioningInstruction = Positioning.determineTablePositioning(tablePos, "", doc, visualObject, legacy32Position, legacy40Position); logger.debug("Positioning: {}", positioningInstruction.toString()); if (positioningInstruction.isMakeNewPage()) { int last = doc.getNumberOfPages() - 1; PDDocumentCatalog root = doc.getDocumentCatalog(); PDPageNode rootPages = root.getPages(); List<PDPage> kids = new ArrayList<PDPage>(); rootPages.getAllKids(kids); PDPage lastPage = kids.get(last); rootPages.getCOSObject().setNeedToBeUpdate(true); PDPage p = new PDPage(lastPage.findMediaBox()); p.setResources(new PDResources()); p.setRotation(lastPage.findRotation()); doc.addPage(p); } // handle rotated page PDDocumentCatalog documentCatalog = doc.getDocumentCatalog(); PDPageNode documentPages = documentCatalog.getPages(); List<PDPage> documentPagesKids = new ArrayList<PDPage>(); documentPages.getAllKids(documentPagesKids); int targetPageNumber = positioningInstruction.getPage(); logger.debug("Target Page: " + targetPageNumber); // rootPages.getAllKids(kids); PDPage targetPage = documentPagesKids.get(targetPageNumber - 1); int rot = targetPage.findRotation(); logger.debug("Page rotation: " + rot); // positioningInstruction.setRotation(positioningInstruction.getRotation() // + rot); logger.debug("resulting Sign rotation: " + positioningInstruction.getRotation()); SignaturePositionImpl position = new SignaturePositionImpl(); position.setX(positioningInstruction.getX()); position.setY(positioningInstruction.getY()); position.setPage(positioningInstruction.getPage()); position.setHeight(visualObject.getHeight()); position.setWidth(visualObject.getWidth()); requestedSignature.setSignaturePosition(position); properties = new PDFAsVisualSignatureProperties(pdfObject.getStatus().getSettings(), pdfObject, (PdfBoxVisualObject) visualObject, positioningInstruction, signatureProfileSettings); properties.buildSignature(); /* * ByteArrayOutputStream sigbos = new * ByteArrayOutputStream(); * sigbos.write(StreamUtils.inputStreamToByteArray * (properties .getVisibleSignature())); sigbos.close(); */ if (signaturePlaceholderData != null) { // Placeholder found! // replace placeholder InputStream is = null; try { is = PADESPDFBOXSigner.class.getResourceAsStream("/placeholder/empty.jpg"); PDJpeg img = new PDJpeg(doc, is); img.getCOSObject().setNeedToBeUpdate(true); PDDocumentCatalog root = doc.getDocumentCatalog(); PDPageNode rootPages = root.getPages(); List<PDPage> kids = new ArrayList<PDPage>(); rootPages.getAllKids(kids); int pageNumber = positioningInstruction.getPage(); // rootPages.getAllKids(kids); PDPage page = kids.get(pageNumber - 1); logger.info("Placeholder name: " + signaturePlaceholderData.getPlaceholderName()); COSDictionary xobjectsDictionary = (COSDictionary) page.findResources() .getCOSDictionary().getDictionaryObject(COSName.XOBJECT); xobjectsDictionary.setItem(signaturePlaceholderData.getPlaceholderName(), img); xobjectsDictionary.setNeedToBeUpdate(true); page.findResources().getCOSObject().setNeedToBeUpdate(true); logger.info("Placeholder name: " + signaturePlaceholderData.getPlaceholderName()); } finally { IOUtils.closeQuietly(is); } } if (signatureProfileSettings.isPDFA()) { PDDocumentCatalog root = doc.getDocumentCatalog(); COSBase base = root.getCOSDictionary().getItem(COSName.OUTPUT_INTENTS); if (base == null) { InputStream colorProfile = null; try { colorProfile = PDDocumentCatalog.class .getResourceAsStream("/icm/sRGB Color Space Profile.icm"); try { PDOutputIntent oi = new PDOutputIntent(doc, colorProfile); oi.setInfo("sRGB IEC61966-2.1"); oi.setOutputCondition("sRGB IEC61966-2.1"); oi.setOutputConditionIdentifier("sRGB IEC61966-2.1"); oi.setRegistryName("http://www.color.org"); root.addOutputIntent(oi); root.getCOSObject().setNeedToBeUpdate(true); logger.info("added Output Intent"); } catch (Throwable e) { throw new PdfAsException("Failed to add Output Intent", e); } } finally { IOUtils.closeQuietly(colorProfile); } } } options.setPage(positioningInstruction.getPage()); options.setVisualSignature(properties.getVisibleSignature()); } visualSignatureDocumentGuard = options.getVisualSignature(); doc.addSignature(signature, signer, options); // set need to update indirect fields array in acro form COSDictionary trailer = doc.getDocument().getTrailer(); if (trailer != null) { COSDictionary troot = (COSDictionary) trailer.getDictionaryObject(COSName.ROOT); if (troot != null) { COSDictionary acroForm = (COSDictionary) troot.getDictionaryObject(COSName.ACRO_FORM); if (acroForm != null) { COSArray tfields = (COSArray) acroForm.getDictionaryObject(COSName.FIELDS); if (tfields != null && !tfields.isDirect()) { tfields.setNeedToBeUpdate(true); } } } } String sigFieldName = signatureProfileSettings.getSignFieldValue(); if (sigFieldName == null) { sigFieldName = "PDF-AS Signatur"; } int count = PdfBoxUtils.countSignatures(doc, sigFieldName); sigFieldName = sigFieldName + count; PDAcroForm acroFormm = doc.getDocumentCatalog().getAcroForm(); PDSignatureField signatureField = null; if (acroFormm != null) { @SuppressWarnings("unchecked") List<PDField> fields = acroFormm.getFields(); if (fields != null) { for (PDField pdField : fields) { if (pdField != null) { if (pdField instanceof PDSignatureField) { PDSignatureField tmpSigField = (PDSignatureField) pdField; if (tmpSigField.getSignature() != null && tmpSigField.getSignature().getDictionary() != null) { if (tmpSigField.getSignature().getDictionary() .equals(signature.getDictionary())) { signatureField = (PDSignatureField) pdField; } } } } } } else { logger.warn("Failed to name Signature Field! [Cannot find Field list in acroForm!]"); } if (signatureField != null) { signatureField.setPartialName(sigFieldName); } if (properties != null) { signatureField.setAlternateFieldName(properties.getAlternativeTableCaption()); } else { signatureField.setAlternateFieldName(sigFieldName); } } else { logger.warn("Failed to name Signature Field! [Cannot find acroForm!]"); } // PDF-UA logger.info("Adding pdf/ua content."); try { PDDocumentCatalog root = doc.getDocumentCatalog(); PDStructureTreeRoot structureTreeRoot = root.getStructureTreeRoot(); if (structureTreeRoot != null) { logger.info("Tree Root: {}", structureTreeRoot.toString()); List<Object> kids = structureTreeRoot.getKids(); if (kids == null) { logger.info("No kid-elements in structure tree Root, maybe not PDF/UA document"); } PDStructureElement docElement = null; for (Object k : kids) { if (k instanceof PDStructureElement) { docElement = (PDStructureElement) k; break; } } PDStructureElement sigBlock = new PDStructureElement("Form", docElement); // create object dictionary and add as child element COSDictionary objectDic = new COSDictionary(); objectDic.setName("Type", "OBJR"); objectDic.setItem("Pg", signatureField.getWidget().getPage()); objectDic.setItem("Obj", signatureField.getWidget()); List<Object> l = new ArrayList<Object>(); l.add(objectDic); sigBlock.setKids(l); sigBlock.setPage(signatureField.getWidget().getPage()); sigBlock.setTitle("Signature Table"); sigBlock.setParent(docElement); docElement.appendKid(sigBlock); // Create and add Attribute dictionary to mitigate PAC // warning COSDictionary sigBlockDic = (COSDictionary) sigBlock.getCOSObject(); COSDictionary sub = new COSDictionary(); sub.setName("O", "Layout"); sub.setName("Placement", "Block"); sigBlockDic.setItem(COSName.A, sub); sigBlockDic.setNeedToBeUpdate(true); // Modify number tree PDNumberTreeNode ntn = structureTreeRoot.getParentTree(); int parentTreeNextKey = structureTreeRoot.getParentTreeNextKey(); if (ntn == null) { ntn = new PDNumberTreeNode(objectDic, null); logger.info("No number-tree-node found!"); } COSArray ntnKids = (COSArray) ntn.getCOSDictionary().getDictionaryObject(COSName.KIDS); COSArray ntnNumbers = (COSArray) ntn.getCOSDictionary().getDictionaryObject(COSName.NUMS); if (ntnNumbers == null && ntnKids != null) {//no number array, so continue with the kids array //create dictionary with limits and nums array COSDictionary pTreeEntry = new COSDictionary(); COSArray limitsArray = new COSArray(); //limits for exact one entry limitsArray.add(COSInteger.get(parentTreeNextKey)); limitsArray.add(COSInteger.get(parentTreeNextKey)); COSArray numsArray = new COSArray(); numsArray.add(COSInteger.get(parentTreeNextKey)); numsArray.add(sigBlock); pTreeEntry.setItem(COSName.NUMS, numsArray); pTreeEntry.setItem(COSName.LIMITS, limitsArray); PDNumberTreeNode newKidsElement = new PDNumberTreeNode(pTreeEntry, PDNumberTreeNode.class); ntnKids.add(newKidsElement); ntnKids.setNeedToBeUpdate(true); //working // List<PDNumberTreeNode> treeRootKids = structureTreeRoot.getParentTree().getKids(); // PDNumberTreeNode last = (PDNumberTreeNode)treeRootKids.get(treeRootKids.size()-1); // COSArray lim1 = (COSArray) last.getCOSDictionary().getDictionaryObject(COSName.LIMITS); // lim1.remove(1); // lim1.add(1, COSInteger.get(parentTreeNextKey)); // PDNumberTreeNode verylast = (PDNumberTreeNode)last.getKids().get(last.getKids().size()-1); // COSArray numa = (COSArray) verylast.getCOSDictionary().getDictionaryObject(COSName.NUMS); // COSArray lim = (COSArray) verylast.getCOSDictionary().getDictionaryObject(COSName.LIMITS); // lim.remove(1); // lim.add(1, COSInteger.get(parentTreeNextKey)); // // int size = numa.size(); // numa.add(size, COSInteger.get(parentTreeNextKey)); // numa.add(sigBlock); //working end } else if (ntnNumbers != null && ntnKids == null) { int arrindex = ntnNumbers.size(); ntnNumbers.add(arrindex, COSInteger.get(parentTreeNextKey)); ntnNumbers.add(arrindex + 1, sigBlock.getCOSObject()); ntnNumbers.getCOSObject().setNeedToBeUpdate(true); structureTreeRoot.setParentTree(ntn); } else if (ntnNumbers == null && ntnKids == null) { //document is not pdfua conform before signature creation throw new PdfAsException("error.pdf.sig.pdfua.1"); } else { //this is not allowed throw new PdfAsException("error.pdf.sig.pdfua.1"); } // set StructureParent for signature field annotation signatureField.getWidget().setStructParent(parentTreeNextKey); //Increase the next Key value in the structure tree root structureTreeRoot.setParentTreeNextKey(parentTreeNextKey + 1); // add the Tabs /S Element for Tabbing through annots PDPage p = signatureField.getWidget().getPage(); p.getCOSDictionary().setName("Tabs", "S"); p.getCOSObject().setNeedToBeUpdate(true); //check alternative signature field name if (signatureField != null) { if (signatureField.getAlternateFieldName().equals("")) signatureField.setAlternateFieldName(sigFieldName); } ntn.getCOSDictionary().setNeedToBeUpdate(true); sigBlock.getCOSObject().setNeedToBeUpdate(true); structureTreeRoot.getCOSObject().setNeedToBeUpdate(true); objectDic.getCOSObject().setNeedToBeUpdate(true); docElement.getCOSObject().setNeedToBeUpdate(true); } } catch (Throwable e) { if (signatureProfileSettings.isPDFUA() == true) { logger.error("Could not create PDF-UA conform document!"); throw new PdfAsException("error.pdf.sig.pdfua.1", e); } else { logger.info("Could not create PDF-UA conform signature"); } } try { applyFilter(doc, requestedSignature); } catch (PDFASError e) { throw new PdfAsErrorCarrier(e); } FileInputStream tmpFileIs = null; try { tmpFileIs = new FileInputStream(new File(fisTmpFile)); synchronized (doc) { doc.saveIncremental(tmpFileIs, tmpOutputStream); } tmpFileIs.close(); } finally { IOUtils.closeQuietly(tmpFileIs); if (options != null) { if (options.getVisualSignature() != null) { options.getVisualSignature().close(); } } } tmpOutputStream.flush(); tmpOutputStream.close(); } finally { IOUtils.closeQuietly(tmpOutputStream); COSDocument visualSignature = options.getVisualSignature(); if (visualSignature != null) { visualSignature.close(); } } FileInputStream readReadyFile = null; try { readReadyFile = new FileInputStream(new File(fisTmpFile)); // write to resulting output stream // ByteArrayOutputStream bos = new ByteArrayOutputStream(); // bos.write(); // bos.close(); pdfObject.setSignedDocument(StreamUtils.inputStreamToByteArray(readReadyFile)); readReadyFile.close(); } finally { IOUtils.closeQuietly(readReadyFile); } } catch (IOException e) { logger.info(MessageResolver.resolveMessage("error.pdf.sig.01") + ": {}", e.toString()); throw new PdfAsException("error.pdf.sig.01", e); } catch (SignatureException e) { logger.info(MessageResolver.resolveMessage("error.pdf.sig.01") + ": {}", e.toString()); throw new PdfAsException("error.pdf.sig.01", e); } catch (COSVisitorException e) { logger.info(MessageResolver.resolveMessage("error.pdf.sig.01") + ": {}", e.toString()); throw new PdfAsException("error.pdf.sig.01", e); } finally { if (doc != null) { try { doc.close(); } catch (IOException e) { logger.debug("Failed to close COS Doc!", e); // Ignore } } if (fisTmpFile != null) { helper.deleteFile(fisTmpFile); } logger.debug("Signature done!"); } }