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:com.enioka.jqm.tools.JobManagerHandler.java

private void shouldKill() {
    // Throttle: only peek once every 1 second.
    if (lastPeek != null && Calendar.getInstance().getTimeInMillis() - lastPeek.getTimeInMillis() < 1000L) {
        return;/*from  w  w w. ja  v  a  2 s.c  o m*/
    }

    EntityManager em = Helpers.getNewEm();
    try {
        this.ji = em.find(JobInstance.class, this.ji.getId());
        jqmlogger.trace("Analysis: should JI " + ji.getId() + " get killed? Status is " + ji.getState());
        if (ji.getState().equals(State.KILLED)) {
            jqmlogger.info("Job will be killed at the request of a user");
            Thread.currentThread().interrupt();
            throw new JqmKillException("This job" + "(ID: " + ji.getId() + ")" + " has been killed by a user");
        }
    } finally {
        em.close();
        lastPeek = Calendar.getInstance();
    }
}

From source file:nl.b3p.viewer.stripes.CycloramaActionBean.java

@DefaultHandler
public Resolution sign() throws JSONException {
    JSONObject json = new JSONObject();
    json.put("success", false);
    EntityManager em = Stripersist.getEntityManager();
    CycloramaAccount account = em.find(CycloramaAccount.class, accountId);
    if (imageId != null && account != null) {

        try {//from w w  w  .  j  a  va 2 s  .  c  om
            apiKey = "K3MRqDUdej4JGvohGfM5e78xaTUxmbYBqL0tSHsNWnwdWPoxizYBmjIBGHAhS3U1";

            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            df.setTimeZone(TimeZone.getTimeZone("GMT"));

            String date = df.format(new Date());
            String token = "X" + account.getUsername() + "&" + imageId + "&" + date + "Z";

            String privateBase64Key = account.getPrivateBase64Key();

            if (privateBase64Key == null || privateBase64Key.equals("")) {
                log.error("Kon private key voor aanmaken TID niet ophalen!");
            }

            tid = getTIDFromBase64EncodedString(privateBase64Key, token);

            json.put("tid", tid);
            json.put("imageId", imageId);
            json.put("apiKey", apiKey);
            json.put("success", true);
        } catch (Exception ex) {
            json.put("message", ex.getLocalizedMessage());
        }
    }

    // return new ForwardResolution("/WEB-INF/jsp/app/globespotter.jsp");
    return new StreamingResolution("application/json", json.toString());
}

From source file:org.noorganization.instalist.server.api.ListResource.java

/**
 * Get a list of shopping-lists./*from ww  w.ja  va2  s  .co  m*/
 * @param _groupId The id of the group, containing the lists.
 * @param _changedSince Requests only the elements that changed since the given date. ISO 8601
 *                     time e.g. 2016-01-19T11:54:07+0100
 */
@GET
@TokenSecured
@Produces({ "application/json" })
public Response getLists(@PathParam("groupid") int _groupId, @QueryParam("changedsince") String _changedSince)
        throws Exception {

    List<ShoppingList> foundLists;
    List<DeletedObject> foundDeleted;
    EntityManager manager = DatabaseHelper.getInstance().getManager();
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

    if (_changedSince != null) {
        Instant changedSince;
        try {
            changedSince = ISO8601Utils.parse(_changedSince, new ParsePosition(0)).toInstant();
        } catch (ParseException _e) {
            manager.close();
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
        }

        TypedQuery<ShoppingList> foundListsQuery = manager.createQuery(
                "select sl from " + "ShoppingList sl where sl.group = :group and sl.updated > :updated",
                ShoppingList.class);
        foundListsQuery.setParameter("group", group);
        foundListsQuery.setParameter("updated", changedSince);
        foundLists = foundListsQuery.getResultList();

        TypedQuery<DeletedObject> foundDeletedListsQuery = manager
                .createQuery("select do from" + " DeletedObject do where do.group = :group and "
                        + "do.updated > :updated and do.type = :type", DeletedObject.class);
        foundDeletedListsQuery.setParameter("group", group);
        foundDeletedListsQuery.setParameter("updated", changedSince);
        foundDeletedListsQuery.setParameter("type", DeletedObject.Type.LIST);
        foundDeleted = foundDeletedListsQuery.getResultList();
    } else {
        TypedQuery<ShoppingList> foundListsQuery = manager
                .createQuery("select sl from " + "ShoppingList sl where sl.group = :group", ShoppingList.class);
        foundListsQuery.setParameter("group", group);
        foundLists = foundListsQuery.getResultList();

        TypedQuery<DeletedObject> foundDeletedListsQuery = manager.createQuery(
                "select do " + "from DeletedObject do where do.group = :group and do.type = :type",
                DeletedObject.class);
        foundDeletedListsQuery.setParameter("group", group);
        foundDeletedListsQuery.setParameter("type", DeletedObject.Type.LIST);
        foundDeleted = foundDeletedListsQuery.getResultList();
    }
    manager.close();

    ArrayList<ListInfo> rtn = new ArrayList<ListInfo>(foundLists.size() + foundDeleted.size());
    for (ShoppingList current : foundLists) {
        ListInfo toAdd = new ListInfo();
        toAdd.setUUID(current.getUUID());
        toAdd.setName(current.getName());
        if (current.getCategory() != null)
            toAdd.setCategoryUUID(current.getCategory().getUUID());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        toAdd.setDeleted(false);
        rtn.add(toAdd);
    }
    for (DeletedObject current : foundDeleted) {
        ListInfo toAdd = new ListInfo();
        toAdd.setUUID(current.getUUID());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        toAdd.setDeleted(true);
        rtn.add(toAdd);
    }

    return ResponseFactory.generateOK(rtn);
}

From source file:com.enioka.jqm.tools.JobManagerHandler.java

private Integer addDeliverable(String path, String fileLabel) throws IOException {
    Deliverable d = null;//from   ww  w  .  j  ava 2 s .  c  om
    EntityManager em = Helpers.getNewEm();
    try {
        this.ji = em.find(JobInstance.class, ji.getId());

        String outputRoot = this.ji.getNode().getDlRepo();
        String ext = FilenameUtils.getExtension(path);
        String relDestPath = "" + ji.getJd().getApplicationName() + "/" + ji.getId() + "/" + UUID.randomUUID()
                + "." + ext;
        String absDestPath = FilenameUtils.concat(outputRoot, relDestPath);
        String fileName = FilenameUtils.getName(path);
        FileUtils.moveFile(new File(path), new File(absDestPath));
        jqmlogger.debug("A deliverable is added. Stored as " + absDestPath + ". Initial name: " + fileName);

        em.getTransaction().begin();
        d = Helpers.createDeliverable(relDestPath, fileName, fileLabel, this.ji.getId(), em);
        em.getTransaction().commit();
    } finally {
        em.close();
    }
    return d.getId();
}

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

public ActionForward delete(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();
    String[] deleteList = (String[]) dynaForm.get("deleteReport");
    for (int i = 0; i < deleteList.length; i++) {
        Integer id = FormUtils.StringToInteger(deleteList[i]);
        Report report = (Report) em.find(Report.class, id);
        if (report != null) {
            em.remove(report);/* w  ww .j a  va 2 s.  com*/
        }
        em.flush();
    }

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

From source file:org.eclipse.smila.binarystorage.persistence.jpa.JPABinaryPersistence.java

/**
 * Internal method to find a BinaryStorageDao object by id.
 *
 * @param em//  w  w  w  . j av a 2s.  c  om
 *          the EntityManager to use
 * @param id
 *          the id of the BinaryStorageDao
 * @return the RecordDao object or null
 */
private BinaryStorageDao findBinaryStorageDao(final EntityManager em, final String id) {
    return em.find(BinaryStorageDao.class, id);
}

From source file:org.nuxeo.theme.webwidgets.providers.PersistentProvider.java

public synchronized Widget getWidgetByUid(final String uid) throws ProviderException {
    Widget widget;//from www  .j  a v a 2 s  .  c  o  m
    try {
        widget = getPersistenceProvider().run(false, new RunCallback<Widget>() {
            public Widget runWith(EntityManager em) {
                Widget widget = em.find(WidgetEntity.class, Integer.valueOf(uid));
                return widget;
            }
        });
    } catch (ClientException e) {
        throw new ProviderException(e);
    }

    if (widget == null) {
        throw new ProviderException("Widget not found: " + uid);
    }
    return widget;
}

From source file:org.noorganization.instalist.server.api.EntryResource.java

/**
 * Get a list of listEntries.//from ww  w  .  ja  v a 2  s .c o m
 * @param _groupId The id of the group containing various list-entries.
 * @param _changedSince Limits the result to elements that changed since the given date. ISO
 *                      8601 time e.g. 2016-01-19T11:54:07+0100
 */
@GET
@TokenSecured
@Produces({ "application/json" })
public Response getEntries(@PathParam("groupid") int _groupId, @QueryParam("changedsince") String _changedSince)
        throws Exception {
    List<ListEntry> foundEntries;
    List<DeletedObject> foundDeleted;
    EntityManager manager = DatabaseHelper.getInstance().getManager();
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

    if (_changedSince != null) {
        Instant changedSince;
        try {
            changedSince = ISO8601Utils.parse(_changedSince, new ParsePosition(0)).toInstant();
        } catch (ParseException _e) {
            manager.close();
            return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
        }

        TypedQuery<ListEntry> foundEntriesQuery = manager.createQuery(
                "select le from " + "ListEntry le where le.group = :group and le.updated > :updated",
                ListEntry.class);
        foundEntriesQuery.setParameter("group", group);
        foundEntriesQuery.setParameter("updated", changedSince);
        foundEntries = foundEntriesQuery.getResultList();

        TypedQuery<DeletedObject> foundDeletedEntriesQuery = manager.createQuery(
                "select do " + "from DeletedObject do where do.group = :group and do.updated > :updated and "
                        + "do.type = :type",
                DeletedObject.class);
        foundDeletedEntriesQuery.setParameter("group", group);
        foundDeletedEntriesQuery.setParameter("updated", changedSince);
        foundDeletedEntriesQuery.setParameter("type", DeletedObject.Type.LISTENTRY);
        foundDeleted = foundDeletedEntriesQuery.getResultList();
    } else {
        foundEntries = new ArrayList<ListEntry>(group.getListEntries());

        TypedQuery<DeletedObject> deletedEntriesQuery = manager.createQuery(
                "select do from " + "DeletedObject do where do.group = :group and do.type = :type",
                DeletedObject.class);
        deletedEntriesQuery.setParameter("group", group);
        deletedEntriesQuery.setParameter("type", DeletedObject.Type.LISTENTRY);
        foundDeleted = deletedEntriesQuery.getResultList();
    }
    manager.close();

    ArrayList<EntryInfo> rtn = new ArrayList<EntryInfo>(foundEntries.size() + foundDeleted.size());
    for (ListEntry current : foundEntries) {
        EntryInfo toAdd = new EntryInfo().withDeleted(false);
        toAdd.setUUID(current.getUUID());
        toAdd.setProductUUID(current.getProduct().getUUID());
        toAdd.setListUUID(current.getList().getUUID());
        toAdd.setAmount(current.getAmount());
        toAdd.setPriority(current.getPriority());
        toAdd.setStruck(current.getStruck());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        rtn.add(toAdd);
    }
    for (DeletedObject current : foundDeleted) {
        EntryInfo toAdd = new EntryInfo();
        toAdd.setUUID(current.getUUID());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        toAdd.setDeleted(true);
        rtn.add(toAdd);
    }

    return ResponseFactory.generateOK(rtn);
}

From source file:org.apereo.portal.portlet.dao.jpa.JpaPortletEntityDao.java

@Override
@PortalTransactionalRequiresNew//from w  w w. j a  v a 2 s . c  o  m
public boolean portletEntityExists(IPortletEntityId portletEntityId) {
    Validate.notNull(portletEntityId, "portletEntityId can not be null");

    final EntityManager entityManager = this.getEntityManager();
    entityManager.clear();

    final long internalPortletEntityId = getNativePortletEntityId(portletEntityId);
    final PortletEntityImpl portletEntity = entityManager.find(PortletEntityImpl.class,
            internalPortletEntityId);
    return portletEntity != null;
}

From source file:com.enioka.jqm.tools.JobManagerHandler.java

private History getEndedJI(int jobId) {
    EntityManager em = Helpers.getNewEm();
    History h = null;//from   www .ja v  a 2 s.  c  om
    try {
        h = em.find(History.class, jobId);
    } catch (Exception e) {
        throw new JqmRuntimeException("Could not query history", e);
    } finally {
        em.close();
    }
    return h;
}