Search in sources :

Example 21 with Item

use of gov.usgs.cida.coastalhazards.model.Item in project coastal-hazards by USGS-CIDA.

the class ItemManager method persistAll.

public synchronized boolean persistAll(List<Item> items) throws CycleIntroductionException {
    boolean worked = false;
    EntityTransaction transaction = em.getTransaction();
    try {
        transaction.begin();
        for (Item item : items) {
            persistItem(item);
        }
        transaction.commit();
        worked = true;
    } catch (Exception ex) {
        log.debug("Exception during save", ex);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        if (ex instanceof CycleIntroductionException) {
            throw ex;
        }
    }
    fixEnabledStatus();
    return worked;
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) Item(gov.usgs.cida.coastalhazards.model.Item) CycleIntroductionException(gov.usgs.cida.coastalhazards.exception.CycleIntroductionException) BadRequestException(gov.usgs.cida.coastalhazards.exception.BadRequestException) CycleIntroductionException(gov.usgs.cida.coastalhazards.exception.CycleIntroductionException) PersistenceException(javax.persistence.PersistenceException)

Example 22 with Item

use of gov.usgs.cida.coastalhazards.model.Item in project coastal-hazards by USGS-CIDA.

the class ItemManager method mergeAll.

public synchronized boolean mergeAll(List<Item> items) throws CycleIntroductionException {
    boolean worked = false;
    EntityTransaction transaction = em.getTransaction();
    try {
        transaction.begin();
        for (Item item : items) {
            mergeItem(item);
        }
        transaction.commit();
        worked = true;
    } catch (Exception ex) {
        log.debug("Exception during save", ex);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        if (ex instanceof CycleIntroductionException) {
            throw ex;
        }
    }
    fixEnabledStatus();
    return worked;
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) Item(gov.usgs.cida.coastalhazards.model.Item) CycleIntroductionException(gov.usgs.cida.coastalhazards.exception.CycleIntroductionException) BadRequestException(gov.usgs.cida.coastalhazards.exception.BadRequestException) CycleIntroductionException(gov.usgs.cida.coastalhazards.exception.CycleIntroductionException) PersistenceException(javax.persistence.PersistenceException)

Example 23 with Item

use of gov.usgs.cida.coastalhazards.model.Item in project coastal-hazards by USGS-CIDA.

the class ItemManager method query.

/**
 * Query the database for items and return it as a json string
 *
 * @param queryText keywords to query on
 * @param types item types to include in results
 * @param sortBy sort the results according to this technique
 * @param count max items to return (TODO paging)
 * @param bbox search bounding box (TODO fix this)
 * @param subtree whether to return entire subtree for aggregated items
 * @param showDisabled whether to include disabled items in the search
 * @return JSON result of items
 */
public String query(List<String> queryText, List<String> types, String sortBy, int count, String bbox, boolean subtree, boolean showDisabled) {
    StringBuilder builder = new StringBuilder();
    List<String> queryParams = new LinkedList<>();
    int paramIndex = 1;
    builder.append("select i from Item i where (i.enabled = true");
    // show disabled means return enable == true and false, so 1=1, narrow it down if !showDisabled
    if (showDisabled) {
        builder.append(" or i.enabled = false)");
    } else {
        // exclude uber
        builder.append(") and i.id != '").append(Item.UBER_ID).append("'");
    }
    boolean hasQueryText = isEmpty(queryText);
    boolean hasType = isEmpty(types);
    List<Item.Type> typesList = new LinkedList<>();
    List<String> idsInBboxList = new LinkedList<>();
    if (hasQueryText || hasType) {
        if (hasQueryText) {
            builder.append(" and (");
            List<String> likes = new ArrayList<>();
            for (String keyword : queryText) {
                if (StringUtils.isNotBlank(keyword)) {
                    queryParams.add('%' + keyword + "%");
                    StringBuilder likeBuilder = new StringBuilder();
                    likeBuilder.append(" lower(i.summary.keywords) like lower(?").append(paramIndex).append(")");
                    likeBuilder.append(" or lower(i.summary.full.title) like lower(?").append(paramIndex).append(")");
                    likes.add(likeBuilder.toString());
                    paramIndex++;
                }
            }
            builder.append(StringUtils.join(likes, " or")).append(")");
        }
        if (hasType) {
            builder.append(" and");
            for (String type : types) {
                typesList.add(Item.Type.valueOf(type));
            }
            builder.append(" i.type in(:types)");
        }
    }
    // }
    if (StringUtils.isNotBlank(bbox)) {
        String[] split = bbox.split(",");
        if (split.length != 4) {
            throw new BadRequestException();
        }
        double minX = Double.parseDouble(split[0]);
        double minY = Double.parseDouble(split[1]);
        double maxX = Double.parseDouble(split[2]);
        double maxY = Double.parseDouble(split[3]);
        // Beware, changing database will cause this to fail but will not be caught by hibernate
        Query bboxQuery = em.createNativeQuery("SELECT item.id FROM item, bbox WHERE item.bbox_id=bbox.id AND ST_Intersects(bbox.bbox, ST_MakeBox2D(ST_Point(:minx, :miny), ST_Point(:maxx, :maxy)))");
        bboxQuery.setParameter("minx", minX);
        bboxQuery.setParameter("miny", minY);
        bboxQuery.setParameter("maxx", maxX);
        bboxQuery.setParameter("maxy", maxY);
        List<Object> results = bboxQuery.getResultList();
        for (Object result : results) {
            if (result instanceof String) {
                idsInBboxList.add((String) result);
            } else {
                throw new IllegalStateException("ID should be a string");
            }
        }
        builder.append(" and i.id in(:bboxIds)");
    }
    String jsonResult;
    Query query = em.createQuery(builder.toString(), Item.class);
    for (int i = 0; i < queryParams.size(); i++) {
        String param = queryParams.get(i);
        query.setParameter(i + 1, param);
    }
    if (hasType) {
        query.setParameter("types", typesList);
    }
    if (StringUtils.isNotBlank(bbox)) {
        if (idsInBboxList.isEmpty()) {
            query.setParameter("bboxIds", "EMPTY");
        } else {
            query.setParameter("bboxIds", idsInBboxList);
        }
    }
    if (count > 0) {
        query.setMaxResults(count);
    }
    List<Item> resultList = query.getResultList();
    Map<String, Object> resultMap = new HashMap<>();
    resultMap.put("subtree", subtree);
    resultMap.put("items", resultList);
    if (subtree) {
        jsonResult = GsonUtil.getSubtreeGson().toJson(resultMap, HashMap.class);
    } else {
        jsonResult = GsonUtil.getIdOnlyGson().toJson(resultMap, HashMap.class);
    }
    return jsonResult;
}
Also used : Query(javax.persistence.Query) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) Item(gov.usgs.cida.coastalhazards.model.Item) BadRequestException(gov.usgs.cida.coastalhazards.exception.BadRequestException)

Example 24 with Item

use of gov.usgs.cida.coastalhazards.model.Item in project coastal-hazards by USGS-CIDA.

the class ItemManager method delete.

public boolean delete(String itemId) {
    boolean deleted = false;
    EntityTransaction transaction = em.getTransaction();
    try {
        Item item = em.find(Item.class, itemId);
        mergeAll(updateAncestors(item));
        // Delete Dependant Items then delete item
        if (deleteDependants(itemId)) {
            transaction.begin();
            em.remove(item);
            transaction.commit();
            deleted = true;
        } else {
            throw new Exception("Failed to delete dependant objects for " + itemId);
        }
        fixEnabledStatus();
    } catch (Exception ex) {
        log.debug("Transaction failed on delete of item " + itemId, ex);
        if (transaction.isActive()) {
            transaction.rollback();
        }
    }
    return deleted;
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) Item(gov.usgs.cida.coastalhazards.model.Item) BadRequestException(gov.usgs.cida.coastalhazards.exception.BadRequestException) CycleIntroductionException(gov.usgs.cida.coastalhazards.exception.CycleIntroductionException) PersistenceException(javax.persistence.PersistenceException)

Example 25 with Item

use of gov.usgs.cida.coastalhazards.model.Item in project coastal-hazards by USGS-CIDA.

the class ItemManager method delete.

public boolean delete(String itemId, boolean deleteChildren) {
    boolean deleted = false;
    if (isOrphan(itemId)) {
        Item item = load(itemId);
        List<Item> children = new ArrayList<>();
        if (item.getChildren() != null && item.getChildren().size() > 0) {
            children = new ArrayList<>(item.getChildren());
        }
        deleted = delete(itemId);
        if (deleted) {
            if (deleteChildren) {
                for (Item child : children) {
                    if (isOrphan(child)) {
                        deleted = delete(child.getId(), true);
                        if (!deleted) {
                            log.error("An error occured while deleting child " + child.getId() + " of " + itemId + ". Remaining children will be orphaned.");
                            break;
                        }
                    }
                }
            }
        }
    }
    return deleted;
}
Also used : Item(gov.usgs.cida.coastalhazards.model.Item) ArrayList(java.util.ArrayList)

Aggregations

Item (gov.usgs.cida.coastalhazards.model.Item)60 ItemManager (gov.usgs.cida.coastalhazards.jpa.ItemManager)26 Response (javax.ws.rs.core.Response)24 Path (javax.ws.rs.Path)22 LinkedList (java.util.LinkedList)21 GET (javax.ws.rs.GET)20 Produces (javax.ws.rs.Produces)20 HashMap (java.util.HashMap)16 BadRequestException (gov.usgs.cida.coastalhazards.exception.BadRequestException)12 Summary (gov.usgs.cida.coastalhazards.model.summary.Summary)12 JsonObject (com.google.gson.JsonObject)10 ArrayList (java.util.ArrayList)10 Viewable (org.glassfish.jersey.server.mvc.Viewable)10 Gson (com.google.gson.Gson)9 Service (gov.usgs.cida.coastalhazards.model.Service)8 NotFoundException (javax.ws.rs.NotFoundException)8 Test (org.junit.Test)8 JsonElement (com.google.gson.JsonElement)7 StatusManager (gov.usgs.cida.coastalhazards.jpa.StatusManager)7 Status (gov.usgs.cida.coastalhazards.model.util.Status)7