Example usage for javax.persistence EntityManager persist

List of usage examples for javax.persistence EntityManager persist

Introduction

In this page you can find the example usage for javax.persistence EntityManager persist.

Prototype

public void persist(Object entity);

Source Link

Document

Make an instance managed and persistent.

Usage

From source file:org.apache.juddi.api.impl.UDDIPublicationImpl.java

public void addPublisherAssertions(AddPublisherAssertions body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from w  ww.j ava2  s  .  c  om*/
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidatePublish(publisher).validateAddPublisherAssertions(em, body);

        List<org.uddi.api_v3.PublisherAssertion> apiPubAssertionList = body.getPublisherAssertion();
        for (org.uddi.api_v3.PublisherAssertion apiPubAssertion : apiPubAssertionList) {

            org.apache.juddi.model.PublisherAssertion modelPubAssertion = new org.apache.juddi.model.PublisherAssertion();

            MappingApiToModel.mapPublisherAssertion(apiPubAssertion, modelPubAssertion);

            org.apache.juddi.model.PublisherAssertion existingPubAssertion = em
                    .find(modelPubAssertion.getClass(), modelPubAssertion.getId());
            boolean persistNewAssertion = true;
            if (existingPubAssertion != null) {
                if (modelPubAssertion.getTmodelKey().equalsIgnoreCase(existingPubAssertion.getTmodelKey())
                        && modelPubAssertion.getKeyName().equalsIgnoreCase(existingPubAssertion.getKeyName())
                        && modelPubAssertion.getKeyValue()
                                .equalsIgnoreCase(existingPubAssertion.getKeyValue())) {
                    // This pub assertion is already been "asserted".  Simply need to set the "check" value on the existing (and persistent) assertion
                    if (publisher.isOwner(existingPubAssertion.getBusinessEntityByFromKey()))
                        existingPubAssertion.setFromCheck("true");
                    if (publisher.isOwner(existingPubAssertion.getBusinessEntityByToKey()))
                        existingPubAssertion.setToCheck("true");

                    persistNewAssertion = false;
                } else {
                    // Otherwise, it is a new relationship between these entities.  Remove the old one so the new one can be added.
                    // TODO: the model only seems to allow one assertion per two business (primary key is fromKey and toKey). Spec seems to imply as 
                    // many relationships as desired (the differentiator would be the keyedRef values).
                    em.remove(existingPubAssertion);
                }
            }

            if (persistNewAssertion) {
                org.apache.juddi.model.BusinessEntity beFrom = em.find(
                        org.apache.juddi.model.BusinessEntity.class, modelPubAssertion.getId().getFromKey());
                org.apache.juddi.model.BusinessEntity beTo = em.find(
                        org.apache.juddi.model.BusinessEntity.class, modelPubAssertion.getId().getToKey());
                modelPubAssertion.setBusinessEntityByFromKey(beFrom);
                modelPubAssertion.setBusinessEntityByToKey(beTo);

                modelPubAssertion.setFromCheck("false");
                modelPubAssertion.setToCheck("false");

                em.persist(modelPubAssertion);

                if (publisher.isOwner(modelPubAssertion.getBusinessEntityByFromKey()))
                    modelPubAssertion.setFromCheck("true");
                if (publisher.isOwner(modelPubAssertion.getBusinessEntityByToKey()))
                    modelPubAssertion.setToCheck("true");
            }

        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.ADD_PUBLISHERASSERTIONS, QueryStatus.SUCCESS, procTime);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.ADD_PUBLISHERASSERTIONS, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public int enqueue(JobRequest jd) {
    jqmlogger.trace("BEGINING ENQUEUE");
    EntityManager em = getEm();
    JobDef job = null;/*from   w  w  w  .  j  a  v a2  s. c  o  m*/
    try {
        job = em.createNamedQuery("HibApi.findJobDef", JobDef.class)
                .setParameter("applicationName", jd.getApplicationName()).getSingleResult();
    } catch (NoResultException ex) {
        jqmlogger.error("Job definition named " + jd.getApplicationName() + " does not exist");
        closeQuietly(em);
        throw new JqmInvalidRequestException("no job definition named " + jd.getApplicationName());
    }

    jqmlogger.trace("Job to enqueue is from JobDef " + job.getId());
    Integer hl = null;
    List<RuntimeParameter> jps = overrideParameter(job, jd, em);

    // Begin transaction (that will hold a lock in case of Highlander)
    try {
        em.getTransaction().begin();

        if (job.isHighlander()) {
            hl = highlanderMode(job, em);
        }

        if (hl != null) {
            jqmlogger.trace(
                    "JI won't actually be enqueued because a job in highlander mode is currently submitted: "
                            + hl);
            closeQuietly(em);
            return hl;
        }
        jqmlogger.trace("Not in highlander mode or no currently enqueued instance");
    } catch (Exception e) {
        closeQuietly(em);
        throw new JqmClientException("Could not do highlander analysis", e);
    }

    try {
        Queue q = job.getQueue();
        if (jd.getQueueName() != null) {
            q = em.createNamedQuery("HibApi.findQueue", Queue.class).setParameter("name", jd.getQueueName())
                    .getSingleResult();
        }

        JobInstance ji = new JobInstance();
        ji.setJd(job);

        ji.setState(State.SUBMITTED);
        ji.setQueue(q);
        ji.setNode(null);
        ji.setApplication(jd.getApplication());
        ji.setEmail(jd.getEmail());
        ji.setKeyword1(jd.getKeyword1());
        ji.setKeyword2(jd.getKeyword2());
        ji.setKeyword3(jd.getKeyword3());
        ji.setModule(jd.getModule());
        ji.setProgress(0);
        ji.setSessionID(jd.getSessionID());
        ji.setUserName(jd.getUser());

        ji.setCreationDate(Calendar.getInstance());
        if (jd.getParentID() != null) {
            ji.setParentId(jd.getParentID());
        }
        em.persist(ji);

        // There is sadly no portable and easy way to get DB time before insert... so we update afterwards.
        // Also updates the internal queue position marker (done in update and not setter to avoid full stupid JPA update).
        em.createNamedQuery("HibApi.updateJiWithDbTime").setParameter("i", ji.getId()).executeUpdate();

        for (RuntimeParameter jp : jps) {
            jqmlogger.trace("Parameter: " + jp.getKey() + " - " + jp.getValue());
            em.persist(ji.addParameter(jp.getKey(), jp.getValue()));
        }

        jqmlogger.trace("JI just created: " + ji.getId());
        em.getTransaction().commit();
        return ji.getId();
    } catch (NoResultException e) {
        throw new JqmInvalidRequestException("An entity specified in the execution request does not exist", e);
    } catch (Exception e) {
        throw new JqmClientException("Could not create new JobInstance", e);
    } finally {
        closeQuietly(em);
    }
}

From source file:de.egore911.opengate.services.PilotService.java

@POST
@Path("/register")
@Produces("application/json")
@Documentation("Register a new pilot. This will at first verify the login and email are "
        + "unique and the email is valid. After this it will register the pilot and send "
        + "and email to him to verify the address. The 'verify' will finalize the registration. "
        + "This method returns a JSON object containing a status field, i.e. {status: 'failed', "
        + "details: '...'} in case of an error and {status: 'ok', id: ...}. If an internal "
        + "error occured an HTTP 500 will be sent.")
public Response performRegister(@FormParam("login") String login, @FormParam("email") String email,
        @FormParam("faction_id") @Documentation("ID of the faction this pilot will be working for") long factionId) {
    JSONObject jsonObject = new JSONObject();
    EntityManager em = EntityManagerFilter.getEntityManager();
    Number n = (Number) em
            .createQuery("select count(pilot.key) from Pilot pilot " + "where pilot.login = (:login)")
            .setParameter("login", login).getSingleResult();
    if (n.intValue() > 0) {
        try {/*from   www  .  j  a  v  a  2s  .co m*/
            StatusHelper.failed(jsonObject, "Duplicate login");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    n = (Number) em.createQuery("select count(pilot.key) from Pilot pilot " + "where pilot.email = (:email)")
            .setParameter("email", email).getSingleResult();
    if (n.intValue() > 0) {
        try {
            StatusHelper.failed(jsonObject, "Duplicate email");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    InternetAddress recipient;
    try {
        recipient = new InternetAddress(email, login);
    } catch (UnsupportedEncodingException e1) {
        try {
            StatusHelper.failed(jsonObject, "Invalid email");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    Faction faction;
    try {
        faction = em.find(Faction.class, factionId);
    } catch (NoResultException e) {
        try {
            StatusHelper.failed(jsonObject, "Invalid faction");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e1) {
            LOG.log(Level.SEVERE, e.getMessage(), e1);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    Vessel vessel;
    try {
        vessel = (Vessel) em
                .createQuery("select vessel from Vessel vessel " + "where vessel.faction = :faction "
                        + "order by vessel.techLevel asc")
                .setParameter("faction", faction).setMaxResults(1).getSingleResult();
        // TODO assign initical equipment as well
    } catch (NoResultException e) {
        try {
            StatusHelper.failed(jsonObject, "Faction has no vessel");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e1) {
            LOG.log(Level.SEVERE, e.getMessage(), e1);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    String passwordHash;
    String password = randomText();
    try {
        passwordHash = hashPassword(password);
    } catch (NoSuchAlgorithmException e) {
        LOG.log(Level.SEVERE, e.getMessage(), e);
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }

    em.getTransaction().begin();
    try {
        Pilot pilot = new Pilot();
        pilot.setLogin(login);
        pilot.setCreated(new Date());
        pilot.setPasswordHash(passwordHash);
        pilot.setEmail(email);
        pilot.setFaction(faction);
        pilot.setVessel(vessel);
        pilot.setVerificationCode(randomText());
        em.persist(pilot);
        em.getTransaction().commit();
        try {
            // send e-mail to registered user containing the new password

            Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);

            String msgBody = "Welcome to opengate!\n\nSomeone, propably you, registered the user "
                    + pilot.getLogin()
                    + " with your e-mail adress. The following credentials can be used for your account:\n"
                    + "  login : " + pilot.getLogin() + "\n" + "  password : " + password + "\n\n"
                    + "To log into the game you need to verify your account using the following link: http://opengate-meta.appspot.com/services/pilot/verify/"
                    + pilot.getLogin() + "?verification=" + pilot.getVerificationCode();

            try {
                Message msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress("egore911@gmail.com", "Opengate administration"));
                msg.addRecipient(Message.RecipientType.TO, recipient);
                msg.setSubject("Your Example.com account has been activated");
                msg.setText(msgBody);
                Transport.send(msg);

            } catch (AddressException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            } catch (MessagingException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            } catch (UnsupportedEncodingException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }

            StatusHelper.ok(jsonObject);
            jsonObject.put("id", pilot.getKey().getId());
            jsonObject.put("vessel_id", pilot.getVessel().getKey().getId());
            // TODO properly wrap the vessel and its equipment/cargo
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    } catch (NoResultException e) {
        return Response.status(Status.FORBIDDEN).build();
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
    }
}

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.//w w w  . java 2 s .  co 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:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

@Override
public Long saveFilter(Filter f, String userName) throws PersistenceException {
    TransactionContext tc = null;/*  w w  w  . j ava 2 s .co m*/
    try {
        tc = createTransactionalContext();
        EntityManager em = tc.getEm();
        ITransaction tx = tc.getTx();
        tx.begin();
        Long id = null;
        Filter orig = null;
        if (f.getId() != null)
            orig = em.find(Filter.class, f.getId());
        if (orig != null) {
            if (orig.getValues() != null && !orig.getValues().isEmpty()) {
                for (FilterValue fv : orig.getValues()) {
                    em.remove(fv);
                }
                orig.getValues().clear();
            }
            orig.setName(f.getName());
            orig.setClassName(f.getClassName());
            orig.setViewName(f.getViewName());
            orig.setUserName(userName);
            ArrayList<FilterValue> l = new ArrayList<FilterValue>();
            orig.setValues(l);
            for (FilterValue fv : f.getValues()) {
                fv.setId(null);
                fv.setFilter(orig);
                em.persist(fv);
                l.add(fv);
            }
            if (f.getSortAttribute() != null) {
                orig.setSortAttribute(f.getSortAttribute());
                orig.setSortAsc(f.getSortAsc());
            }

            em.merge(orig);
            id = orig.getId();
        } else {
            f.setId(null);
            f.setCreateUser(userName);
            f.setUserName(userName);
            for (FilterValue fv : f.getValues())
                fv.setId(null);
            em.persist(f);
            id = f.getId();
        }

        tx.commit();
        return id;
    } catch (Exception e) {
        catchPersistException(tc, e);
        throw new PersistenceException(e.getMessage(), e);
    } finally {
        if (tc != null)
            close(tc);
    }
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

@Override
public void saveConfiguration(String viewName, String className, int nbRows, List<HeaderInfo> headers,
        ScreenLabels sl, String connectedUser, LanguageEnum language) throws PersistenceException {
    TransactionContext tc = null;/*from ww w .j a v a  2s. c o m*/
    try {
        tc = createTransactionalContext();
        EntityManager em = tc.getEm();
        ITransaction tx = tc.getTx();
        tx.begin();
        List<ScreenConfig> l = em.createQuery(
                "select o from ScreenConfig o where o.viewName = :vN and o.className = :clazz and o.createUser = :user")
                .setParameter("vN", viewName).setParameter("clazz", className)
                .setParameter("user", connectedUser).getResultList();
        ScreenConfig sc = null;
        Map<String, ScreenHeaderInfo> headerByAttribute = new HashMap<String, ScreenHeaderInfo>();
        if (l != null && !l.isEmpty()) {
            sc = l.get(0);
            if (l.size() > 1) {
                for (int i = 1; i < l.size(); i++) {
                    em.remove(l.get(i));
                }
            }
            for (ScreenHeaderInfo hi : sc.getHeaders()) {
                headerByAttribute.put(hi.getAttribute(), hi);
            }
        } else {
            sc = new ScreenConfig();
            sc.setViewName(viewName);
            sc.setClassName(className);
            sc.setCreateUser(connectedUser);
            em.persist(sc);
        }
        sc.setNbRows(nbRows);

        if (sl != null) {
            boolean found = false;
            if (sc.getLabels() != null && !sc.getLabels().isEmpty()) {
                for (ScreenLabels lb : sc.getLabels()) {
                    if (lb.getLanguage().equals(language)) {
                        if (sl.getCreateLabel() != null)
                            lb.setCreateLabel(sl.getCreateLabel());
                        if (sl.getEditLabel() != null)
                            lb.setEditLabel(sl.getEditLabel());
                        if (sl.getFormLabel() != null)
                            lb.setFormLabel(sl.getFormLabel());
                        if (sl.getSelectLabel() != null)
                            lb.setSelectLabel(sl.getSelectLabel());
                        if (sl.getTableLabel() != null)
                            lb.setTableLabel(sl.getTableLabel());
                        if (sl.getViewLabel() != null)
                            lb.setViewLabel(sl.getViewLabel());
                        em.merge(lb);
                        found = true;
                        break;
                    }
                }
            }
            if (!found) {
                sl.setScreenConfig(sc);
                em.persist(sl);
            }
        }
        for (HeaderInfo hi : headers) {
            ScreenHeaderInfo shi = headerByAttribute.get(hi.getAttribute());
            if (shi == null) {
                shi = new ScreenHeaderInfo();
                shi.setAttribute(hi.getAttribute());
                shi.setDisplayed(hi.isDisplayed());
                shi.setScreenConfig(sc);
                shi.setIndex(hi.getIndex());
                em.persist(shi);
            } else {
                shi.setDisplayed(hi.isDisplayed());
                shi.setScreenConfig(sc);
                shi.setIndex(hi.getIndex());
                em.merge(shi);
            }
            if (hi.getLabel() != null) {
                boolean found = false;
                List<Label> labels = shi.getLabels();
                if (labels != null && !labels.isEmpty()) {
                    Iterator<Label> it = labels.iterator();
                    while (it.hasNext()) {
                        Label lbl = it.next();
                        if (lbl.getLanguage().equals(language)) {
                            if (hi.getLabel().length() > 0) {
                                lbl.setLabel(hi.getLabel());
                                em.merge(lbl);
                            } else {
                                em.remove(lbl);
                                it.remove();
                            }
                            found = true;
                            break;
                        }
                    }
                }
                if (!found) {
                    Label lbl = new Label();
                    lbl.setLanguage(language);
                    lbl.setLabel(hi.getLabel());
                    lbl.setHeader(shi);
                    em.persist(lbl);
                }
            }
        }
        tx.commit();
    } catch (Exception e) {
        catchPersistException(tc, e);
        throw new PersistenceException(e.getMessage(), e);
    } finally {
        if (tc != null)
            close(tc);
    }
}

From source file:org.sparkcommerce.openadmin.server.service.persistence.module.provider.RuleFieldPersistenceProvider.java

protected boolean populateQuantityBaseRuleCollection(EntityManager em, DataDTOToMVELTranslator translator,
        String entityKey, String fieldService, String jsonPropertyValue,
        Collection<QuantityBasedRule> criteriaList, Class<?> memberType) {
    boolean dirty = false;
    if (!StringUtils.isEmpty(jsonPropertyValue)) {
        DataWrapper dw = ruleFieldExtractionUtility.convertJsonToDataWrapper(jsonPropertyValue);
        if (dw != null && StringUtils.isEmpty(dw.getError())) {
            List<QuantityBasedRule> updatedRules = new ArrayList<QuantityBasedRule>();
            for (DataDTO dto : dw.getData()) {
                if (dto.getId() != null && !CollectionUtils.isEmpty(criteriaList)) {
                    checkId: {/*from  w  w w  .j  av  a  2 s. c  om*/
                        //updates are comprehensive, even data that was not changed
                        //is submitted here
                        //Update Existing Criteria
                        for (QuantityBasedRule quantityBasedRule : criteriaList) {
                            //make compatible with enterprise module
                            Long sandBoxVersionId = sandBoxHelper.getSandBoxVersionId(em,
                                    quantityBasedRule.getClass(), dto.getId());
                            if (sandBoxVersionId == null) {
                                sandBoxVersionId = dto.getId();
                            }
                            if (sandBoxVersionId.equals(quantityBasedRule.getId())) {
                                //don't update if the data has not changed
                                if (!quantityBasedRule.getQuantity().equals(dto.getQuantity())) {
                                    quantityBasedRule.setQuantity(dto.getQuantity());
                                    dirty = true;
                                }
                                try {
                                    String mvel = ruleFieldExtractionUtility.convertDTOToMvelString(translator,
                                            entityKey, dto, fieldService);
                                    if (!quantityBasedRule.getMatchRule().equals(mvel)) {
                                        quantityBasedRule.setMatchRule(mvel);
                                        dirty = true;
                                    }
                                } catch (MVELTranslationException e) {
                                    throw new RuntimeException(e);
                                }
                                //make compatible with enterprise module
                                em.flush();
                                updatedRules.add(quantityBasedRule);
                                break checkId;
                            }
                        }
                        throw new IllegalArgumentException("Unable to update the rule of type ("
                                + memberType.getName() + ") because an update was requested for id ("
                                + dto.getId() + "), which does not exist.");
                    }
                } else {
                    //Create a new Criteria
                    QuantityBasedRule quantityBasedRule;
                    try {
                        quantityBasedRule = (QuantityBasedRule) memberType.newInstance();
                        quantityBasedRule.setQuantity(dto.getQuantity());
                        quantityBasedRule.setMatchRule(ruleFieldExtractionUtility
                                .convertDTOToMvelString(translator, entityKey, dto, fieldService));
                        if (StringUtils.isEmpty(quantityBasedRule.getMatchRule())
                                && !StringUtils.isEmpty(dw.getRawMvel())) {
                            quantityBasedRule.setMatchRule(dw.getRawMvel());
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    sandBoxHelper.setupSandBoxState(quantityBasedRule, em);
                    em.persist(quantityBasedRule);
                    criteriaList.add(quantityBasedRule);
                    updatedRules.add(quantityBasedRule);
                    dirty = true;
                }
            }
            //if an item was not included in the comprehensive submit from the client, we can assume that the
            //listing was deleted, so we remove it here.
            Iterator<QuantityBasedRule> itr = criteriaList.iterator();
            while (itr.hasNext()) {
                checkForRemove: {
                    QuantityBasedRule original = itr.next();
                    for (QuantityBasedRule quantityBasedRule : updatedRules) {
                        if (String.valueOf(original.getId())
                                .equals(String.valueOf(quantityBasedRule.getId()))) {
                            break checkForRemove;
                        }
                    }
                    sandBoxHelper.archiveObject(original, em);
                    itr.remove();
                    dirty = true;
                }
            }
        }
    }
    return dirty;
}

From source file:fr.natoine.dao.annotation.DAOAnnotation.java

/**
 * Creates an Annotation/*from w  w  w  .ja va2 s  .  co  m*/
 * @param label
 * @param context_creation
 * @param hTMLContent
 * @param access
 * @param representsResource
 * @param status
 * @param added
 * @param annotated
 * @return
 */
public boolean createAnnotation(String label, String context_creation, URI access, URI representsResource,
        AnnotationStatus status, Collection<Resource> added, Collection<Resource> annotated,
        Collection<URI> annotatedURIs, Agent _creator) {
    label = StringOp.deleteBlanks(label);
    if (!StringOp.isNull(label)) {
        Annotation _annotation = new Annotation();
        _annotation.setContextCreation(context_creation);
        _annotation.setCreation(new Date());
        _annotation.setLabel(label);
        _annotation.setAccess(access);
        _annotation.setRepresentsResource(representsResource);
        _annotation.setStatus(status);
        _annotation.setCreator(_creator);
        //_annotation.setAdded(added);
        //_annotation.setAnnotated(annotated);
        //_annotation.setAnnotatedURIs(annotatedURIs);
        //EntityManagerFactory emf = this.setEMF();
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            if (representsResource.getId() != null) {
                URI _synchro_represents_resource = em.find(URI.class, representsResource.getId());
                if (_synchro_represents_resource != null)
                    _annotation.setRepresentsResource(_synchro_represents_resource);
            }
            if (access.getId() != null) {
                URI _synchro_access = em.find(URI.class, access.getId());
                if (_synchro_access != null)
                    _annotation.setAccess(_synchro_access);
            }
            if (status.getId() != null) {
                AnnotationStatus _synchro_status = em.find(AnnotationStatus.class, status.getId());
                if (_synchro_status != null)
                    _annotation.setStatus(_synchro_status);
            }
            if (_creator != null && _creator.getId() != null) {
                Agent _synchro_agent = em.find(_creator.getClass(), _creator.getId());
                if (_synchro_agent != null)
                    _annotation.setCreator(_synchro_agent);
            }
            Collection<Resource> _synchro_added = new ArrayList<Resource>();
            for (Resource _to_add : added) {
                if (_to_add.getId() != null) {
                    Resource _synchro_to_add = em.find(_to_add.getClass(), _to_add.getId());
                    if (_synchro_to_add != null)
                        _synchro_added.add(_synchro_to_add);
                } else
                    _synchro_added.add(_to_add);
            }
            _annotation.setAdded(_synchro_added);
            Collection<Resource> _synchro_annotated = new ArrayList<Resource>();
            for (Resource _to_annotate : annotated) {
                if (_to_annotate.getId() != null) {
                    Resource _synchro_to_annotate = em.find(_to_annotate.getClass(), _to_annotate.getId());
                    if (_synchro_to_annotate != null)
                        _synchro_annotated.add(_synchro_to_annotate);
                } else
                    _synchro_annotated.add(_to_annotate);
            }
            _annotation.setAnnotated(_synchro_annotated);
            Collection<URI> synchro_annotatedURIs = new ArrayList<URI>();
            for (URI _to_annotate : annotatedURIs) {
                if (_to_annotate.getId() != null) {
                    URI _synchro_to_annotate = em.find(_to_annotate.getClass(), _to_annotate.getId());
                    if (_synchro_to_annotate != null) {
                        //empcher qu'une mme URI soit ajoute plusieurs fois  une mme annotation
                        if (!synchro_annotatedURIs.contains(_synchro_to_annotate))
                            synchro_annotatedURIs.add(_synchro_to_annotate);
                    }
                } else
                    synchro_annotatedURIs.add(_to_annotate);
            }
            _annotation.setAnnotatedURIs(synchro_annotatedURIs);
            em.persist(_annotation);
            tx.commit();
            em.close();
            return true;
        } catch (Exception e) {
            System.out.println(
                    "[CreateAnnotation.createAnnotation] fails to create annotation" + " context creation : "
                            + context_creation + " label : " + label + " cause : " + e.getMessage());
            tx.rollback();
            //em.close();
            return false;
        }
    } else {
        System.out.println("[CreateAnnotation.createAnnotation] unable to persist annotation"
                + " not a valid label : " + label);
        return false;
    }
}

From source file:nl.b3p.kaartenbalie.struts.WfsPricingAction.java

public ActionForward save(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();
    request.setAttribute("id", request.getParameter("id"));
    if (!isTokenValid(request)) {
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, TOKEN_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }/*  w  w w . j av  a 2  s  .com*/
    ActionErrors errors = dynaForm.validate(mapping, request);
    if (!errors.isEmpty()) {
        addMessages(request, errors);
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, VALIDATION_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }
    Date validFrom = FormUtils.FormStringToDate(dynaForm.getString("validFrom"), null);
    Date validUntil = FormUtils.FormStringToDate(dynaForm.getString("validUntil"), null);
    if (validUntil != null && validFrom != null) {
        if (validUntil.before(validFrom)) {
            prepareMethod(dynaForm, request, EDIT, LIST);
            addAlternateMessage(mapping, request, START_END_ERROR_KEY);
            return getAlternateForward(mapping, request);
        }
    }
    LayerPricing lp = getLayerPricing(dynaForm, request, true);
    if (lp == null) {
        prepareMethod(dynaForm, request, LIST, EDIT);
        addAlternateMessage(mapping, request, NOTFOUND_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }
    lp.setValidFrom(validFrom);
    lp.setValidUntil(validUntil);

    WfsLayer layer = null;
    String id = FormUtils.nullIfEmpty(getLayerID(dynaForm));
    if (id != null) {
        layer = getWfsLayerByUniqueName(id);
    }
    if (layer == null || layer.getName() == null || layer.getName().trim().length() == 0) {
        prepareMethod(dynaForm, request, LIST, EDIT);
        addAlternateMessage(mapping, request, LAYER_PLACEHOLDER_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }

    lp.setServerProviderPrefix(layer.getSpAbbr());
    lp.setLayerName(layer.getName());
    lp.setPlanType(FormUtils.StringToInt(dynaForm.getString("planType")));
    String service = dynaForm.getString("service");
    String operation = null;
    if (service != null && service.equalsIgnoreCase("WMS")) {
        operation = dynaForm.getString("operationWMS");
    } else if (service != null && service.equalsIgnoreCase("WFS")) {
        operation = dynaForm.getString("operationWFS");
    } else {
        service = null;
    }
    if (operation != null && operation.trim().length() == 0) {
        operation = null;
    }
    lp.setService(service);
    lp.setOperation(operation);
    BigDecimal minScale = FormUtils.bdValueNull(dynaForm.getString("minScale"));
    BigDecimal maxScale = FormUtils.bdValueNull(dynaForm.getString("maxScale"));
    String projection = dynaForm.getString("projection");
    if (projection != null && projection.trim().length() == 0) {
        projection = null;
    }
    if (projection != null && (minScale != null || maxScale != null)) {
        boolean scaleOK = false;
        if (minScale != null && minScale.doubleValue() > 0) {
            if (maxScale != null && maxScale.doubleValue() > 0) {
                if (maxScale.compareTo(minScale) > 0) {
                    scaleOK = true;
                }
            }
        }
        if (!scaleOK) {
            prepareMethod(dynaForm, request, LIST, EDIT);
            addAlternateMessage(mapping, request, SCALE_ERROR_KEY);
            return getAlternateForward(mapping, request);
        }
        if (minScale != null) {
            lp.setMinScale(minScale.setScale(2, RoundingMode.HALF_UP));
        }
        if (maxScale != null) {
            lp.setMaxScale(maxScale.setScale(2, RoundingMode.HALF_UP));
        }
        lp.setProjection(projection);
    }
    BigDecimal unitPrice = FormUtils.bdValueNull(dynaForm.getString("unitPrice"));
    /* 
     * || door && vervangen. Price is namelijk verplicht en dus nooit null
     * en hij kwam dus altijd door de check. Ook als het bedrag 0 was.
     */
    if (unitPrice != null && unitPrice.doubleValue() > 0.0) {
        lp.setUnitPrice(unitPrice.setScale(2, RoundingMode.HALF_UP));
    } else {
        lp.setLayerIsFree(Boolean.TRUE);
    }
    em.persist(lp);
    return super.save(mapping, dynaForm, request, response);
}

From source file:nl.b3p.kaartenbalie.struts.WmsPricingAction.java

public ActionForward save(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();
    request.setAttribute("id", request.getParameter("id"));
    if (!isTokenValid(request)) {
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, TOKEN_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }//from   w w w .j av a2s  .  c  o m
    ActionErrors errors = dynaForm.validate(mapping, request);
    if (!errors.isEmpty()) {
        addMessages(request, errors);
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, VALIDATION_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }
    Date validFrom = FormUtils.FormStringToDate(dynaForm.getString("validFrom"), null);
    Date validUntil = FormUtils.FormStringToDate(dynaForm.getString("validUntil"), null);
    if (validUntil != null && validFrom != null) {
        if (validUntil.before(validFrom)) {
            prepareMethod(dynaForm, request, EDIT, LIST);
            addAlternateMessage(mapping, request, START_END_ERROR_KEY);
            return getAlternateForward(mapping, request);
        }
    }
    LayerPricing lp = getLayerPricing(dynaForm, request, true);
    if (lp == null) {
        prepareMethod(dynaForm, request, LIST, EDIT);
        addAlternateMessage(mapping, request, NOTFOUND_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }
    lp.setValidFrom(validFrom);
    lp.setValidUntil(validUntil);

    Layer layer = null;
    String id = FormUtils.nullIfEmpty(getLayerID(dynaForm));
    if (id != null) {
        layer = getLayerByUniqueName(id);
    }
    if (layer == null || layer.getName() == null || layer.getName().trim().length() == 0) {
        prepareMethod(dynaForm, request, LIST, EDIT);
        addAlternateMessage(mapping, request, LAYER_PLACEHOLDER_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }
    lp.setServerProviderPrefix(layer.getSpAbbr());
    lp.setLayerName(layer.getName());
    lp.setPlanType(FormUtils.StringToInt(dynaForm.getString("planType")));
    String service = dynaForm.getString("service");
    String operation = null;
    if (service != null && service.equalsIgnoreCase("WMS")) {
        operation = dynaForm.getString("operationWMS");
    } else if (service != null && service.equalsIgnoreCase("WFS")) {
        operation = dynaForm.getString("operationWFS");
    } else {
        service = null;
    }
    if (operation != null && operation.trim().length() == 0) {
        operation = null;
    }
    lp.setService(service);
    lp.setOperation(operation);
    BigDecimal minScale = FormUtils.bdValueNull(dynaForm.getString("minScale"));
    BigDecimal maxScale = FormUtils.bdValueNull(dynaForm.getString("maxScale"));
    String projection = dynaForm.getString("projection");
    if (projection != null && projection.trim().length() == 0) {
        projection = null;
    }
    if (projection != null && (minScale != null || maxScale != null)) {
        boolean scaleOK = false;
        if (minScale != null && minScale.doubleValue() > 0) {
            if (maxScale != null && maxScale.doubleValue() > 0) {
                if (maxScale.compareTo(minScale) > 0) {
                    scaleOK = true;
                }
            }
        }
        if (!scaleOK) {
            prepareMethod(dynaForm, request, LIST, EDIT);
            addAlternateMessage(mapping, request, SCALE_ERROR_KEY);
            return getAlternateForward(mapping, request);
        }
        if (minScale != null) {
            lp.setMinScale(minScale.setScale(2, RoundingMode.HALF_UP));
        }
        if (maxScale != null) {
            lp.setMaxScale(maxScale.setScale(2, RoundingMode.HALF_UP));
        }
        lp.setProjection(projection);
    }
    BigDecimal unitPrice = FormUtils.bdValueNull(dynaForm.getString("unitPrice"));
    /* 
     * || door && vervangen. Price is namelijk verplicht en dus nooit null
     * en hij kwam dus altijd door de check. Ook als het bedrag 0 was.
     */
    if (unitPrice != null && unitPrice.doubleValue() > 0.0) {
        lp.setUnitPrice(unitPrice.setScale(2, RoundingMode.HALF_UP));
    } else {
        lp.setLayerIsFree(Boolean.TRUE);
    }
    em.persist(lp);
    prepareMethod(dynaForm, request, LIST, EDIT);
    addDefaultMessage(mapping, request, ACKNOWLEDGE_MESSAGES);
    return getDefaultForward(mapping, request);
}