Example usage for javax.persistence EntityManager isOpen

List of usage examples for javax.persistence EntityManager isOpen

Introduction

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

Prototype

public boolean isOpen();

Source Link

Document

Determine whether the entity manager is open.

Usage

From source file:de.zib.gndms.dspace.service.SubspaceServiceImpl.java

@Override
@RequestMapping(value = "/_{subspace}/config", method = RequestMethod.PUT)
@Secured("ROLE_ADMIN")
public ResponseEntity<Void> setSubspaceConfiguration(@PathVariable final String subspace,
        @RequestBody final Configuration config, @RequestHeader("DN") final String dn) {

    GNDMSResponseHeader headers = getSubspaceHeaders(subspace, dn);

    try {//from  www  .  jav  a  2  s  .c  om
        SubspaceConfiguration subspaceConfig = SubspaceConfiguration.checkSubspaceConfig(config);

        if (!subspaceProvider.exists(subspace) || subspaceConfig.getMode() != SetupMode.UPDATE) {
            logger.warn("Subspace " + subspace + " cannot be updated");
            return new ResponseEntity<Void>(null, headers, HttpStatus.FORBIDDEN);
        }
        final EntityManager em = emf.createEntityManager();
        TxFrame tx = new TxFrame(em);

        try {

            SetupSubspaceAction action = new SetupSubspaceAction(subspaceConfig);
            action.setOwnEntityManager(em);
            logger.info("Calling action for updating the supspace " + subspace + ".");

            action.call();
        } finally {
            tx.finish();
            if (em != null && em.isOpen()) {
                em.close();
            }
        }
        return new ResponseEntity<Void>(null, headers, HttpStatus.OK);
    } catch (WrongConfigurationException e) {
        logger.warn(e.getMessage());
        return new ResponseEntity<Void>(null, headers, HttpStatus.BAD_REQUEST);
    }
}

From source file:de.zib.gndms.infra.system.GNDMSystemDirectory.java

@SuppressWarnings({ "MethodWithTooExceptionsDeclared" })
@NotNull//from  ww  w .ja v a 2s.c  om
public AbstractORQCalculator<?, ?> newORQCalculator(final @NotNull EntityManagerFactory emf,
        final @NotNull String offerTypeKey) throws ClassNotFoundException, IllegalAccessException,
        InstantiationException, NoSuchMethodException, InvocationTargetException {
    EntityManager em = emf.createEntityManager();
    try {
        OfferType type = em.find(OfferType.class, offerTypeKey);
        if (type == null)
            throw new IllegalArgumentException("Unknow offer type: " + offerTypeKey);
        AbstractORQCalculator<?, ?> orqc = orqPark.getInstance(type);
        orqc.setConfigletProvider(this);
        return orqc;
    } finally {
        if (!em.isOpen())
            em.close();
    }
}

From source file:de.zib.gndms.dspace.service.SubspaceServiceImpl.java

@Override
@RequestMapping(value = "/_{subspaceId}", method = RequestMethod.DELETE)
@Secured("ROLE_ADMIN")
public ResponseEntity<Specifier<Facets>> deleteSubspace(@PathVariable final String subspaceId,
        @RequestHeader("DN") final String dn) {
    GNDMSResponseHeader headers = getSubspaceHeaders(subspaceId, dn);

    if (!subspaceProvider.exists(subspaceId)) {
        logger.warn("Subspace " + subspaceId + " not found");
        return new ResponseEntity<Specifier<Facets>>(null, headers, HttpStatus.NOT_FOUND);
    }/*from   w  ww .ja  v  a2  s  .c o  m*/

    final EntityManager em = emf.createEntityManager();
    TxFrame tx = new TxFrame(em);
    try {
        final Taskling taskling = subspaceProvider.delete(subspaceId);

        final TaskClient client = new TaskClient(localBaseUrl);
        client.setRestTemplate(restTemplate);
        final Specifier<Facets> spec = TaskClient.TaskServiceAux.getTaskSpecifier(client, taskling.getId(),
                uriFactory, null, dn);
        return new ResponseEntity<Specifier<Facets>>(spec, headers, HttpStatus.OK);
    } catch (NoSuchElementException e) {
        return new ResponseEntity<Specifier<Facets>>(null, headers, HttpStatus.NOT_FOUND);
    } finally {
        tx.finish();
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}

From source file:com.tesora.dve.common.catalog.CatalogDAO.java

public void close() {
    EntityManager theEm = em.getAndSet(null);
    if (theEm != null && theEm.isOpen())
        theEm.close();
}

From source file:de.zib.gndms.dspace.service.SliceServiceImpl.java

@Override
@RequestMapping(value = "/_{subspaceId}/_{sliceKindId}/_{sliceId}", method = RequestMethod.POST)
@Secured("ROLE_USER")
public ResponseEntity<Specifier<Void>> transformSlice(@PathVariable final String subspaceId,
        @PathVariable final String sliceKindId, @PathVariable final String sliceId,
        @RequestBody final Specifier<Void> newSliceKind, @RequestHeader("DN") final String dn) {
    GNDMSResponseHeader headers = setHeaders(subspaceId, sliceKindId, sliceId, dn);

    try {/*ww  w  . j a v a 2s  .  co m*/
        Slice slice = findSliceOfKind(subspaceId, sliceKindId, sliceId);

        SliceKind newSliceK = sliceKindProvider.get(subspaceId, newSliceKind.getUrl());
        Subspace space = subspaceProvider.get(subspaceId);

        EntityManager em = emf.createEntityManager();
        TxFrame tx = new TxFrame(em);
        try {
            // TODO is this right? what is this uuid generator (last entry)?
            TransformSliceAction action = new TransformSliceAction(dn, slice.getTerminationTime(), newSliceK,
                    space, slice.getTotalStorageSize(), null);
            action.setOwnEntityManager(em);
            logger.info("Calling action for transforming sliceId " + sliceId + ".");
            action.call();
            tx.commit();
        } finally {
            tx.finish();
            if (em != null && em.isOpen()) {
                em.close();
            }
        }

        Specifier<Void> spec = new Specifier<Void>();

        HashMap<String, String> urimap = new HashMap<String, String>(2);
        urimap.put("service", "dspace");
        urimap.put(UriFactory.SUBSPACE, subspaceId);
        urimap.put(UriFactory.SLICE_KIND, sliceKindId);
        urimap.put(UriFactory.SLICE, sliceId);
        spec.setUriMap(new HashMap<String, String>(urimap));
        spec.setUrl(uriFactory.quoteUri(urimap));

        return new ResponseEntity<Specifier<Void>>(spec, headers, HttpStatus.OK);
    } catch (NoSuchElementException ne) {
        logger.warn(ne.getMessage());
        return new ResponseEntity<Specifier<Void>>(null, headers, HttpStatus.NOT_FOUND);
    }
}

From source file:de.zib.gndms.infra.system.GNDMSystem.java

/**
 * Returns a list of all {@link org.globus.wsrf.Resource}s, which are managed by an EntityManager, corresponding to
 * the given EntityManagerFactory and//from  w  w w  .  j  a v  a 2 s  .  c o  m
 * which are managed by the {@code GNDMPersistentServiceHome} {@link de.zib.gndms.infra.system.GNDMSystemDirectory#getHome(Class)}    
 *
 * @param emg the factory to create the EntityManager, used for the {@code list all} query
 * @param clazz the class, whose corresponding GNDMPersistentServiceHome will be used for the query.(See {@link de.zib.gndms.infra.system.GNDMSystemDirectory#homes})
 * @param <M> the model type
 * @return  a list of all {@code Resources}, corresponding to a specific EntityManager and GNDMPersistentServiceHome.
 */
public final @NotNull <M extends GridResource> List<String> listAllResources(
        final @NotNull EntityManagerFactory emg, final @NotNull Class<M> clazz) {
    final EntityManager manager = emg.createEntityManager();
    List<String> retList = null;
    try {
        try {
            manager.getTransaction().begin();
            retList = listAllResources(getInstanceDir().getHome(clazz), manager);
            manager.getTransaction().commit();
        } finally {
            if (manager.getTransaction().isActive())
                manager.getTransaction().rollback();
        }
    } finally {
        if (manager.isOpen())
            manager.close();
    }
    return retList;
}

From source file:de.zib.gndms.infra.system.GNDMSystem.java

/**
 * Refreshes all resources corresponding to a specific GNDMPersistentServiceHome
 * @param home the GNDMPersistentServiceHome,whose Resource will be refreshed
 * @param <M>  the model type//from   w ww  .  j  a  va2  s.  c om
 */
@SuppressWarnings({ "ConstantConditions" })
public final <M extends GridResource> void refreshAllResources(
        final @NotNull GNDMPersistentServiceHome<M> home) {
    final EntityManager manager = home.getEntityManagerFactory().createEntityManager();
    try {
        try {
            manager.getTransaction().begin();
            for (String id : listAllResources(home, manager)) {
                try {
                    if (isDebugging())
                        logger.debug("Restoring " + home.getNickName() + ':' + id);
                    home.find(home.getKeyForId(id));
                } catch (ResourceException e) {
                    logger.warn(e);
                }
            }
            manager.getTransaction().commit();
        } finally {
            if (manager.getTransaction().isActive())
                manager.getTransaction().rollback();
        }
    } finally {
        if (manager.isOpen())
            manager.close();
    }
}

From source file:com.jada.admin.AdminLookupDispatchAction.java

protected ActionForward process(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response, String name) {
    ActionForward forward = null;//  w ww .  j a v a  2  s .com

    AdminBean adminBean = getAdminBean(request);
    if (adminBean == null) {
        Cookie cookies[] = request.getCookies();
        if (cookies == null) {
            return actionMapping.findForward("sessionexpire");
        }
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals(Constants.SESSION_COOKIE_USER)) {
                return actionMapping.findForward("sessionexpire");
            }
        }
        return actionMapping.findForward("login");
    }

    EntityManager em = null;
    try {
        em = JpaConnection.getInstance().getCurrentEntityManager();
        em.getTransaction().begin();

        if (actionMapping instanceof AdminActionMapping) {
            AdminActionMapping adminMapping = (AdminActionMapping) actionMapping;
            String userTypes = adminMapping.getUserTypes();
            String tokens[] = userTypes.split(",");
            User user = adminBean.getUser();
            String userType = user.getUserType();
            boolean found = false;
            for (int i = 0; i < tokens.length; i++) {
                if (userType.equals(tokens[i])) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new com.jada.admin.SecurityException(
                        "user " + user.getUserId() + " is blocked from accessing " + actionMapping.getPath());
            }
        }

        logger.debug("RequestURL  > " + request.getRequestURL());
        logger.debug("QueryString > " + request.getQueryString());
        if (Utility.getLogLevel(logger).equals(Level.DEBUG)) {
            logger.debug("Request Information ...");
            Enumeration<?> enumeration = request.getParameterNames();
            while (enumeration.hasMoreElements()) {
                String key = (String) enumeration.nextElement();
                String line = "";
                line += "key=" + key + " value=";
                String values[] = request.getParameterValues(key);
                for (int i = 0; i < values.length; i++) {
                    if (i > 0) {
                        line += ",";
                    }
                    line += "[" + values[i] + "]";
                }
                logger.debug(line);
            }
        }
        AdminMaintActionForm form = (AdminMaintActionForm) actionForm;
        forward = customProcess(actionMapping, form, request, response, name);

        em = JpaConnection.getInstance().getCurrentEntityManager();
        if (em.isOpen()) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().commit();
            }
        }
        if (form != null) {
            if (form.isStream) {
                streamWebService(response, form.getStreamData());
            } else {
                encodeForm(form);
            }
        }

    } catch (Throwable e) {
        logger.error("Exception encountered in " + actionMapping.getName());
        logger.error("Exception", e);
        if (e instanceof com.jada.admin.SecurityException) {
            forward = actionMapping.findForward("securityException");
        } else {
            forward = actionMapping.findForward("exception");
        }
    } finally {
        try {
            em = JpaConnection.getInstance().getCurrentEntityManager();
            if (em.isOpen()) {
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
            }
            em.close();
        } catch (Throwable e1) {
            logger.error("Could not rollback transaction after exception!", e1);
        }
    }
    return forward;
}

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

private void closeEntityManager(EntityManager em) {
    if (em != null && em.isOpen())
        close(em);
}

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

@Override
public EntityManager getEntityManager() {
    EntityManager em = emByThread.get();

    if (em == null || !em.isOpen()) {
        em = emf.createEntityManager();/*from  www.jav  a  2  s .c  o m*/
        em.setFlushMode(FlushModeType.COMMIT);
        emByThread.set(em);
    }
    return em;
}