Search in sources :

Example 1 with Item

use of gov.usgs.cida.coastalhazards.model.Item 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 Item

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

the class TreeResource method getRootTrees.

@GET
@Path("/item")
@Produces(MediaType.APPLICATION_JSON)
public Response getRootTrees(@Context Request request) {
    Response response = null;
    try (ItemManager itemManager = new ItemManager()) {
        List<Item> items = itemManager.loadRootItems();
        Gson treeGson = new GsonBuilder().registerTypeAdapter(Item.class, new ItemTreeAdapter()).create();
        JsonObject root = new JsonObject();
        JsonArray rootItems = new JsonArray();
        for (Item item : items) {
            rootItems.add(treeGson.toJsonTree(item));
        }
        root.add("items", rootItems);
        response = Response.ok(root.toString(), MediaType.APPLICATION_JSON_TYPE).build();
    } catch (Exception e) {
        log.error(e.toString());
    }
    return response;
}
Also used : Response(javax.ws.rs.core.Response) JsonArray(com.google.gson.JsonArray) Item(gov.usgs.cida.coastalhazards.model.Item) ItemManager(gov.usgs.cida.coastalhazards.jpa.ItemManager) GsonBuilder(com.google.gson.GsonBuilder) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) ItemTreeAdapter(gov.usgs.cida.coastalhazards.gson.adapter.ItemTreeAdapter) JsonSyntaxException(com.google.gson.JsonSyntaxException) BadRequestException(gov.usgs.cida.coastalhazards.exception.BadRequestException) NotFoundException(javax.ws.rs.NotFoundException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 3 with Item

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

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

the class MetadataResource method getMetadataSummaryByAttribtueUsingItemID.

@GET
@Path("/summarize/itemid/{itemid}/attribute/{attr}")
@Produces(MediaType.APPLICATION_JSON)
public Response getMetadataSummaryByAttribtueUsingItemID(@PathParam("itemid") String itemId, @PathParam("attr") String attr) throws URISyntaxException {
    Response response;
    try (ItemManager itemManager = new ItemManager()) {
        Item item = itemManager.load(itemId);
        String jsonSummary = MetadataUtil.getSummaryFromWPS(getMetadataUrl(item), attr);
        Summary summary = GsonUtil.getDefault().fromJson(jsonSummary, Summary.class);
        response = Response.ok(GsonUtil.getDefault().toJson(summary, Summary.class), MediaType.APPLICATION_JSON_TYPE).build();
    } catch (IOException | ParserConfigurationException | SAXException | JsonSyntaxException ex) {
        Map<String, String> err = new HashMap<>();
        err.put("message", ex.getMessage());
        response = Response.serverError().entity(GsonUtil.getDefault().toJson(err, HashMap.class)).build();
    }
    return response;
}
Also used : Response(javax.ws.rs.core.Response) Item(gov.usgs.cida.coastalhazards.model.Item) JsonSyntaxException(com.google.gson.JsonSyntaxException) ItemManager(gov.usgs.cida.coastalhazards.jpa.ItemManager) Summary(gov.usgs.cida.coastalhazards.model.summary.Summary) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) HashMap(java.util.HashMap) Map(java.util.Map) SAXException(org.xml.sax.SAXException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 5 with Item

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

the class QRCodeResource method generateQRImageUsingItemID.

/**
 * Produces a QR code that directs to back of card for a given item ID
 *
 * @param id
 * @param width
 * @param height
 * @return
 */
@GET
@Path("/info/item/{id}")
@Produces("image/png")
public Response generateQRImageUsingItemID(@PathParam("id") String id, @QueryParam("width") int width, @QueryParam("height") int height) throws IOException {
    URL url = null;
    String urlString = "ui/info/item/" + id;
    Response response;
    QRCodeGenerator qrcr = new QRCodeGenerator();
    // Make sure the item exists in the database
    try (ItemManager itemManager = new ItemManager()) {
        Item item = itemManager.load(id);
        if (item == null) {
            throw new NotFoundException();
        }
    }
    // Check if the base URL doesn't contain a trailing slash. If not, attach one to the beginning of url string
    if (BASE_URL.charAt(BASE_URL.length() - 1) != '/') {
        urlString = "/" + urlString;
    }
    // Create the URL string
    urlString = BASE_URL + urlString;
    try {
        url = new URL(urlString);
        qrcr.setUrl(url);
    } catch (MalformedURLException | URISyntaxException ex) {
        throw new ParamException.QueryParamException(ex, "URL could not be formed", "URL " + url + " could not be formed.");
    }
    if (width > 0 && height > 0) {
        if (width > MAX_WIDTH) {
            qrcr.setWidth(MAX_WIDTH);
        } else {
            qrcr.setWidth(width);
        }
        if (height > MAX_HEIGHT) {
            qrcr.setHeight(MAX_HEIGHT);
        } else {
            qrcr.setHeight(height);
        }
    }
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        qrcr.writeToOutputStream(baos);
        baos.flush();
        response = Response.ok(baos.toByteArray(), "image/png").build();
    }
    return response;
}
Also used : QRCodeGenerator(gov.usgs.cida.utilities.QRCodeGenerator) MalformedURLException(java.net.MalformedURLException) ItemManager(gov.usgs.cida.coastalhazards.jpa.ItemManager) NotFoundException(javax.ws.rs.NotFoundException) URISyntaxException(java.net.URISyntaxException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) URL(java.net.URL) Response(javax.ws.rs.core.Response) Item(gov.usgs.cida.coastalhazards.model.Item) ParamException(org.glassfish.jersey.server.ParamException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

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