Example usage for javax.persistence EntityManager find

List of usage examples for javax.persistence EntityManager find

Introduction

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

Prototype

public <T> T find(Class<T> entityClass, Object primaryKey);

Source Link

Document

Find by primary key.

Usage

From source file:fr.xebia.demo.wicket.blog.service.GenericService.java

public void delete(T entity) throws ServiceException {
    try {/*from w w  w.  jav a  2  s.com*/
        EntityManager entityManager = currentEntityManager();
        entityManager.getTransaction().begin();

        Serializable objectId = getObjectId(entity);
        if (objectId == null) {
            throw new ServiceException("Entity has no id");
        }
        T loadedEntity = entityManager.find(getObjectClass(), objectId);
        if (loadedEntity == null) {
            throw new ServiceException("Entity referenced by id " + objectId + " does not exist");
        }
        entityManager.remove(loadedEntity);

        commitTransaction();
    } catch (PersistenceException e) {
        logger.error(e.getCause(), e);
        rollbackTransaction();
        throw new ServiceException("Can't delete object", e);
    } finally {
        closeEntityManager();
    }
}

From source file:org.opencastproject.scheduler.impl.persistence.SchedulerServiceDatabaseImpl.java

@Override
public void deleteEvent(long eventId) throws NotFoundException, SchedulerServiceDatabaseException {
    EntityManager em = null;
    EntityTransaction tx = null;//from  w ww  . j a va  2  s  . co m
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        EventEntity entity = em.find(EventEntity.class, eventId);
        if (entity == null) {
            throw new NotFoundException("Event with ID " + eventId + " does not exist");
        }
        em.remove(entity);
        tx.commit();
    } catch (Exception e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        if (e instanceof NotFoundException) {
            throw (NotFoundException) e;
        }
        logger.error("Could not delete series: {}", e.getMessage());
        throw new SchedulerServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.apache.oozie.service.JPAService.java

/**
 * Initializes the {@link JPAService}.//  ww  w .  j  a  va  2 s.  co  m
 *
 * @param services services instance.
 */
public void init(Services services) throws ServiceException {
    LOG = XLog.getLog(JPAService.class);
    Configuration conf = services.getConf();
    String dbSchema = ConfigurationService.get(conf, CONF_DB_SCHEMA);
    String url = ConfigurationService.get(conf, CONF_URL);
    String driver = ConfigurationService.get(conf, CONF_DRIVER);
    String user = ConfigurationService.get(conf, CONF_USERNAME);
    String password = ConfigurationService.getPassword(conf, CONF_PASSWORD).trim();
    String maxConn = ConfigurationService.get(conf, CONF_MAX_ACTIVE_CONN).trim();
    String dataSource = ConfigurationService.get(conf, CONF_CONN_DATA_SOURCE);
    String connPropsConfig = ConfigurationService.get(conf, CONF_CONN_PROPERTIES);
    String brokerImplConfig = ConfigurationService.get(conf, CONF_OPENJPA_BROKER_IMPL);
    boolean autoSchemaCreation = ConfigurationService.getBoolean(conf, CONF_CREATE_DB_SCHEMA);
    boolean validateDbConn = ConfigurationService.getBoolean(conf, CONF_VALIDATE_DB_CONN);
    String evictionInterval = ConfigurationService.get(conf, CONF_VALIDATE_DB_CONN_EVICTION_INTERVAL).trim();
    String evictionNum = ConfigurationService.get(conf, CONF_VALIDATE_DB_CONN_EVICTION_NUM).trim();

    if (!url.startsWith("jdbc:")) {
        throw new ServiceException(ErrorCode.E0608, url, "invalid JDBC URL, must start with 'jdbc:'");
    }
    String dbType = url.substring("jdbc:".length());
    if (dbType.indexOf(":") <= 0) {
        throw new ServiceException(ErrorCode.E0608, url,
                "invalid JDBC URL, missing vendor 'jdbc:[VENDOR]:...'");
    }
    dbType = dbType.substring(0, dbType.indexOf(":"));

    String persistentUnit = "oozie-" + dbType;

    // Checking existince of ORM file for DB type
    String ormFile = "META-INF/" + persistentUnit + "-orm.xml";
    try {
        IOUtils.getResourceAsStream(ormFile, -1);
    } catch (IOException ex) {
        throw new ServiceException(ErrorCode.E0609, dbType, ormFile);
    }

    // support for mysql replication urls "jdbc:mysql:replication://master:port,slave:port[,slave:port]/db"
    if (url.startsWith("jdbc:mysql:replication")) {
        url = "\"".concat(url).concat("\"");
        LOG.info("A jdbc replication url is provided. Url: [{0}]", url);
    }

    String connProps = "DriverClassName={0},Url={1},Username={2},Password={3},MaxActive={4}";
    connProps = MessageFormat.format(connProps, driver, url, user, password, maxConn);
    Properties props = new Properties();
    if (autoSchemaCreation) {
        connProps += ",TestOnBorrow=false,TestOnReturn=false,TestWhileIdle=false";
        props.setProperty("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)");
    } else if (validateDbConn) {
        // validation can be done only if the schema already exist, else a
        // connection cannot be obtained to create the schema.
        String interval = "timeBetweenEvictionRunsMillis=" + evictionInterval;
        String num = "numTestsPerEvictionRun=" + evictionNum;
        connProps += ",TestOnBorrow=true,TestOnReturn=true,TestWhileIdle=true," + interval + "," + num;
        connProps += ",ValidationQuery=select count(*) from VALIDATE_CONN";
        connProps = MessageFormat.format(connProps, dbSchema);
    } else {
        connProps += ",TestOnBorrow=false,TestOnReturn=false,TestWhileIdle=false";
    }
    if (connPropsConfig != null) {
        connProps += "," + connPropsConfig;
    }
    props.setProperty("openjpa.ConnectionProperties", connProps);

    props.setProperty("openjpa.ConnectionDriverName", dataSource);
    if (!StringUtils.isEmpty(brokerImplConfig)) {
        props.setProperty("openjpa.BrokerImpl", brokerImplConfig);
        LOG.info("Setting openjpa.BrokerImpl to {0}", brokerImplConfig);
    }

    factory = Persistence.createEntityManagerFactory(persistentUnit, props);

    EntityManager entityManager = getEntityManager();
    entityManager.find(WorkflowActionBean.class, 1);
    entityManager.find(WorkflowJobBean.class, 1);
    entityManager.find(CoordinatorActionBean.class, 1);
    entityManager.find(CoordinatorJobBean.class, 1);
    entityManager.find(SLAEventBean.class, 1);
    entityManager.find(JsonSLAEvent.class, 1);
    entityManager.find(BundleJobBean.class, 1);
    entityManager.find(BundleActionBean.class, 1);
    entityManager.find(SLARegistrationBean.class, 1);
    entityManager.find(SLASummaryBean.class, 1);

    LOG.info(XLog.STD, "All entities initialized");
    // need to use a pseudo no-op transaction so all entities, datasource
    // and connection pool are initialized one time only
    entityManager.getTransaction().begin();
    OpenJPAEntityManagerFactorySPI spi = (OpenJPAEntityManagerFactorySPI) factory;
    // Mask the password with '***'
    String logMsg = spi.getConfiguration().getConnectionProperties().replaceAll("Password=.*?,",
            "Password=***,");
    LOG.info("JPA configuration: {0}", logMsg);
    entityManager.getTransaction().commit();
    entityManager.close();
    try {
        CodecFactory.initialize(conf);
    } catch (Exception ex) {
        throw new ServiceException(ErrorCode.E0100, getClass().getName(), ex);
    }
}

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

public ActionForward create(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();

    Date startDate = reportingDate.parse((String) dynaForm.get("startDate"));
    Date endDate = reportingDate.parse((String) dynaForm.get("endDate"));
    String xsl = (String) dynaForm.get("xsl");
    String name = (String) dynaForm.get("name");

    Integer organizationId = (Integer) dynaForm.get("organizationId");
    Organization organization = (Organization) em.find(Organization.class, organizationId);
    Map parameterMap = new HashMap();
    parameterMap.put("organization", organization);
    parameterMap.put("endDate", endDate);
    parameterMap.put("startDate", startDate);
    parameterMap.put("xsl", xsl);
    parameterMap.put("name", name);

    // TODO via gui opvragen
    if (xsl == null || xsl.length() == 0) {
        parameterMap.put("type", CastorXmlTransformer.XML);
    } else {/*from  ww w.java 2s.  c  om*/
        parameterMap.put("type", CastorXmlTransformer.HTML);
    }

    parameterMap.put("users", organization.getMainUsers());

    ReportThread rtt = new ReportThread();
    rtt.init(parameterMap);
    rtt.start();

    dynaForm.initialize(mapping);
    prepareMethod(dynaForm, request, EDIT, LIST);
    addDefaultMessage(mapping, request, ACKNOWLEDGE_MESSAGES);
    return getDefaultForward(mapping, request);
}

From source file:org.opencastproject.scheduler.impl.persistence.SchedulerServiceDatabaseImpl.java

@Override
public void updateEvent(DublinCoreCatalog event) throws NotFoundException, SchedulerServiceDatabaseException {
    if (event == null) {
        throw new SchedulerServiceDatabaseException("Cannot update <null> event");
    }//  w  ww  .  j a v  a2  s. c  o m
    Long eventId = Long.parseLong(event.getFirst(DublinCore.PROPERTY_IDENTIFIER));
    String dcXML;
    try {
        dcXML = serializeDublinCore(event);
    } catch (Exception e1) {
        logger.error("Could not serialize Dublin Core: {}", e1);
        throw new SchedulerServiceDatabaseException(e1);
    }
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        EventEntity entity = em.find(EventEntity.class, eventId);
        if (entity == null) {
            throw new NotFoundException("Event with ID " + eventId + " does not exist.");
        }
        entity.setEventDublinCore(dcXML);
        em.merge(entity);
        tx.commit();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        logger.error("Could not store event: {}", e.getMessage());
        throw new SchedulerServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }

}

From source file:org.opencastproject.scheduler.impl.persistence.SchedulerServiceDatabaseImpl.java

@Override
public void updateEventWithMetadata(long eventId, Properties caProperties)
        throws SchedulerServiceDatabaseException, NotFoundException {
    if (caProperties == null) {
        caProperties = new Properties();
    }/*  w w w.  j  av a 2s .co m*/
    String caSerialized;
    try {
        caSerialized = serializeProperties(caProperties);
    } catch (IOException e) {
        logger.error("Could not serialize properties: {}", e);
        throw new SchedulerServiceDatabaseException(e);
    }
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        EventEntity entity = em.find(EventEntity.class, eventId);
        if (entity == null) {
            throw new NotFoundException("Event with ID: " + eventId + " does not exist");
        }
        entity.setCaptureAgentMetadata(caSerialized);
        em.merge(entity);
        tx.commit();
    } catch (NotFoundException e) {
        logger.error("Event with ID '{}' does not exist", eventId);
        throw e;
    } catch (Exception e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        logger.error("Could not store event metadata: {}", e.getMessage());
        throw new SchedulerServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

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

@After(on = { "addSubcategory", "saveCategory",
        "removeCategory" }, stages = LifecycleStage.BindingAndValidation)
public void loadCategory() {
    EntityManager em = Stripersist.getEntityManager();

    if (nodeId != null) {
        // Demangle id
        Long id;//from w  w  w .  java 2s. com
        if (nodeId.equals("0")) {
            id = 0L;
        } else {
            id = Long.parseLong(nodeId.substring(1));
        }

        category = em.find(Category.class, id);
    }
}

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

private void setOperationalInfo(EntityManager em, org.apache.juddi.model.Tmodel uddiEntity,
        UddiEntityPublisher publisher) throws DispositionReportFaultMessage {

    uddiEntity.setAuthorizedName(publisher.getAuthorizedName());

    Date now = new Date();
    uddiEntity.setModified(now);/* w w  w .  jav a2s.  c om*/
    uddiEntity.setModifiedIncludingChildren(now);

    uddiEntity.setNodeId(nodeId);

    org.apache.juddi.model.Tmodel existingUddiEntity = em.find(uddiEntity.getClass(),
            uddiEntity.getEntityKey());
    if (existingUddiEntity != null)
        uddiEntity.setCreated(existingUddiEntity.getCreated());
    else
        uddiEntity.setCreated(now);

    if (existingUddiEntity != null)
        em.remove(existingUddiEntity);

}

From source file:org.apache.juddi.replication.ReplicationNotifier.java

@Deprecated
private Node getNode(String messageSender) {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = null;/* w  w  w  . jav  a  2s .  c  o  m*/
    try {
        tx = em.getTransaction();
        tx.begin();
        Node api = new Node();
        org.apache.juddi.model.Node find = em.find(org.apache.juddi.model.Node.class, messageSender);
        if (find != null) {
            MappingModelToApi.mapNode(find, api);
        }
        tx.commit();
        return api;
    } catch (Exception ex) {
        log.error("error", ex);
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
    } finally {
        em.close();
    }
    return null;
}

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

@SuppressWarnings("unchecked")
public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body)
        throws DispositionReportFaultMessage {
    try {//from  w  w w .  ja v  a2  s  . co m
        JAXBContext context = JAXBContext.newInstance(body.getClass());
        Marshaller marshaller = context.createMarshaller();
        StringWriter sw = new StringWriter();
        marshaller.marshal(body, sw);

        logger.info("Notification received by UDDISubscriptionListenerService : " + sw.toString());

        @SuppressWarnings("rawtypes")
        NotificationList nl = NotificationList.getInstance();
        nl.getNotifications().add(sw.toString());

        org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo = null;

        //find the clerks to go with this subscription
        EntityManager em = PersistenceManager.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();

            this.getEntityPublisher(em, body.getAuthInfo());
            String subscriptionKey = body.getSubscriptionResultsList().getSubscription().getSubscriptionKey();
            org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = null;
            try {
                modelClientSubscriptionInfo = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class,
                        subscriptionKey);
            } catch (ClassCastException e) {
            }
            if (modelClientSubscriptionInfo == null) {
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.SubscripKeyNotFound", subscriptionKey));
            }
            apiClientSubscriptionInfo = new org.apache.juddi.api_v3.ClientSubscriptionInfo();
            MappingModelToApi.mapClientSubscriptionInfo(modelClientSubscriptionInfo, apiClientSubscriptionInfo);

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

        XRegisterHelper.handle(apiClientSubscriptionInfo.getFromClerk(), apiClientSubscriptionInfo.getToClerk(),
                body.getSubscriptionResultsList());

    } catch (JAXBException jaxbe) {
        logger.error("", jaxbe);
        throw new FatalErrorException(new ErrorMessage("errors.subscriptionnotifier.client"));
    }

    new ValidateSubscriptionListener().validateNotification(body);

    DispositionReport dr = new DispositionReport();
    Result res = new Result();
    dr.getResult().add(res);
    return dr;
}