List of usage examples for javax.persistence EntityManager find
public <T> T find(Class<T> entityClass, Object primaryKey);
From source file:gov.osti.services.Metadata.java
/** * Persist the DOECodeMetadata Object to the persistence layer. Assumes an * open Transaction is already in progress, and it's up to the caller to * handle Exceptions or commit as appropriate. * * If the "code ID" is already present in the Object to store, it will * attempt to merge changes; otherwise, a new Object will be instantiated * in the database. Note that any WORKFLOW STATUS present will be preserved, * regardless of the incoming one.//from w ww .j ava 2 s . c o m * * @param em the EntityManager to interface with the persistence layer * @param md the Object to store * @param user the User performing this action (must be the OWNER of the * record in order to UPDATE) * @throws NotFoundException when record to update is not on file * @throws IllegalAccessException when attempting to update record not * owned by User * @throws InvocationTargetException on reflection errors */ private void store(EntityManager em, DOECodeMetadata md, User user) throws NotFoundException, IllegalAccessException, InvocationTargetException { // fix the open source value before storing md.setOpenSource( Accessibility.OS.equals(md.getAccessibility()) || Accessibility.ON.equals(md.getAccessibility())); ValidatorFactory validators = javax.validation.Validation.buildDefaultValidatorFactory(); Validator validator = validators.getValidator(); // must be OSTI user in order to add/update PROJECT KEYWORDS List<String> projectKeywords = md.getProjectKeywords(); if (projectKeywords != null && !projectKeywords.isEmpty() && !user.hasRole("OSTI")) throw new ValidationException("Project Keywords can only be set by authorized users."); // if there's a CODE ID, attempt to look up the record first and // copy attributes into it if (null == md.getCodeId() || 0 == md.getCodeId()) { // perform length validations on Bean Set<ConstraintViolation<DOECodeMetadata>> violations = validator.validate(md); if (!violations.isEmpty()) { List<String> reasons = new ArrayList<>(); violations.stream().forEach(violation -> { reasons.add(violation.getMessage()); }); throw new BadRequestException(ErrorResponse.badRequest(reasons).build()); } em.persist(md); } else { DOECodeMetadata emd = em.find(DOECodeMetadata.class, md.getCodeId()); if (null != emd) { // must be the OWNER, SITE ADMIN, or OSTI in order to UPDATE if (!user.getEmail().equals(emd.getOwner()) && !user.hasRole(emd.getSiteOwnershipCode()) && !user.hasRole("OSTI")) throw new IllegalAccessException("Invalid access attempt."); // to Save, item must be non-existant, or already in Saved workflow status (if here, we know it exists) if (Status.Saved.equals(md.getWorkflowStatus()) && !Status.Saved.equals(emd.getWorkflowStatus())) throw new BadRequestException(ErrorResponse .badRequest("Save cannot be performed after a record has been Submitted or Announced.") .build()); // these fields WILL NOT CHANGE on edit/update md.setOwner(emd.getOwner()); md.setSiteOwnershipCode(emd.getSiteOwnershipCode()); // if there's ALREADY a DOI, and we have been SUBMITTED/APPROVED, keep it if (StringUtils.isNotEmpty(emd.getDoi()) && (Status.Submitted.equals(emd.getWorkflowStatus()) || Status.Approved.equals(emd.getWorkflowStatus()))) md.setDoi(emd.getDoi()); // do not modify AutoBackfill RI info List<RelatedIdentifier> originalList = emd.getRelatedIdentifiers(); List<RelatedIdentifier> newList = md.getRelatedIdentifiers(); // if there is a New List and a non-empty Original List, then process RI info if (newList != null && originalList != null && !originalList.isEmpty()) { // get AutoBackfill data List<RelatedIdentifier> autoRIList = getSourceRi(originalList, RelatedIdentifier.Source.AutoBackfill); // restore any modified Auto data newList.removeAll(autoRIList); // always remove match newList.addAll(autoRIList); // add back, if needed md.setRelatedIdentifiers(newList); } // perform length validations on Bean Set<ConstraintViolation<DOECodeMetadata>> violations = validator.validate(md); if (!violations.isEmpty()) { List<String> reasons = new ArrayList<>(); violations.stream().forEach(violation -> { reasons.add(violation.getMessage()); }); throw new BadRequestException(ErrorResponse.badRequest(reasons).build()); } // found it, "merge" Bean attributes BeanUtilsBean noNulls = new NoNullsBeanUtilsBean(); noNulls.copyProperties(emd, md); // if the RELEASE DATE was set, it might have been "cleared" (set to null) // and thus ignored by the Bean copy; this sets the value regardless if setReleaseDate() got called if (md.hasSetReleaseDate()) emd.setReleaseDate(md.getReleaseDate()); // what comes back needs to be complete: noNulls.copyProperties(md, emd); // EntityManager should handle this attached Object // NOTE: the returned Object is NOT ATTACHED to the EntityManager } else { // can't find record to update, that's an error log.warn("Unable to locate record for " + md.getCodeId() + " to update."); throw new NotFoundException("Record Code ID " + md.getCodeId() + " not on file."); } } }
From source file:org.sigmah.server.servlet.exporter.models.OrgUnitModelHandler.java
/** * Save the flexible elements of imported organizational unit model * /* www.j a v a 2s.c o m*/ * @param orgUnitModel * the imported organizational unit model * @param em * the entity manager */ private void saveOrgUnitFlexibleElement(OrgUnitModel orgUnitModel, EntityManager em) { // OrgUnitModel --> Banner --> Layout --> Groups --> Constraints if (orgUnitModel.getBanner() != null && orgUnitModel.getBanner().getLayout() != null) { List<LayoutGroup> bannerLayoutGroups = orgUnitModel.getBanner().getLayout().getGroups(); if (bannerLayoutGroups != null) { for (LayoutGroup layoutGroup : bannerLayoutGroups) { List<LayoutConstraint> layoutConstraints = layoutGroup.getConstraints(); if (layoutConstraints != null) { for (LayoutConstraint layoutConstraint : layoutConstraints) { if (layoutConstraint.getElement() != null) { if (layoutConstraint.getElement() instanceof QuestionElement) { List<QuestionChoiceElement> questionChoiceElements = ((QuestionElement) layoutConstraint .getElement()).getChoices(); CategoryType type = ((QuestionElement) layoutConstraint.getElement()) .getCategoryType(); if (questionChoiceElements != null || type != null) { FlexibleElement parent = layoutConstraint.getElement(); ((QuestionElement) parent).setChoices(null); ((QuestionElement) parent).setCategoryType(null); em.persist(parent); // Save QuestionChoiceElement with their QuestionElement parent(saved above) if (questionChoiceElements != null) { for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) { if (questionChoiceElement != null) { questionChoiceElement.setId(null); questionChoiceElement .setParentQuestion((QuestionElement) parent); CategoryElement categoryElement = questionChoiceElement .getCategoryElement(); if (categoryElement != null) { questionChoiceElement.setCategoryElement(null); em.persist(questionChoiceElement); saveOrgUnitModelCategoryElement(categoryElement, em); questionChoiceElement.setCategoryElement(categoryElement); em.merge(questionChoiceElement); } else { em.persist(questionChoiceElement); } } } // Set saved QuestionChoiceElement to QuestionElement parent and update it ((QuestionElement) parent).setChoices(questionChoiceElements); } // Save the Category type of QuestionElement parent(saved above) if (type != null) { if (em.find(CategoryType.class, type.getId()) == null) { List<CategoryElement> typeElements = type.getElements(); if (typeElements != null) { type.setElements(null); em.merge(type); for (CategoryElement element : typeElements) { if (em.find(CategoryElement.class, element.getId()) == null) { element.setParentType(type); saveOrgUnitModelCategoryElement(element, em); } } type.setElements(typeElements); em.merge(type); } } // Set the saved CategoryType to QuestionElement parent and update it ((QuestionElement) parent).setCategoryType(type); } // Update the QuestionElement parent em.merge(parent); } else { em.persist(layoutConstraint.getElement()); } } else { em.persist(layoutConstraint.getElement()); } } } } } } } // OrgUnitModel --> Detail --> Layout --> Groups --> Constraints if (orgUnitModel.getDetails() != null && orgUnitModel.getDetails().getLayout() != null) { List<LayoutGroup> detailLayoutGroups = orgUnitModel.getDetails().getLayout().getGroups(); if (detailLayoutGroups != null) { for (LayoutGroup layoutGroup : detailLayoutGroups) { List<LayoutConstraint> layoutConstraints = layoutGroup.getConstraints(); if (layoutConstraints != null) { for (LayoutConstraint layoutConstraint : layoutConstraints) { if (layoutConstraint.getElement() != null) { if (layoutConstraint.getElement() instanceof QuestionElement) { List<QuestionChoiceElement> questionChoiceElements = ((QuestionElement) layoutConstraint .getElement()).getChoices(); CategoryType type = ((QuestionElement) layoutConstraint.getElement()) .getCategoryType(); if (questionChoiceElements != null || type != null) { FlexibleElement parent = layoutConstraint.getElement(); ((QuestionElement) parent).setChoices(null); ((QuestionElement) parent).setCategoryType(null); em.persist(parent); // Save QuestionChoiceElement with their QuestionElement parent(saved above) if (questionChoiceElements != null) { for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) { if (questionChoiceElement != null) { questionChoiceElement.setId(null); questionChoiceElement .setParentQuestion((QuestionElement) parent); CategoryElement categoryElement = questionChoiceElement .getCategoryElement(); if (categoryElement != null) { questionChoiceElement.setCategoryElement(null); em.persist(questionChoiceElement); saveOrgUnitModelCategoryElement(categoryElement, em); questionChoiceElement.setCategoryElement(categoryElement); em.merge(questionChoiceElement); } else { em.persist(questionChoiceElement); } } } // Set saved QuestionChoiceElement to QuestionElement parent and update it ((QuestionElement) parent).setChoices(questionChoiceElements); } // Save the Category type of QuestionElement parent(saved above) if (type != null) { if (em.find(CategoryType.class, type.getId()) == null) { List<CategoryElement> typeElements = type.getElements(); if (typeElements != null) { type.setElements(null); em.merge(type); for (CategoryElement element : typeElements) { if (em.find(CategoryElement.class, element.getId()) == null) { element.setParentType(type); saveOrgUnitModelCategoryElement(element, em); } } type.setElements(typeElements); em.merge(type); } } // Set the saved CategoryType to QuestionElement parent and update it ((QuestionElement) parent).setCategoryType(type); } // Update the QuestionElement parent em.merge(parent); } else { em.persist(layoutConstraint.getElement()); } } else { em.persist(layoutConstraint.getElement()); } } } } } } } }
From source file:org.sigmah.server.endpoint.export.sigmah.handler.OrgUnitModelHandler.java
/** * Save the flexible elements of imported organizational unit model * /* w ww . j a va2 s .c o m*/ * @param orgUnitModel * the imported organizational unit model * @param em * the entity manager */ private void saveOrgUnitFlexibleElement(OrgUnitModel orgUnitModel, EntityManager em) { // OrgUnitModel --> Banner --> Layout --> Groups --> Constraints if (orgUnitModel.getBanner() != null && orgUnitModel.getBanner().getLayout() != null) { List<LayoutGroup> bannerLayoutGroups = orgUnitModel.getBanner().getLayout().getGroups(); if (bannerLayoutGroups != null) { for (LayoutGroup layoutGroup : bannerLayoutGroups) { List<LayoutConstraint> layoutConstraints = layoutGroup.getConstraints(); if (layoutConstraints != null) { for (LayoutConstraint layoutConstraint : layoutConstraints) { if (layoutConstraint.getElement() != null) { if (layoutConstraint.getElement() instanceof QuestionElement) { List<QuestionChoiceElement> questionChoiceElements = ((QuestionElement) layoutConstraint .getElement()).getChoices(); CategoryType type = ((QuestionElement) layoutConstraint.getElement()) .getCategoryType(); if (questionChoiceElements != null || type != null) { FlexibleElement parent = (FlexibleElement) layoutConstraint.getElement(); ((QuestionElement) parent).setChoices(null); ((QuestionElement) parent).setCategoryType(null); em.persist(parent); // Save QuestionChoiceElement with their QuestionElement parent(saved above) if (questionChoiceElements != null) { for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) { if (questionChoiceElement != null) { questionChoiceElement.setId(null); questionChoiceElement .setParentQuestion((QuestionElement) parent); CategoryElement categoryElement = questionChoiceElement .getCategoryElement(); if (categoryElement != null) { questionChoiceElement.setCategoryElement(null); em.persist(questionChoiceElement); saveOrgUnitModelCategoryElement(categoryElement, em); questionChoiceElement.setCategoryElement(categoryElement); em.merge(questionChoiceElement); } else { em.persist(questionChoiceElement); } } } // Set saved QuestionChoiceElement to QuestionElement parent and update it ((QuestionElement) parent).setChoices(questionChoiceElements); } // Save the Category type of QuestionElement parent(saved above) if (type != null) { if (em.find(CategoryType.class, type.getId()) == null) { List<CategoryElement> typeElements = type.getElements(); if (typeElements != null) { type.setElements(null); em.merge(type); for (CategoryElement element : typeElements) { if (em.find(CategoryElement.class, element.getId()) == null) { element.setParentType(type); saveOrgUnitModelCategoryElement(element, em); } } type.setElements(typeElements); em.merge(type); } } //Set the saved CategoryType to QuestionElement parent and update it ((QuestionElement) parent).setCategoryType(type); } //Update the QuestionElement parent em.merge(parent); } else { em.persist(layoutConstraint.getElement()); } } else { em.persist(layoutConstraint.getElement()); } } } } } } } // OrgUnitModel --> Detail --> Layout --> Groups --> Constraints if (orgUnitModel.getDetails() != null && orgUnitModel.getDetails().getLayout() != null) { List<LayoutGroup> detailLayoutGroups = orgUnitModel.getDetails().getLayout().getGroups(); if (detailLayoutGroups != null) { for (LayoutGroup layoutGroup : detailLayoutGroups) { List<LayoutConstraint> layoutConstraints = layoutGroup.getConstraints(); if (layoutConstraints != null) { for (LayoutConstraint layoutConstraint : layoutConstraints) { if (layoutConstraint.getElement() != null) { if (layoutConstraint.getElement() instanceof QuestionElement) { List<QuestionChoiceElement> questionChoiceElements = ((QuestionElement) layoutConstraint .getElement()).getChoices(); CategoryType type = ((QuestionElement) layoutConstraint.getElement()) .getCategoryType(); if (questionChoiceElements != null || type != null) { FlexibleElement parent = (FlexibleElement) layoutConstraint.getElement(); ((QuestionElement) parent).setChoices(null); ((QuestionElement) parent).setCategoryType(null); em.persist(parent); // Save QuestionChoiceElement with their QuestionElement parent(saved above) if (questionChoiceElements != null) { for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) { if (questionChoiceElement != null) { questionChoiceElement.setId(null); questionChoiceElement .setParentQuestion((QuestionElement) parent); CategoryElement categoryElement = questionChoiceElement .getCategoryElement(); if (categoryElement != null) { questionChoiceElement.setCategoryElement(null); em.persist(questionChoiceElement); saveOrgUnitModelCategoryElement(categoryElement, em); questionChoiceElement.setCategoryElement(categoryElement); em.merge(questionChoiceElement); } else { em.persist(questionChoiceElement); } } } // Set saved QuestionChoiceElement to QuestionElement parent and update it ((QuestionElement) parent).setChoices(questionChoiceElements); } // Save the Category type of QuestionElement parent(saved above) if (type != null) { if (em.find(CategoryType.class, type.getId()) == null) { List<CategoryElement> typeElements = type.getElements(); if (typeElements != null) { type.setElements(null); em.merge(type); for (CategoryElement element : typeElements) { if (em.find(CategoryElement.class, element.getId()) == null) { element.setParentType(type); saveOrgUnitModelCategoryElement(element, em); } } type.setElements(typeElements); em.merge(type); } } //Set the saved CategoryType to QuestionElement parent and update it ((QuestionElement) parent).setCategoryType(type); } //Update the QuestionElement parent em.merge(parent); } else { em.persist(layoutConstraint.getElement()); } } else { em.persist(layoutConstraint.getElement()); } } } } } } } }
From source file:org.apache.juddi.validation.ValidatePublish.java
public void validateBindingTemplate(EntityManager em, org.uddi.api_v3.BindingTemplate bindingTemplate, org.uddi.api_v3.BusinessService parent, Configuration config) throws DispositionReportFaultMessage { // A supplied bindingTemplate can't be null if (bindingTemplate == null) { throw new ValueNotAllowedException(new ErrorMessage("errors.bindingtemplate.NullInput")); }/* w ww. j a va 2 s .c o m*/ // Retrieve the binding's passed key String entityKey = bindingTemplate.getBindingKey(); if (entityKey != null && entityKey.length() > 0) { // Per section 4.4: keys must be case-folded entityKey = entityKey.toLowerCase(); bindingTemplate.setBindingKey(entityKey); validateKeyLength(entityKey); } // The parent key is either supplied or provided by the higher call to the parent entity save. If it is provided in both instances, if they differ, an // error occurs. String parentKey = bindingTemplate.getServiceKey(); if (parentKey != null && parentKey.length() > 0) { // Per section 4.4: keys must be case-folded parentKey = parentKey.toLowerCase(); bindingTemplate.setServiceKey(parentKey); } if (parent != null) { if (parentKey != null && parentKey.length() > 0) { if (!parentKey.equalsIgnoreCase(parent.getServiceKey())) { throw new InvalidKeyPassedException( new ErrorMessage("errors.invalidkey.bindingtemplate.ParentMismatch", parentKey + ", " + parent.getBusinessKey())); } } else { parentKey = parent.getServiceKey(); } } boolean entityExists = false; if (entityKey == null || entityKey.length() == 0) { validateNotSigned(bindingTemplate); KeyGenerator keyGen = KeyGeneratorFactory.getKeyGenerator(); entityKey = keyGen.generate(); bindingTemplate.setBindingKey(entityKey); } else { Object obj = em.find(org.apache.juddi.model.BindingTemplate.class, entityKey); if (obj != null) { entityExists = true; org.apache.juddi.model.BindingTemplate bt = (org.apache.juddi.model.BindingTemplate) obj; // If the object exists, and the parentKey was not found to this point, then a save on an existing binding with a blank // service key has occurred. It is set here and added to the entity being saved - a necessary step for the object to be // persisted properly. (This condition makes some validation tests below unnecessary as the parent is "verified" but it's OK to // still run them). if (parentKey == null || parentKey.length() == 0) { parentKey = bt.getBusinessService().getEntityKey(); bindingTemplate.setServiceKey(parentKey); } // If existing binding trying to be saved has a different parent key, then we have a problem // TODO: moving bindings is allowed according to spec? if (!parentKey.equalsIgnoreCase(bt.getBusinessService().getEntityKey())) { throw new InvalidKeyPassedException( new ErrorMessage("errors.invalidkey.bindingtemplate.ParentMismatch", parentKey + ", " + bt.getBusinessService().getEntityKey())); } // Make sure publisher owns this entity. AccessCheck(obj, entityKey); //if (!publisher.isOwner((UddiEntity) obj)&& !((Publisher) publisher).isAdmin()) { // throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidOwner", entityKey)); // } } else { // Inside this block, we have a key proposed by the publisher on a new entity // Validate key and then check to see that the proposed key is valid for this publisher ValidateUDDIKey.validateUDDIv3Key(entityKey); if (!publisher.isValidPublisherKey(em, entityKey)) { throw new KeyUnavailableException( new ErrorMessage("errors.keyunavailable.BadPartition", entityKey)); } } } // Parent key must be passed if this is a new entity if (!entityExists) { if (parentKey == null || parentKey.length() == 0) { throw new InvalidKeyPassedException( new ErrorMessage("errors.invalidkey.ParentServiceNotFound", parentKey)); } } // If parent key IS passed, whether new entity or not, it must be valid. Additionally, the current publisher must be the owner of the parent. Note that // if a parent ENTITY was passed in, then we don't need to check for any of this since this is part of a higher call. if (parentKey != null) { if (parent == null) { Object parentTemp = em.find(org.apache.juddi.model.BusinessService.class, parentKey); if (parentTemp == null) { throw new InvalidKeyPassedException( new ErrorMessage("errors.invalidkey.ParentBusinessNotFound", parentKey)); } // Make sure publisher owns this parent entity. AccessCheck(parentTemp, parentKey); // if (!publisher.isOwner((UddiEntity) parentTemp)) { // throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidOwnerParent", parentKey)); // } } } if (!entityExists) { // Check to make sure key isn't used by another entity. if (!isUniqueKey(em, entityKey)) { throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.KeyExists", entityKey)); } } //was TODO validate "checked" categories or category groups (see section 5.2.3 of spec)? optional to support //at least one must be defined if (bindingTemplate.getAccessPoint() == null && bindingTemplate.getHostingRedirector() == null) { throw new ValueNotAllowedException(new ErrorMessage("errors.bindingtemplate.NoAccessPoint")); } //but not both if (bindingTemplate.getAccessPoint() != null && bindingTemplate.getHostingRedirector() != null) { throw new ValueNotAllowedException(new ErrorMessage("errors.bindingtemplate.NoAccessPoint")); } validateCategoryBag(bindingTemplate.getCategoryBag(), config, false); validateTModelInstanceDetails(bindingTemplate.getTModelInstanceDetails(), config, false); validateAccessPoint(em, bindingTemplate.getAccessPoint(), config); validateDescriptions(bindingTemplate.getDescription()); validateHostingRedirector(em, bindingTemplate.getHostingRedirector(), config); }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
@Override public Map<com.hiperf.common.ui.shared.util.Id, INakedObject> persist(ObjectsToPersist toPersist, String userName, Locale locale) throws PersistenceException { TransactionContext tc = null;//from ww w. java 2 s . c o m Map<com.hiperf.common.ui.shared.util.Id, INakedObject> res = new HashMap<com.hiperf.common.ui.shared.util.Id, INakedObject>(); try { Map<Object, IdHolder> newIdByOldId = new HashMap<Object, IdHolder>(); tc = createTransactionalContext(); EntityManager em = tc.getEm(); ITransaction tx = tc.getTx(); tx.begin(); if (doPersist(toPersist, userName, res, newIdByOldId, em, false, locale)) tx.commit(); else throw new PersistenceException("a technical problem occured during data insertion"); } catch (Exception e) { catchPersistException(tc, e); processDbExceptions(locale, e); } finally { if (tc != null) close(tc); } Map<String, Map<com.hiperf.common.ui.shared.util.Id, INakedObject>> deproxyCtx = new HashMap<String, Map<com.hiperf.common.ui.shared.util.Id, INakedObject>>(); EntityManager em = null; try { for (Entry<com.hiperf.common.ui.shared.util.Id, INakedObject> entry : res.entrySet()) { em = getEntityManager(); INakedObject no = entry.getValue(); String nakedObjectName = no.getClass().getName(); com.hiperf.common.ui.shared.util.Id id = getId(no, idsByClassName.get(nakedObjectName)); Map<com.hiperf.common.ui.shared.util.Id, INakedObject> map = deproxyCtx.get(nakedObjectName); if (map == null || !map.containsKey(id)) { if (id.getFieldNames().size() == 1) { no = (INakedObject) em.find(Class.forName(nakedObjectName), id.getFieldValues().get(0)); } else { Class c = Class.forName(nakedObjectName); no = (INakedObject) em.find(c, getCompositeId(c, id.getFieldNames(), id.getFieldValues())); } entry.setValue(deproxyNakedObject(no, em, deproxyCtx)); } else { entry.setValue(map.get(id)); } } return res; } catch (Exception e) { logger.log(Level.SEVERE, "Exception in persist : " + e.getMessage(), e); throw new PersistenceException("Exception in persist : " + e.getMessage(), e); } finally { closeEntityManager(em); } }
From source file:org.sigmah.server.servlet.exporter.models.ProjectModelHandler.java
private void saveLayoutGroups(final List<LayoutGroup> layoutGroups, EntityManager em, HashMap<Object, Object> modelesReset, HashSet<Object> modelesImport, User user) { final HashSet<Integer> reportModelsId = new HashSet<Integer>(); if (layoutGroups != null) { for (LayoutGroup layoutGroup : layoutGroups) { final List<LayoutConstraint> layoutConstraints; if (layoutGroup != null) layoutConstraints = layoutGroup.getConstraints(); else// w w w .jav a2s. c o m layoutConstraints = null; if (layoutConstraints != null) { // Iterating over the constraints for (LayoutConstraint layoutConstraint : layoutConstraints) { if (layoutConstraint != null && layoutConstraint.getElement() != null) { final FlexibleElement element = layoutConstraint.getElement(); // Do not persist an element twice. if (em.contains(element)) { continue; } // Initialize export flags of flexible element element.initializeExportFlags(); // If the current element is a QuestionElement if (element instanceof QuestionElement) { final QuestionElement questionElement = (QuestionElement) element; List<QuestionChoiceElement> questionChoiceElements = questionElement.getChoices(); CategoryType type = questionElement.getCategoryType(); if (questionChoiceElements != null || type != null) { questionElement.setChoices(null); questionElement.setCategoryType(null); em.persist(questionElement); // Save QuestionChoiceElement with their // QuestionElement parent(saved above) if (questionChoiceElements != null) { for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) { if (questionChoiceElement != null) { questionChoiceElement.setId(null); questionChoiceElement.setParentQuestion(questionElement); CategoryElement categoryElement = questionChoiceElement .getCategoryElement(); if (categoryElement != null) { questionChoiceElement.setCategoryElement(null); em.persist(questionChoiceElement); saveProjectModelCategoryElement(categoryElement, em, modelesReset, modelesImport); questionChoiceElement.setCategoryElement(categoryElement); em.merge(questionChoiceElement); } else { em.persist(questionChoiceElement); } } } // Set saved QuestionChoiceElement to // QuestionElement parent and update it questionElement.setChoices(questionChoiceElements); } // Save the Category type of QuestionElement // parent(saved above) if (type != null) { if (em.find(CategoryType.class, type.getId()) == null) { List<CategoryElement> typeElements = type.getElements(); if (typeElements != null) { type.setElements(null); em.merge(type); for (CategoryElement categoryElement : typeElements) { if (em.find(CategoryElement.class, categoryElement.getId()) == null) { categoryElement.setParentType(type); saveProjectModelCategoryElement(categoryElement, em, modelesReset, modelesImport); } } type.setElements(typeElements); em.merge(type); } } // Set the saved CategoryType to // QuestionElement parent and update it questionElement.setCategoryType(type); } // Update the QuestionElement parent em.merge(questionElement); } else { em.persist(element); } } // Report element else if (element instanceof ReportElement) { final ReportElement reportElement = (ReportElement) element; final ProjectReportModel oldModel = reportElement.getModel(); if (oldModel != null) { final int oldModelId = oldModel.getId(); final ProjectReportModel newModel; if (!reportModelsId.contains(oldModelId)) { oldModel.resetImport(new HashMap<Object, Object>(), new HashSet<Object>()); oldModel.setOrganization(user.getOrganization()); newModel = oldModel; ProjectReportModelHandler.saveProjectReportModelElement(newModel, em); em.persist(newModel); reportElement.setModel(newModel); em.persist(reportElement); reportModelsId.add(reportElement.getModel().getId()); } // If the report model has been already // saved, it is re-used. else { newModel = em.find(ProjectReportModel.class, oldModelId); reportElement.setModel(newModel); em.persist(reportElement); } } } // Reports list element else if (element instanceof ReportListElement) { final ReportListElement reportListElement = (ReportListElement) element; final ProjectReportModel oldModel = reportListElement.getModel(); if (oldModel != null) { final int oldModelId = oldModel.getId(); final ProjectReportModel newModel; if (!reportModelsId.contains(oldModelId)) { oldModel.resetImport(new HashMap<Object, Object>(), new HashSet<Object>()); oldModel.setOrganization(user.getOrganization()); newModel = oldModel; ProjectReportModelHandler.saveProjectReportModelElement(newModel, em); em.persist(newModel); reportListElement.setModel(newModel); em.persist(reportListElement); reportModelsId.add(reportListElement.getModel().getId()); } // If the report model has been already // saved, it is re-used. else { newModel = em.find(ProjectReportModel.class, oldModelId); reportListElement.setModel(newModel); em.persist(reportListElement); } } } // Budget element else if (element instanceof BudgetElement) { final BudgetElement budgetElement = (BudgetElement) element; final List<BudgetSubField> subFields = budgetElement.getBudgetSubFields(); final BudgetSubField ratioDividend = budgetElement.getRatioDividend(); final BudgetSubField ratioDivisor = budgetElement.getRatioDivisor(); budgetElement.setBudgetSubFields(null); budgetElement.setRatioDividend(null); budgetElement.setRatioDivisor(null); em.persist(budgetElement); final ArrayList<BudgetSubField> allSubFields = new ArrayList<BudgetSubField>( subFields); allSubFields.add(ratioDividend); allSubFields.add(ratioDivisor); for (final BudgetSubField subField : allSubFields) { subField.setBudgetElement(budgetElement); em.persist(budgetElement); } budgetElement.setBudgetSubFields(subFields); budgetElement.setRatioDividend(ratioDividend); budgetElement.setRatioDivisor(ratioDivisor); em.merge(budgetElement); } // Others elements else { em.persist(layoutConstraint.getElement()); } } } } } } }
From source file:org.apache.juddi.validation.ValidatePublish.java
public void validateBusinessService(EntityManager em, org.uddi.api_v3.BusinessService businessService, org.uddi.api_v3.BusinessEntity parent, Configuration config) throws DispositionReportFaultMessage { // A supplied businessService can't be null if (businessService == null) { throw new ValueNotAllowedException(new ErrorMessage("errors.businessservice.NullInput")); }/* w w w . j ava2s. c om*/ validateNotSigned(businessService); // Retrieve the service's passed key String entityKey = businessService.getServiceKey(); if (entityKey != null && entityKey.length() > 0) { // Per section 4.4: keys must be case-folded entityKey = entityKey.toLowerCase(); validateKeyLength(entityKey); businessService.setServiceKey(entityKey); } // The parent key is either supplied or provided by the higher call to the parent entity save. If the passed-in parent's business key differs from // the (non-null) business key retrieved from the service, then we have a possible service projection. String parentKey = businessService.getBusinessKey(); if (parentKey != null && parentKey.length() > 0) { // Per section 4.4: keys must be case-folded parentKey = parentKey.toLowerCase(); businessService.setBusinessKey(parentKey); } boolean isProjection = false; if (parent != null) { if (parentKey != null && parentKey.length() > 0) { if (!parentKey.equalsIgnoreCase(parent.getBusinessKey())) { // Possible projected service - if we have differing parent businesses but a service key was not provided, this is an error as it is not possible // for the business that doesn't "own" the service to generate the key for it. if (entityKey == null || entityKey.length() == 0) { throw new InvalidKeyPassedException( new ErrorMessage("errors.invalidkey.ServiceKeyNotProvidedWithProjection", parentKey + ", " + parent.getBusinessKey())); } isProjection = true; } } else { parentKey = parent.getBusinessKey(); } } // Projections don't require as rigorous testing as only the projected service's business key and service key are examined for validity. if (isProjection) { Object obj = em.find(org.apache.juddi.model.BusinessService.class, entityKey); // Can't project a service that doesn't exist! if (obj == null) { throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ProjectedServiceNotFound", parentKey + ", " + entityKey)); } else { // If the supplied business key doesn't match the existing service's business key, the projection is invalid. org.apache.juddi.model.BusinessService bs = (org.apache.juddi.model.BusinessService) obj; if (!businessService.getBusinessKey().equalsIgnoreCase(bs.getBusinessEntity().getEntityKey())) { throw new InvalidProjectionException(new ErrorMessage("errors.invalidprojection.ParentMismatch", businessService.getBusinessKey() + ", " + bs.getBusinessEntity().getEntityKey())); } } obj = null; } else { boolean entityExists = false; if (entityKey == null || entityKey.length() == 0) { KeyGenerator keyGen = KeyGeneratorFactory.getKeyGenerator(); entityKey = keyGen.generate(); businessService.setServiceKey(entityKey); } else { Object obj = em.find(org.apache.juddi.model.BusinessService.class, entityKey); if (obj != null) { entityExists = true; org.apache.juddi.model.BusinessService bs = (org.apache.juddi.model.BusinessService) obj; // If the object exists, and the parentKey was not found to this point, then a save on an existing service with a blank // business key has occurred. It is set here and added to the entity being saved - a necessary step for the object to be // persisted properly. (This condition makes some validation tests below unnecessary as the parent is "verified" but it's OK to // still run them). if (parentKey == null || parentKey.length() == 0) { parentKey = bs.getBusinessEntity().getEntityKey(); businessService.setBusinessKey(parentKey); } // Make sure publisher owns this entity. AccessCheck(obj, entityKey); // If existing service trying to be saved has a different parent key, then we have a problem if (!parentKey.equalsIgnoreCase(bs.getBusinessEntity().getEntityKey())) { // if both businesses are owned by this publisher then we allow it. // we already check the current business is owned, lets see if the old one is too if (!publisher.isOwner(bs.getBusinessEntity())) { throw new InvalidKeyPassedException( new ErrorMessage("errors.invalidkey.businessservice.ParentMismatch", parentKey + ", " + bs.getBusinessEntity().getEntityKey())); } else { if (log.isDebugEnabled()) { log.debug("Services moved from business " + bs.getBusinessEntity() + " to " + businessService.getBusinessKey()); } } } } else { // Inside this block, we have a key proposed by the publisher on a new entity // Validate key and then check to see that the proposed key is valid for this publisher ValidateUDDIKey.validateUDDIv3Key(entityKey); if (!publisher.isValidPublisherKey(em, entityKey)) { throw new KeyUnavailableException( new ErrorMessage("errors.keyunavailable.BadPartition", entityKey)); } } } // Parent key must be passed if this is a new entity if (!entityExists) { if (parentKey == null || parentKey.length() == 0) { throw new InvalidKeyPassedException( new ErrorMessage("errors.invalidkey.ParentBusinessNotFound", parentKey)); } } // If parent key IS passed, whether new entity or not, it must be valid. Additionally, the current publisher must be the owner of the parent. Note that // if a parent ENTITY was passed in, then we don't need to check for any of this since this is part of a higher call. if (parentKey != null) { if (parent == null) { Object parentTemp = em.find(org.apache.juddi.model.BusinessEntity.class, parentKey); if (parentTemp == null) { throw new InvalidKeyPassedException( new ErrorMessage("errors.invalidkey.ParentBusinessNotFound", parentKey)); } // Make sure publisher owns this parent entity. AccessCheck(parentTemp, parentKey); // if (!publisher.isOwner((UddiEntity) parentTemp)) { // throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidOwnerParent", parentKey)); //} } } if (!entityExists) { // Check to make sure key isn't used by another entity. if (!isUniqueKey(em, entityKey)) { throw new KeyUnavailableException( new ErrorMessage("errors.keyunavailable.KeyExists", entityKey)); } } // TODO: validate "checked" categories or category groups (see section 5.2.3 of spec)? optional to support validateNames(businessService.getName()); validateCategoryBag(businessService.getCategoryBag(), config, false); validateDescriptions(businessService.getDescription()); validateBindingTemplates(em, businessService.getBindingTemplates(), businessService, config); } }
From source file:org.sigmah.server.endpoint.export.sigmah.handler.ProjectModelHandler.java
private void saveLayoutGroups(final List<LayoutGroup> layoutGroups, EntityManager em, HashMap<Object, Object> modelesReset, HashSet<Object> modelesImport, Authentication authentication) { final HashSet<Integer> reportModelsId = new HashSet<Integer>(); if (layoutGroups != null) { for (LayoutGroup layoutGroup : layoutGroups) { final List<LayoutConstraint> layoutConstraints; if (layoutGroup != null) layoutConstraints = layoutGroup.getConstraints(); else//from ww w. ja va 2s .c om layoutConstraints = null; if (layoutConstraints != null) { // Iterating over the constraints for (LayoutConstraint layoutConstraint : layoutConstraints) { if (layoutConstraint != null && layoutConstraint.getElement() != null) { // Do not persist an element twice. if (em.contains(layoutConstraint.getElement())) { continue; } //Initialize export flags of flexible element layoutConstraint.getElement().initializeExportFlags(); // If the current element is a QuestionElement if (layoutConstraint.getElement() instanceof QuestionElement) { List<QuestionChoiceElement> questionChoiceElements = ((QuestionElement) layoutConstraint .getElement()).getChoices(); CategoryType type = ((QuestionElement) layoutConstraint.getElement()) .getCategoryType(); if (questionChoiceElements != null || type != null) { FlexibleElement parent = (FlexibleElement) layoutConstraint.getElement(); ((QuestionElement) parent).setChoices(null); ((QuestionElement) parent).setCategoryType(null); em.persist(parent); // Save QuestionChoiceElement with their // QuestionElement parent(saved above) if (questionChoiceElements != null) { for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) { if (questionChoiceElement != null) { questionChoiceElement.setId(null); questionChoiceElement.setParentQuestion((QuestionElement) parent); CategoryElement categoryElement = questionChoiceElement .getCategoryElement(); if (categoryElement != null) { questionChoiceElement.setCategoryElement(null); em.persist(questionChoiceElement); saveProjectModelCategoryElement(categoryElement, em, modelesReset, modelesImport); questionChoiceElement.setCategoryElement(categoryElement); em.merge(questionChoiceElement); } else { em.persist(questionChoiceElement); } } } // Set saved QuestionChoiceElement to // QuestionElement parent and update it ((QuestionElement) parent).setChoices(questionChoiceElements); } // Save the Category type of QuestionElement // parent(saved above) if (type != null) { if (em.find(CategoryType.class, type.getId()) == null) { List<CategoryElement> typeElements = type.getElements(); if (typeElements != null) { type.setElements(null); em.merge(type); for (CategoryElement element : typeElements) { if (em.find(CategoryElement.class, element.getId()) == null) { element.setParentType(type); saveProjectModelCategoryElement(element, em, modelesReset, modelesImport); } } type.setElements(typeElements); em.merge(type); } } // Set the saved CategoryType to // QuestionElement parent and update it ((QuestionElement) parent).setCategoryType(type); } // Update the QuestionElement parent em.merge(parent); } else { em.persist(layoutConstraint.getElement()); } } // Report element else if (layoutConstraint.getElement() instanceof ReportElement) { final ReportElement element = (ReportElement) layoutConstraint.getElement(); final ProjectReportModel oldModel = element.getModel(); if (oldModel != null) { final int oldModelId = oldModel.getId(); final ProjectReportModel newModel; if (!reportModelsId.contains(oldModelId)) { oldModel.resetImport(new HashMap<Object, Object>(), new HashSet<Object>()); oldModel.setOrganization(authentication.getUser().getOrganization()); newModel = oldModel; ProjectReportModelHandler.saveProjectReportModelElement(newModel, em); em.persist(newModel); element.setModel(newModel); em.persist(element); reportModelsId.add(element.getModel().getId()); } // If the report model has been already // saved, it is re-used. else { newModel = em.find(ProjectReportModel.class, oldModelId); element.setModel(newModel); em.persist(element); } } } // Reports list element else if (layoutConstraint.getElement() instanceof ReportListElement) { final ReportListElement element = (ReportListElement) layoutConstraint.getElement(); final ProjectReportModel oldModel = element.getModel(); if (oldModel != null) { final int oldModelId = oldModel.getId(); final ProjectReportModel newModel; if (!reportModelsId.contains(oldModelId)) { oldModel.resetImport(new HashMap<Object, Object>(), new HashSet<Object>()); oldModel.setOrganization(authentication.getUser().getOrganization()); newModel = oldModel; ProjectReportModelHandler.saveProjectReportModelElement(newModel, em); em.persist(newModel); element.setModel(newModel); em.persist(element); reportModelsId.add(element.getModel().getId()); } // If the report model has been already // saved, it is re-used. else { newModel = em.find(ProjectReportModel.class, oldModelId); element.setModel(newModel); em.persist(element); } } } // Others elements else { em.persist(layoutConstraint.getElement()); } } } } } } }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
private void processRemovedManyToMany(ObjectsToPersist toPersist, Map<com.hiperf.common.ui.shared.util.Id, INakedObject> res, Map<Object, IdHolder> newIdByOldId, EntityManager em) throws ClassNotFoundException, IntrospectionException, PersistenceException, IllegalAccessException, InvocationTargetException, NoSuchFieldException { Map<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>>> manyToManyRemoved = toPersist .getManyToManyRemovedByClassName(); if (manyToManyRemoved != null && !manyToManyRemoved.isEmpty()) { for (Entry<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>>> e : manyToManyRemoved .entrySet()) {//from w w w . j a va2s . co m String className = e.getKey(); Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>> map = e .getValue(); if (map != null && !map.isEmpty()) { Class<?> clazz = Class.forName(className); for (Entry<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>> entry : map .entrySet()) { com.hiperf.common.ui.shared.util.Id id = entry.getKey(); Map<String, List<com.hiperf.common.ui.shared.util.Id>> m = entry.getValue(); if (m != null && !m.isEmpty()) { Object objId = id.getFieldValues().get(0); if (newIdByOldId.containsKey(objId)) objId = newIdByOldId.get(objId).getId(); Object o = em.find(clazz, objId); if (o != null) { PropertyDescriptor[] pds = propertyDescriptorsByClassName.get(className); for (Entry<String, List<com.hiperf.common.ui.shared.util.Id>> ee : m.entrySet()) { String attr = ee.getKey(); List<com.hiperf.common.ui.shared.util.Id> ll = ee.getValue(); if (ll != null && !ll.isEmpty()) { Collection coll = null; Class classInColl = null; PropertyDescriptor myPd = null; for (PropertyDescriptor pd : pds) { if (pd.getName().equals(attr)) { myPd = pd; coll = (Collection) pd.getReadMethod().invoke(o, StorageService.emptyArg); break; } } if (coll != null) { ParameterizedType genericType = (ParameterizedType) clazz .getDeclaredField(myPd.getName()).getGenericType(); if (genericType != null) { for (Type t : genericType.getActualTypeArguments()) { if (t instanceof Class && INakedObject.class.isAssignableFrom((Class) t)) { classInColl = (Class) t; break; } } } for (com.hiperf.common.ui.shared.util.Id i : ll) { Object idObj = i.getFieldValues().get(0); if (newIdByOldId.containsKey(idObj)) idObj = newIdByOldId.get(idObj); Object linkedObj = em.find(classInColl, idObj); coll.remove(linkedObj); } } } } res.put(id, (INakedObject) em.merge(o)); } } } } } } }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
private void processAddedManyToMany(ObjectsToPersist toPersist, Map<com.hiperf.common.ui.shared.util.Id, INakedObject> res, Map<Object, IdHolder> newIdByOldId, EntityManager em) throws ClassNotFoundException, IntrospectionException, PersistenceException, IllegalAccessException, InvocationTargetException, NoSuchFieldException { Map<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>>> manyToManyAdded = toPersist .getManyToManyAddedByClassName(); if (manyToManyAdded != null && !manyToManyAdded.isEmpty()) { for (Entry<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>>> e : manyToManyAdded .entrySet()) {/*from w w w.j a v a 2s . c om*/ String className = e.getKey(); Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>> map = e .getValue(); if (map != null && !map.isEmpty()) { Class<?> clazz = Class.forName(className); for (Entry<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>> entry : map .entrySet()) { com.hiperf.common.ui.shared.util.Id id = entry.getKey(); Map<String, List<com.hiperf.common.ui.shared.util.Id>> m = entry.getValue(); if (m != null && !m.isEmpty()) { Object objId = id.getFieldValues().get(0); if (newIdByOldId.containsKey(objId)) objId = newIdByOldId.get(objId).getId(); Object o = em.find(clazz, objId); if (o != null) { PropertyDescriptor[] pds = propertyDescriptorsByClassName.get(className); for (Entry<String, List<com.hiperf.common.ui.shared.util.Id>> ee : m.entrySet()) { String attr = ee.getKey(); List<com.hiperf.common.ui.shared.util.Id> ll = ee.getValue(); if (ll != null && !ll.isEmpty()) { Collection coll = null; Class classInColl = null; PropertyDescriptor myPd = null; String mappedBy = null; for (PropertyDescriptor pd : pds) { if (pd.getName().equals(attr)) { myPd = pd; coll = (Collection) pd.getReadMethod().invoke(o, StorageService.emptyArg); if (coll == null) { if (List.class.isAssignableFrom(pd.getPropertyType())) coll = new ArrayList(); else coll = new HashSet(); pd.getWriteMethod().invoke(o, coll); } ManyToMany ann = pd.getReadMethod().getAnnotation(ManyToMany.class); if (ann == null) { ann = clazz.getDeclaredField(pd.getName()) .getAnnotation(ManyToMany.class); } if (ann != null) { mappedBy = ann.mappedBy(); } break; } } if (coll != null) { ParameterizedType genericType = (ParameterizedType) clazz .getDeclaredField(myPd.getName()).getGenericType(); if (genericType != null) { for (Type t : genericType.getActualTypeArguments()) { if (t instanceof Class && INakedObject.class.isAssignableFrom((Class) t)) { classInColl = (Class) t; break; } } } for (com.hiperf.common.ui.shared.util.Id i : ll) { Object idObj = i.getFieldValues().get(0); if (newIdByOldId.containsKey(idObj)) idObj = newIdByOldId.get(idObj).getId(); Object linkedObj = em.find(classInColl, idObj); if (mappedBy == null || mappedBy.length() == 0) coll.add(linkedObj); else { PropertyDescriptor[] pds2 = propertyDescriptorsByClassName .get(classInColl.getName()); if (pds2 == null) { pds2 = propertyDescriptorsByClassName .get(classInColl.getName()); } for (PropertyDescriptor pd : collectionsByClassName .get(classInColl.getName())) { if (pd.getName().equals(mappedBy)) { Collection coll2 = (Collection) pd.getReadMethod() .invoke(linkedObj, StorageService.emptyArg); if (coll2 == null) { if (List.class .isAssignableFrom(pd.getPropertyType())) coll2 = new ArrayList(); else coll2 = new HashSet(); pd.getWriteMethod().invoke(linkedObj, coll2); } coll2.add(o); } } em.merge(linkedObj); } if (linkedObj instanceof INakedObject) res.put(i, (INakedObject) linkedObj); } } } } res.put(id, (INakedObject) em.merge(o)); } } } } } } }