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;
}
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;
}
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;
}
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;
}
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;
}
Aggregations