Search in sources :

Example 1 with StatusManager

use of gov.usgs.cida.coastalhazards.jpa.StatusManager 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 StatusManager

use of gov.usgs.cida.coastalhazards.jpa.StatusManager 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 StatusManager

use of gov.usgs.cida.coastalhazards.jpa.StatusManager in project coastal-hazards by USGS-CIDA.

the class TemplateResource method instantiateTemplate.

@POST
@Path("/item/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@RolesAllowed({ CoastalHazardsTokenBasedSecurityFilter.CCH_ADMIN_ROLE })
public Response instantiateTemplate(@Context HttpServletRequest request, @PathParam("id") String id, String content) {
    Response response = null;
    try (ItemManager itemMan = new ItemManager();
        LayerManager layerMan = new LayerManager()) {
        Item template = itemMan.load(id);
        if (template.getItemType() != Item.ItemType.template) {
            throw new UnsupportedOperationException("Only template items may be instantiated");
        }
        List<Item> childItems = template.getChildren();
        List<Item> newItemList = null;
        List<Item> newAndOldList = null;
        List<Item> retainedItems = new LinkedList<>();
        List<String> displayed = new LinkedList<>();
        JsonParser parser = new JsonParser();
        JsonObject parsed = parser.parse(content).getAsJsonObject();
        // TODO only supporting one level for now, bring in aggs later
        boolean allAttributes = parseAllAttribute(parsed);
        boolean retainAggregations = retainAggregations(parsed);
        if (allAttributes) {
            JsonElement layer = parsed.get("layerId");
            if (layer != null) {
                String layerId = layer.getAsString();
                try {
                    newItemList = makeItemsFromLayer(template, layerId, layerMan);
                    retainedItems = findItemsToRetain(template, retainAggregations);
                    newAndOldList = new LinkedList<>(retainedItems);
                    newAndOldList.addAll(newItemList);
                } catch (IOException ex) {
                    log.error("Cannot create items", ex);
                }
                for (Item retained : retainedItems) {
                    displayed.add(retained.getId());
                }
                List<String> displayedIdByAttr = makeDisplayedChildren(newItemList);
                displayed.addAll(displayedIdByAttr);
            }
        } else {
            Map<String, Item> childMap = makeChildItemMap(childItems);
            JsonArray children = parsed.get("children").getAsJsonArray();
            newItemList = makeItemsFromDocument(template, children, childMap, itemMan, layerMan);
            List<String> visibleItems = visibleItems(children, newItemList, childMap);
            displayed.addAll(visibleItems);
            newAndOldList = newItemList;
        }
        itemMan.persistAll(newItemList);
        template.setChildren(newAndOldList);
        template.setDisplayedChildren(displayed);
        template.setSummary(gatherTemplateSummary(template.getSummary(), newItemList));
        String mergeId = itemMan.merge(template);
        if (mergeId != null) {
            response = Response.ok().build();
            try (StatusManager statusMan = new StatusManager()) {
                Status status = new Status();
                status.setStatusName(Status.StatusName.ITEM_UPDATE);
                statusMan.save(status);
            }
        } else {
            response = Response.serverError().build();
        }
    }
    return response;
}
Also used : HttpStatus(org.apache.http.HttpStatus) Status(gov.usgs.cida.coastalhazards.model.util.Status) StatusManager(gov.usgs.cida.coastalhazards.jpa.StatusManager) ItemManager(gov.usgs.cida.coastalhazards.jpa.ItemManager) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) LinkedList(java.util.LinkedList) Response(javax.ws.rs.core.Response) JsonArray(com.google.gson.JsonArray) Item(gov.usgs.cida.coastalhazards.model.Item) JsonElement(com.google.gson.JsonElement) LayerManager(gov.usgs.cida.coastalhazards.jpa.LayerManager) JsonParser(com.google.gson.JsonParser) Path(javax.ws.rs.Path) RolesAllowed(javax.annotation.security.RolesAllowed) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 4 with StatusManager

use of gov.usgs.cida.coastalhazards.jpa.StatusManager in project coastal-hazards by USGS-CIDA.

the class CacheResource method deleteCache.

@Path("/")
@DELETE
@RolesAllowed({ CoastalHazardsTokenBasedSecurityFilter.CCH_ADMIN_ROLE })
public Response deleteCache() {
    Response response = null;
    try (StatusManager statusMan = new StatusManager()) {
        if (clearCache()) {
            Status clearedStatus = new Status();
            clearedStatus.setStatusName(Status.StatusName.CACHE_CLEAR);
            statusMan.save(clearedStatus);
            response = Response.ok().build();
        } else {
            response = Response.serverError().entity("Error clearing cache").build();
        }
    } catch (Exception e) {
        log.error("Unable to clear cache", e);
        response = Response.serverError().entity("Unable to clear cache").build();
    }
    return response;
}
Also used : Response(javax.ws.rs.core.Response) Status(gov.usgs.cida.coastalhazards.model.util.Status) StatusManager(gov.usgs.cida.coastalhazards.jpa.StatusManager) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) RolesAllowed(javax.annotation.security.RolesAllowed)

Example 5 with StatusManager

use of gov.usgs.cida.coastalhazards.jpa.StatusManager in project coastal-hazards by USGS-CIDA.

the class HealthResource method healthCheck.

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response healthCheck() {
    Response response;
    boolean overallHealth = true;
    Map<String, Object> componentCheckMap = new TreeMap<>();
    try {
        EntityManagerFactory emf = JPAHelper.getEntityManagerFactory();
        boolean open = emf.isOpen();
        componentCheckMap.put("EntityManagerFactory", open);
        overallHealth = open && overallHealth;
    } catch (Exception e) {
        LOG.warn("Exception occurred while checking health", e);
        componentCheckMap.put("EntityManagerFactory", false);
        overallHealth = false;
    }
    try {
        Gson defaultGson = GsonUtil.getDefault();
        boolean ok = (defaultGson != null);
        componentCheckMap.put("DefaultGson", ok);
        overallHealth = ok && overallHealth;
    } catch (Exception e) {
        LOG.warn("Exception occurred while checking health", e);
        componentCheckMap.put("DefaultGson", false);
        overallHealth = false;
    }
    try {
        Gson idGson = GsonUtil.getIdOnlyGson();
        boolean ok = (idGson != null);
        componentCheckMap.put("NonSubtreeGson", ok);
        overallHealth = ok && overallHealth;
    } catch (Exception e) {
        LOG.warn("Exception occurred while checking health", e);
        componentCheckMap.put("NonSubtreeGson", false);
        overallHealth = false;
    }
    try {
        Gson subtreeGson = GsonUtil.getSubtreeGson();
        boolean ok = (subtreeGson != null);
        componentCheckMap.put("SubtreeGson", ok);
        overallHealth = ok && overallHealth;
    } catch (Exception e) {
        LOG.warn("Exception occurred while checking health", e);
        componentCheckMap.put("SubtreeGson", false);
        overallHealth = false;
    }
    try (ItemManager im = new ItemManager()) {
        Item uber = im.load("uber");
        boolean ok = (uber != null && uber.isEnabled());
        componentCheckMap.put("ItemManager", ok);
        overallHealth = ok && overallHealth;
    } catch (Exception e) {
        LOG.warn("Exception occurred while checking health", e);
        componentCheckMap.put("ItemManager", false);
        overallHealth = false;
    }
    try {
        Map<String, Boolean> geoserverStatus = new HashMap<>();
        GeoServerRESTReader rest = new GeoServerRESTReader(geoserverEndpoint, geoserverUser, geoserverPass);
        boolean existGeoserver = rest.existGeoserver();
        boolean workspacesConfigured = rest.getWorkspaceNames().contains("proxied");
        // TODO may want to add some more checks
        geoserverStatus.put("up", existGeoserver);
        geoserverStatus.put("configured", workspacesConfigured);
        componentCheckMap.put("Geoserver", geoserverStatus);
        overallHealth = overallHealth && existGeoserver && workspacesConfigured;
    } catch (Exception e) {
        LOG.warn("Exception occurred while checking health", e);
        componentCheckMap.put("Geoserver", false);
        overallHealth = false;
    }
    try {
        // health check add for pycsw Jira cchs-306
        boolean hasCswGetCapabilities = false;
        Map<String, Boolean> pyCswStatus = new HashMap<>();
        String endpointTest = pycswEndpoint + "?service=CSW&request=GetCapabilities&version=" + pycswVersion;
        HttpGet httpGet = new HttpGet(endpointTest);
        HttpClient httpclient = new DefaultHttpClient();
        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };
        // close anonymous inner class
        String resp = httpclient.execute(httpGet, responseHandler);
        hasCswGetCapabilities = resp != null;
        pyCswStatus.put("getCapabilities", hasCswGetCapabilities);
        componentCheckMap.put("PyCsw", pyCswStatus);
        overallHealth = overallHealth && hasCswGetCapabilities;
    } catch (Exception e) {
        LOG.warn("Exception occurred while checking csw health", e);
        componentCheckMap.put("Pycsw", false);
        overallHealth = false;
    }
    try (StatusManager statusMan = new StatusManager()) {
        // NOTE this does not effect the overall health
        boolean staleCache = false;
        Map<Status.StatusName, Status> statuses = statusMan.loadAll();
        Status itemLastUpdate = statuses.get(StatusName.ITEM_UPDATE);
        Status structureLastUpdate = statuses.get(StatusName.STRUCTURE_UPDATE);
        Status cacheClearedDate = statuses.get(StatusName.CACHE_CLEAR);
        Date itemOrStructureUpdate = null;
        if (itemLastUpdate != null) {
            itemOrStructureUpdate = itemLastUpdate.getLastUpdate();
        }
        if (structureLastUpdate != null) {
            Date structureDate = structureLastUpdate.getLastUpdate();
            if (structureDate != null && itemOrStructureUpdate != null && structureDate.after(itemOrStructureUpdate)) {
                itemOrStructureUpdate = structureDate;
            }
        }
        if (cacheClearedDate != null) {
            Date cacheDate = cacheClearedDate.getLastUpdate();
            if (cacheDate != null && itemOrStructureUpdate != null && cacheDate.before(itemOrStructureUpdate)) {
                staleCache = true;
            }
        }
        componentCheckMap.put("TileCacheStale", staleCache);
    }
    Gson gson = GsonUtil.getDefault();
    String json = gson.toJson(componentCheckMap);
    if (overallHealth) {
        response = Response.ok(json, MediaType.APPLICATION_JSON_TYPE).build();
    } else {
        response = Response.serverError().entity(json).build();
    }
    return response;
}
Also used : ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) HttpGet(org.apache.http.client.methods.HttpGet) Gson(com.google.gson.Gson) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) Item(gov.usgs.cida.coastalhazards.model.Item) GeoServerRESTReader(it.geosolutions.geoserver.rest.GeoServerRESTReader) Status(gov.usgs.cida.coastalhazards.model.util.Status) StatusManager(gov.usgs.cida.coastalhazards.jpa.StatusManager) ItemManager(gov.usgs.cida.coastalhazards.jpa.ItemManager) HttpResponse(org.apache.http.HttpResponse) StatusName(gov.usgs.cida.coastalhazards.model.util.Status.StatusName) TreeMap(java.util.TreeMap) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) Date(java.util.Date) Response(javax.ws.rs.core.Response) HttpResponse(org.apache.http.HttpResponse) EntityManagerFactory(javax.persistence.EntityManagerFactory) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

StatusManager (gov.usgs.cida.coastalhazards.jpa.StatusManager)9 Status (gov.usgs.cida.coastalhazards.model.util.Status)9 ItemManager (gov.usgs.cida.coastalhazards.jpa.ItemManager)8 Response (javax.ws.rs.core.Response)8 Item (gov.usgs.cida.coastalhazards.model.Item)7 Path (javax.ws.rs.Path)6 RolesAllowed (javax.annotation.security.RolesAllowed)5 ThumbnailManager (gov.usgs.cida.coastalhazards.jpa.ThumbnailManager)4 Produces (javax.ws.rs.Produces)4 BadRequestException (gov.usgs.cida.coastalhazards.exception.BadRequestException)3 Date (java.util.Date)3 Consumes (javax.ws.rs.Consumes)3 GET (javax.ws.rs.GET)3 NotFoundException (javax.ws.rs.NotFoundException)3 JsonElement (com.google.gson.JsonElement)2 JsonObject (com.google.gson.JsonObject)2 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 LinkedList (java.util.LinkedList)2 DELETE (javax.ws.rs.DELETE)2