Search in sources :

Example 1 with BadRequestException

use of gov.usgs.cida.coastalhazards.exception.BadRequestException in project coastal-hazards by USGS-CIDA.

the class TreeResource method updateItemChildren.

/**
 * Updates one or more items for children and displayed children
 *
 * @return whether items were updated in the database or not
 */
private boolean updateItemChildren(Map<String, JsonObject> items) {
    List<Item> itemList = new LinkedList<>();
    boolean updated = false;
    for (Entry<String, JsonObject> entry : items.entrySet()) {
        String itemId = entry.getKey();
        JsonObject updateData = entry.getValue();
        if (updateData.has("children")) {
            Item parentItem;
            List<Item> children;
            try (ItemManager manager = new ItemManager()) {
                parentItem = manager.load(itemId);
                children = new LinkedList<>();
                log.info("Attempting to update item {}", parentItem.getId());
                // Update the item's children
                Iterator<JsonElement> iterator = updateData.get("children").getAsJsonArray().iterator();
                while (iterator.hasNext()) {
                    String childId = iterator.next().getAsString();
                    Item child = manager.load(childId);
                    children.add(child);
                }
                parentItem.setChildren(children);
                // Update the item's displayedChildren
                if (updateData.has("displayedChildren")) {
                    Iterator<JsonElement> displayedIterator = updateData.get("displayedChildren").getAsJsonArray().iterator();
                    List<String> displayedChildren = new ArrayList<>();
                    while (displayedIterator.hasNext()) {
                        String childId = displayedIterator.next().getAsString();
                        displayedChildren.add(childId);
                    }
                    parentItem.setDisplayedChildren(displayedChildren);
                }
            }
            itemList.add(parentItem);
        } else {
            log.error("Incoming JSON Object {} has no children");
            throw new BadRequestException();
        }
    }
    // in the database
    if (!itemList.isEmpty()) {
        // Update the children
        try (ItemManager manager = new ItemManager()) {
            updated = manager.mergeAll(itemList);
        }
        if (updated) {
            log.info("Updated {} items", itemList.size());
            // Update the thumbnails
            try (ThumbnailManager thumbMan = new ThumbnailManager()) {
                for (Item item : itemList) {
                    thumbMan.updateDirtyBits(item.getId());
                }
                log.debug("Updated thumbs for {} items", itemList.size());
            }
            // Update the status manager
            try (StatusManager statusMan = new StatusManager()) {
                Status status = new Status();
                status.setStatusName(Status.StatusName.STRUCTURE_UPDATE);
                if (statusMan.save(status)) {
                    log.debug("Status Manager updated structure status after items were updated.");
                } else {
                    log.warn("Status Manager did not update the structure status after updating items. This could lead to inconsistencies in the data");
                }
            } catch (Exception e) {
                log.error(e.toString());
            }
        } else {
            log.warn("Could not update {} items.", itemList.size());
        }
    }
    return updated;
}
Also used : Status(gov.usgs.cida.coastalhazards.model.util.Status) StatusManager(gov.usgs.cida.coastalhazards.jpa.StatusManager) ItemManager(gov.usgs.cida.coastalhazards.jpa.ItemManager) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) LinkedList(java.util.LinkedList) JsonSyntaxException(com.google.gson.JsonSyntaxException) BadRequestException(gov.usgs.cida.coastalhazards.exception.BadRequestException) NotFoundException(javax.ws.rs.NotFoundException) Item(gov.usgs.cida.coastalhazards.model.Item) ThumbnailManager(gov.usgs.cida.coastalhazards.jpa.ThumbnailManager) JsonElement(com.google.gson.JsonElement) BadRequestException(gov.usgs.cida.coastalhazards.exception.BadRequestException)

Example 2 with BadRequestException

use of gov.usgs.cida.coastalhazards.exception.BadRequestException in project coastal-hazards by USGS-CIDA.

the class ItemResource method postItem.

/**
 * Only allows one card to be posted at a time for now
 *
 * @param content Posted content as text string (should be JSON)
 * @param request passed through context of request
 * @return
 */
@RolesAllowed({ CoastalHazardsTokenBasedSecurityFilter.CCH_ADMIN_ROLE })
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response postItem(String content, @Context HttpServletRequest request) {
    Response response;
    Item item = Item.fromJSON(content);
    final String id;
    try (ItemManager itemManager = new ItemManager()) {
        id = itemManager.persist(item);
    }
    if (null == id) {
        throw new BadRequestException();
    } else {
        Map<String, Object> ok = new HashMap<String, Object>() {

            private static final long serialVersionUID = 2398472L;

            {
                put("id", id);
            }
        };
        response = Response.ok(GsonUtil.getDefault().toJson(ok, HashMap.class), MediaType.APPLICATION_JSON_TYPE).build();
    }
    try (StatusManager statusMan = new StatusManager();
        ThumbnailManager thumbMan = new ThumbnailManager()) {
        Status status = new Status();
        status.setStatusName(Status.StatusName.ITEM_UPDATE);
        statusMan.save(status);
        thumbMan.updateDirtyBits(id);
    }
    return response;
}
Also used : Response(javax.ws.rs.core.Response) Status(gov.usgs.cida.coastalhazards.model.util.Status) Item(gov.usgs.cida.coastalhazards.model.Item) StatusManager(gov.usgs.cida.coastalhazards.jpa.StatusManager) ThumbnailManager(gov.usgs.cida.coastalhazards.jpa.ThumbnailManager) ItemManager(gov.usgs.cida.coastalhazards.jpa.ItemManager) HashMap(java.util.HashMap) BadRequestException(gov.usgs.cida.coastalhazards.exception.BadRequestException) RolesAllowed(javax.annotation.security.RolesAllowed) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 3 with BadRequestException

use of gov.usgs.cida.coastalhazards.exception.BadRequestException 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 4 with BadRequestException

use of gov.usgs.cida.coastalhazards.exception.BadRequestException in project coastal-hazards by USGS-CIDA.

the class ItemResource method updateItem.

/**
 * @param request
 * @param id
 * @param content
 * @return
 */
@RolesAllowed({ CoastalHazardsTokenBasedSecurityFilter.CCH_ADMIN_ROLE })
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response updateItem(@Context HttpServletRequest request, @PathParam("id") String id, String content) {
    Response response = null;
    try (ItemManager itemManager = new ItemManager()) {
        Item dbItem = itemManager.load(id);
        Item updatedItem = Item.fromJSON(content);
        String trackId = null;
        // If this is a storm going from active to inactive then remove the track item
        if (dbItem.getType() == Item.Type.storms && !updatedItem.isActiveStorm() && dbItem.isActiveStorm()) {
            Integer trackIndex = null;
            // Find Track Child
            for (Item child : updatedItem.getChildren()) {
                if (child.getName().equals("track")) {
                    trackId = child.getId();
                    trackIndex = updatedItem.getChildren().indexOf(child);
                    break;
                }
            }
            // Remove Track Child
            if (trackId != null && trackIndex != null) {
                updatedItem.getChildren().remove(trackIndex.intValue());
            }
        }
        Item mergedItem = Item.copyValues(updatedItem, dbItem);
        String mergedId = null;
        if (dbItem == null) {
            mergedId = itemManager.persist(mergedItem);
        } else {
            mergedId = itemManager.merge(mergedItem);
        }
        if (null != mergedId) {
            // Delete the storm track item once the storm has been successfully saved
            if (trackId != null) {
                itemManager.delete(trackId, true);
            }
            response = Response.ok().build();
        } else {
            throw new BadRequestException();
        }
        try (StatusManager statusMan = new StatusManager();
            ThumbnailManager thumbMan = new ThumbnailManager()) {
            Status status = new Status();
            status.setStatusName(Status.StatusName.ITEM_UPDATE);
            statusMan.save(status);
            thumbMan.updateDirtyBits(id);
        }
    }
    return response;
}
Also used : Response(javax.ws.rs.core.Response) Status(gov.usgs.cida.coastalhazards.model.util.Status) Item(gov.usgs.cida.coastalhazards.model.Item) StatusManager(gov.usgs.cida.coastalhazards.jpa.StatusManager) ThumbnailManager(gov.usgs.cida.coastalhazards.jpa.ThumbnailManager) ItemManager(gov.usgs.cida.coastalhazards.jpa.ItemManager) BadRequestException(gov.usgs.cida.coastalhazards.exception.BadRequestException) Path(javax.ws.rs.Path) RolesAllowed(javax.annotation.security.RolesAllowed) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

Example 5 with BadRequestException

use of gov.usgs.cida.coastalhazards.exception.BadRequestException in project coastal-hazards by USGS-CIDA.

the class SLDGenerator method getGenerator.

public static SLDGenerator getGenerator(Item item, String selectedId, Integer ribbon) {
    SLDGenerator generator = null;
    Item.Type itemDotType = item.getType();
    Item.ItemType itemType = item.getItemType();
    if (itemType == Item.ItemType.data) {
        String itemAttribute = item.getAttr();
        Map<String, SLDConfig> typeLookup = generatorMap.get(itemDotType);
        SLDConfig conf = typeLookup.get(StringUtils.upperCase(itemAttribute));
        if (null != conf) {
            generator = new SLDGenerator(item, selectedId, ribbon, conf);
        }
    } else if (itemType == Item.ItemType.aggregation || itemType == Item.ItemType.template) {
        SortedSet<String> aggAttributes = ItemUtil.gatherAttributes(item);
        Map<String, SLDConfig> typeLookup = generatorMap.get(itemDotType);
        // TODO enforce all attributes map to same SLD type
        SLDConfig conf = typeLookup.get(StringUtils.upperCase(aggAttributes.first()));
        generator = new SLDGenerator(item, selectedId, ribbon, conf);
    } else {
        throw new BadRequestException();
    }
    if (null == generator) {
        throw new IllegalArgumentException("Type not found");
    }
    return generator;
}
Also used : Item(gov.usgs.cida.coastalhazards.model.Item) BadRequestException(gov.usgs.cida.coastalhazards.exception.BadRequestException) SortedSet(java.util.SortedSet) EnumMap(java.util.EnumMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Aggregations

BadRequestException (gov.usgs.cida.coastalhazards.exception.BadRequestException)5 Item (gov.usgs.cida.coastalhazards.model.Item)5 ItemManager (gov.usgs.cida.coastalhazards.jpa.ItemManager)3 StatusManager (gov.usgs.cida.coastalhazards.jpa.StatusManager)3 ThumbnailManager (gov.usgs.cida.coastalhazards.jpa.ThumbnailManager)3 Status (gov.usgs.cida.coastalhazards.model.util.Status)3 HashMap (java.util.HashMap)3 ArrayList (java.util.ArrayList)2 LinkedList (java.util.LinkedList)2 RolesAllowed (javax.annotation.security.RolesAllowed)2 Consumes (javax.ws.rs.Consumes)2 Response (javax.ws.rs.core.Response)2 JsonElement (com.google.gson.JsonElement)1 JsonObject (com.google.gson.JsonObject)1 JsonSyntaxException (com.google.gson.JsonSyntaxException)1 EnumMap (java.util.EnumMap)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 SortedSet (java.util.SortedSet)1 Query (javax.persistence.Query)1