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 BusinessDetail saveBusiness(SaveBusiness body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();
    if (!body.getBusinessEntity().isEmpty()) {
        log.debug("Inbound save business request for key " + body.getBusinessEntity().get(0).getBusinessKey());
    }//  ww  w  .  j  av  a 2s  .c  o m
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

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

        ValidatePublish validator = new ValidatePublish(publisher);
        validator.validateSaveBusiness(em, body, null);

        BusinessDetail result = new BusinessDetail();

        List<org.uddi.api_v3.BusinessEntity> apiBusinessEntityList = body.getBusinessEntity();
        for (org.uddi.api_v3.BusinessEntity apiBusinessEntity : apiBusinessEntityList) {

            org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity();

            MappingApiToModel.mapBusinessEntity(apiBusinessEntity, modelBusinessEntity);

            setOperationalInfo(em, modelBusinessEntity, publisher);

            em.persist(modelBusinessEntity);

            result.getBusinessEntity().add(apiBusinessEntity);
        }

        //check how many business this publisher owns.
        validator.validateSaveBusinessMax(em);

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.SAVE_BUSINESS, QueryStatus.SUCCESS, procTime);

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

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

/**
 * Creates an AnnotationStatus that specifies another AnnotationStatus
 * @param label/* w  w  w. j  a  va 2  s .c o  m*/
 * @param comment
 * @param father
 * @return
 */
public boolean createAnnotationStatusChild(String label, String comment, String color, AnnotationStatus father,
        JSONArray descripteur) {
    label = StringOp.deleteBlanks(label);
    if (!StringOp.isNull(label)) {
        comment = StringOp.deleteBlanks(comment);
        AnnotationStatus _as = new AnnotationStatus();
        _as.setComment(comment);
        _as.setLabel(label);
        _as.setFather(father);
        _as.setDescripteur(descripteur);
        _as.setColor(color);
        //   EntityManagerFactory emf = this.setEMF();
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            if (father.getId() != null) {
                AnnotationStatus _synchro_father = em.find(AnnotationStatus.class, father.getId());
                if (_synchro_father != null)
                    _as.setFather(_synchro_father);
            }
            em.persist(_as);
            tx.commit();
            //      em.close();
            return true;
        } catch (Exception e) {
            System.out
                    .println("[CreateAnnotationStatus.createAnnotationStatus] fails to create AnnotationStatus"
                            + " label : " + label + " comment : " + comment + " cause : " + e.getMessage());
            tx.rollback();
            //   em.close();
            return false;
        }
    } else {
        System.out.println("[CreateAnnotationStatus.createAnnotationStatus] unable to persist AnnotationStatus"
                + " not a valid label : " + label);
        return false;
    }
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.entitymanagers.LexiconBuilderController.java

/**
 * Sets the provided document and all tokens contained therein as having been seen.
 * @param em the {@link EntityManager} to use.
 * @param document the {@link LexiconBuilderDocument} object to mark as seen.
 * @param seenTags a delimited list of POS tags to mark as seen.
 * @return the supplied {@link LexiconBuilderDocument}.
 *//*w  w w .j  av  a2  s  . c  om*/
public LexiconBuilderDocument setSeenDocument(EntityManager em, LexiconBuilderDocument document,
        String seenTags) {
    Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em");
    Validate.notNull(document, CannedMessages.NULL_ARGUMENT, "document");
    Validate.notNull(document.getStore(), CannedMessages.NULL_ARGUMENT, "document.store");
    Validate.notNull(document.getBaseDocument(), CannedMessages.NULL_ARGUMENT, "document.baseDocument");

    document.setSeen(true);

    if (document.getBaseDocument() instanceof FullTextDocument
            && document.getStore() instanceof LexiconBuilderDocumentStore) {
        List<LexiconDocument> seenTokens = this.getSeenTokens(em,
                (LexiconBuilderDocumentStore) document.getStore());
        FullTextDocument ftDoc = (FullTextDocument) document.getBaseDocument();
        for (final LinguisticToken token : ftDoc.getParsedContent().getTokens()) {
            if (seenTags != null && !token.getPosTag().is(seenTags)) {
                continue;
            }

            LexiconDocument seenToken = Iterables.find(seenTokens, new Predicate<LexiconDocument>() {
                @Override
                public boolean apply(LexiconDocument seenToken) {
                    return seenToken.getContent().equalsIgnoreCase(token.toString());
                }
            }, null);

            if (seenToken == null) {
                seenToken = (LexiconDocument) new LexiconDocument().setContent(token.toString())
                        .setStore(document.getStore());

                em.persist(seenToken);
            }
        }
    }

    if (em.contains(document)) {
        em.refresh(document);
    } else {
        em.persist(document);
    }

    return document;
}

From source file:nl.b3p.viewer.admin.stripes.LayoutManagerActionBean.java

public Resolution saveApplicationLayout() {
    try {// w w w .j a  v a  2  s  .c om
        EntityManager em = Stripersist.getEntityManager();
        JSONObject jsonLayout = new JSONObject(layout);

        for (Iterator it = jsonLayout.keys(); it.hasNext();) {
            String key = (String) it.next();
            JSONObject layoutItem = jsonLayout.getJSONObject(key);
            if (layoutItem.has("components")) {
                JSONArray layoutItemComponents = layoutItem.getJSONArray("components");
                for (int i = 0; i < layoutItemComponents.length(); i++) {
                    JSONObject layoutComponent = layoutItemComponents.getJSONObject(i);
                    String compName = layoutComponent.getString("name");
                    String compClassName = layoutComponent.getString("componentClass");
                    Query q = em.createQuery(
                            "from ConfiguredComponent where application = :application and name = :name")
                            .setParameter("application", application).setParameter("name", compName);
                    // Check if the component is already saved. If not, return error
                    try {
                        q.getSingleResult();
                    } catch (NoResultException nre) {
                        ConfiguredComponent cc = new ConfiguredComponent();
                        cc.setClassName(compClassName);
                        cc.setName(compName);
                        cc.setApplication(application);
                        em.persist(cc);
                    }
                }
            }
        }

        application.setLayout(layout);
        application.setGlobalLayout(globalLayout);
        // Remove legacy properties to clean old apps
        application.removeOldProperties();
        em.persist(application);
        em.getTransaction().commit();
    } catch (JSONException ex) {
        Logger.getLogger(LayoutManagerActionBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    return new ForwardResolution("/WEB-INF/jsp/application/layoutmanager.jsp");
}

From source file:uk.ac.edukapp.service.WidgetProfileService.java

public boolean addActivity(Widgetprofile widgetProfile, String body) {
    EntityManager entityManager = getEntityManagerFactory().createEntityManager();

    entityManager.getTransaction().begin();

    // check if activity exists
    int activity_id = Integer.parseInt(body);
    Activity activity = entityManager.find(Activity.class, activity_id);

    if (activity == null) {
        logger.error("error - activity with id:" + activity_id + " does not exist");
        return false;
    }/*from   ww  w  .j  a v  a2 s  . c  o m*/

    List<Activity> widget_activities = widgetProfile.getActivities();

    boolean contains = false;
    for (Activity a : widget_activities) {
        if (a.getActivitytext().equals(activity.getActivitytext()) && (a.getId() == activity.getId())) {
            contains = true;
        }
    }

    if (contains) {
        logger.warn("Widget:" + widgetProfile.getId() + " already has activity:" + activity.getActivitytext());
        return false;
    } else {
        widget_activities.add(activity);
    }

    entityManager.persist(entityManager.merge(widgetProfile));
    entityManager.getTransaction().commit();
    entityManager.close();
    return true;
}

From source file:com.jada.admin.customAttribute.CustomAttributeGroupMaintAction.java

public ActionForward resequence(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Throwable {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    CustomAttributeGroupMaintActionForm form = (CustomAttributeGroupMaintActionForm) actionForm;

    JSONEscapeObject jsonResult = new JSONEscapeObject();
    jsonResult.put("status", Constants.WEBSERVICE_STATUS_SUCCESS);

    MessageResources resources = this.getResources(request);
    Vector<JSONEscapeObject> errors = new Vector<JSONEscapeObject>();
    String seqNums[] = form.getSeqNums();
    if (seqNums != null) {
        String customAttribDetailIds[] = form.getCustomAttribDetailIds();
        for (int i = 0; i < seqNums.length; i++) {
            if (!Format.isInt(seqNums[i])) {
                JSONEscapeObject object = new JSONEscapeObject();
                object.put("customAttribDetailId", customAttribDetailIds[i]);
                object.put("error", resources.getMessage("error.int.invalid"));
                errors.add(object);/*w ww  . ja va 2  s  .c  o m*/
            }
        }
        if (errors.size() > 0) {
            jsonResult.put("validations", errors);
            streamWebService(response, jsonResult.toHtmlString());
            return null;
        }

        for (int i = 0; i < customAttribDetailIds.length; i++) {
            CustomAttributeDetail customAttributeDetail = (CustomAttributeDetail) em
                    .find(CustomAttributeDetail.class, Format.getLong(customAttribDetailIds[i]));
            customAttributeDetail.setSeqNum(Format.getInt(seqNums[i]));
            em.persist(customAttributeDetail);
        }
    }

    streamWebService(response, jsonResult.toHtmlString());
    return null;
}

From source file:BO.UserHandler.java

public boolean addFriend(VUser u) {
    EntityManager em;
    EntityManagerFactory emf;//  ww  w.  j av  a 2s  .  c  om
    emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
    em = emf.createEntityManager();

    try {
        em.getTransaction().begin();
        System.out.println(u.getEmail());
        System.out.println(u.getFriendToAdd());

        try {
            List<Friendship> f = (List<Friendship>) em
                    .createQuery("SELECT f from Friendship f WHERE f.receivingFriend.email LIKE :email1 "
                            + "AND f.sendingFriend.email LIKE :email2")
                    .setParameter("email1", u.getEmail()).setParameter("email2", u.getFriendToAdd())
                    .getResultList();
            if (!f.isEmpty()) {
                return false;
            }
        } catch (Exception e) {

        }

        try {

            List<Friendship> f = (List<Friendship>) em
                    .createQuery("SELECT f from Friendship f WHERE f.sendingFriend.email LIKE :email1 "
                            + "AND f.receivingFriend.email LIKE :email2")
                    .setParameter("email1", u.getEmail()).setParameter("email2", u.getFriendToAdd())
                    .getResultList();
            if (!f.isEmpty()) {
                return false;
            }
        } catch (Exception e) {

        }

        User sender = getUserByEmail(u.getEmail());
        User receiver = getUserByEmail(u.getFriendToAdd());

        Friendship friendship = new Friendship(sender, receiver);
        em.persist(friendship);
        em.flush();
        em.getTransaction().commit();
        return true;
    } catch (Exception e) {
        return false;
    } finally {
        if (em != null) {
            em.close();
        }
        emf.close();
    }
}

From source file:org.apache.juddi.v3.auth.HTTPContainerAuthenticator.java

@Override
public UddiEntityPublisher identify(String authInfoNotused, String authorizedNameNotused, WebServiceContext ctx)
        throws AuthenticationException, FatalErrorException {
    int MaxBindingsPerService = -1;
    int MaxServicesPerBusiness = -1;
    int MaxTmodels = -1;
    int MaxBusinesses = -1;
    try {/*ww  w.  ja  va 2s  .  c om*/
        MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE,
                -1);
        MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS,
                -1);
        MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1);
        MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1);
    } catch (Exception ex) {
        MaxBindingsPerService = -1;
        MaxServicesPerBusiness = -1;
        MaxTmodels = -1;
        MaxBusinesses = -1;
        log.error("config exception! ", ex);
    }
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        String user = null;
        if (ctx == null)
            throw new UnknownUserException(
                    new ErrorMessage("errors.auth.NoPublisher", "no web service context!"));
        if (ctx.getUserPrincipal() != null) {
            user = ctx.getUserPrincipal().getName();
        }
        if (user == null) {
            MessageContext mc = ctx.getMessageContext();
            HttpServletRequest req = null;
            if (mc != null) {
                req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
            }
            if (req != null && req.getUserPrincipal() != null) {
                user = req.getUserPrincipal().getName();
            }
        }
        if (user == null || user.length() == 0) {
            throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher"));
        }
        tx.begin();
        Publisher publisher = em.find(Publisher.class, user);
        if (publisher == null) {
            log.warn("Publisher \"" + user
                    + "\" was not found in the database, adding the publisher in on the fly.");
            publisher = new Publisher();
            publisher.setAuthorizedName(user);
            publisher.setIsAdmin("false");
            publisher.setIsEnabled("true");
            publisher.setMaxBindingsPerService(MaxBindingsPerService);
            publisher.setMaxBusinesses(MaxBusinesses);
            publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness);
            publisher.setMaxTmodels(MaxTmodels);
            publisher.setPublisherName("Unknown");
            em.persist(publisher);
            tx.commit();
        }

        return publisher;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

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

/**
 * Adds client subscription information. This effectively links a server to
 * serverr subscription to clerk//from  w w  w  .  j a v  a  2s.  co  m
 * Administrative privilege required.
 * @param body
 * @return ClientSubscriptionInfoDetail
 * @throws DispositionReportFaultMessage
 * @throws RemoteException 
 */
public ClientSubscriptionInfoDetail saveClientSubscriptionInfo(SaveClientSubscriptionInfo body)
        throws DispositionReportFaultMessage, RemoteException {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

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

        new ValidateClientSubscriptionInfo(publisher).validateSaveClientSubscriptionInfo(em, body);

        ClientSubscriptionInfoDetail result = new ClientSubscriptionInfoDetail();

        List<org.apache.juddi.api_v3.ClientSubscriptionInfo> apiClientSubscriptionInfoList = body
                .getClientSubscriptionInfo();
        for (org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo : apiClientSubscriptionInfoList) {

            org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = new org.apache.juddi.model.ClientSubscriptionInfo();

            MappingApiToModel.mapClientSubscriptionInfo(apiClientSubscriptionInfo, modelClientSubscriptionInfo);

            Object existingUddiEntity = em.find(modelClientSubscriptionInfo.getClass(),
                    modelClientSubscriptionInfo.getSubscriptionKey());
            if (existingUddiEntity != null) {
                em.remove(existingUddiEntity);
            }

            em.persist(modelClientSubscriptionInfo);

            result.getClientSubscriptionInfo().add(apiClientSubscriptionInfo);
        }

        tx.commit();
        return result;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:org.sigmah.server.servlet.exporter.models.OrgUnitModelHandler.java

/**
 * Save the flexible elements of imported organizational unit model
 * /*from  w w  w  . ja v  a2  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 = 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());
                            }
                        }
                    }
                }
            }
        }
    }
}