use of gov.usgs.cida.coastalhazards.jpa.ItemManager 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;
}
use of gov.usgs.cida.coastalhazards.jpa.ItemManager in project coastal-hazards by USGS-CIDA.
the class SLDResource method getSLDInfo.
/**
* JSON representation of the contents of the SLD, this is primarily for
* building a UI legend ;qs=0 is to make this a lower priority than the xml
* document, must say accepts=application/json to get this document
*
* @param id item ID
* @param ribbon Not used currently, but represents which ribbon to
* represent
* @return JSON document with SLD info
*/
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON + ";qs=0")
public Response getSLDInfo(@PathParam("id") String id, @QueryParam("ribbon") Integer ribbon, @QueryParam("selectedItem") String selectedId) {
PerformanceProfiler.startTimer("SLDResource.getSLDInfo - " + id);
Response response;
try (ItemManager manager = new ItemManager()) {
if (selectedId == null || selectedId.length() == 0) {
selectedId = id;
}
PerformanceProfiler.startTimer("SLDResource.getSLD_ItemManager.load - " + id);
Item item = manager.load(id);
PerformanceProfiler.stopDebug("SLDResource.getSLD_ItemManager.load - " + id);
if (item == null) {
response = Response.status(Response.Status.NOT_FOUND).build();
} else {
PerformanceProfiler.startTimer("SLDResource.getSLDInfo_getGenerator - " + id);
SLDGenerator generator = SLDGenerator.getGenerator(item, selectedId, ribbon);
PerformanceProfiler.stopDebug("SLDResource.getSLDInfo_getGenerator - " + id);
if (generator == null) {
response = Response.status(Response.Status.NOT_FOUND).build();
} else {
PerformanceProfiler.startTimer("SLDResource.getSLDInfo_generateSLDInfo - " + id);
response = generator.generateSLDInfo();
PerformanceProfiler.stopDebug("SLDResource.getSLDInfo_generateSLDInfo - " + id);
}
}
} catch (Exception e) {
response = Response.status(500).build();
}
PerformanceProfiler.stopDebug("SLDResource.getSLDInfo - " + id);
return response;
}
use of gov.usgs.cida.coastalhazards.jpa.ItemManager in project coastal-hazards by USGS-CIDA.
the class TemplateResource method instantiateStormTemplate.
@GET
@Path("/storm")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed({ CoastalHazardsTokenBasedSecurityFilter.CCH_ADMIN_ROLE })
public Response instantiateStormTemplate(@Context HttpServletRequest request, @QueryParam("layerId") String layerId, @QueryParam("activeStorm") String active, @QueryParam("alias") String alias, @QueryParam("copyType") String copyType, @QueryParam("copyVal") String copyVal, @QueryParam("trackId") String trackId) {
Response response;
if (layerId != null && active != null) {
Gson gson = GsonUtil.getDefault();
String childJson = null;
childJson = gson.toJson(StormUtil.createStormChildMap(layerId, Boolean.parseBoolean(active), trackId));
if (childJson != null && childJson.length() > 0) {
try (ItemManager itemMan = new ItemManager();
LayerManager layerMan = new LayerManager();
AliasManager aliasMan = new AliasManager()) {
Layer layer = layerMan.load(layerId);
if (layer != null) {
Summary summary = null;
if (copyType.equalsIgnoreCase("item") || copyType.equalsIgnoreCase("alias")) {
summary = copyExistingSummary(copyType, copyVal, itemMan, aliasMan);
} else {
summary = StormUtil.buildStormTemplateSummary(layer);
}
if (summary != null) {
List<Service> services = layer.getServices();
List<Service> serviceCopies = new LinkedList<>();
for (Service service : services) {
serviceCopies.add(Service.copyValues(service, new Service()));
}
Item baseTemplate = baseTemplateItem(Boolean.parseBoolean(active), layer.getBbox(), serviceCopies, summary);
String templateId = itemMan.persist(baseTemplate);
if (templateId != null && templateId.length() > 0) {
response = instantiateTemplate(request, templateId, childJson);
if (response.getStatus() == HttpStatus.SC_OK) {
Map<String, Object> ok = new HashMap<String, Object>() {
private static final long serialVersionUID = 2398472L;
{
put("id", templateId);
}
};
if (alias != null && alias.length() > 0) {
Alias fullAlias = aliasMan.load(alias);
if (fullAlias != null) {
fullAlias.setItemId(templateId);
aliasMan.update(fullAlias);
} else {
fullAlias = new Alias();
fullAlias.setId(alias);
fullAlias.setItemId(templateId);
aliasMan.save(fullAlias);
}
}
response = Response.ok(GsonUtil.getDefault().toJson(ok, HashMap.class), MediaType.APPLICATION_JSON_TYPE).build();
}
} else {
response = Response.status(500).build();
}
} else {
response = Response.status(400).build();
}
} else {
response = Response.status(400).build();
}
} catch (Exception e) {
log.error(e.toString());
response = Response.status(500).build();
}
} else {
response = Response.status(400).build();
}
} else {
response = Response.status(400).build();
}
return response;
}
use of gov.usgs.cida.coastalhazards.jpa.ItemManager 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.ItemManager 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