Search in sources :

Example 6 with ItemManager

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

Example 7 with ItemManager

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;
}
Also used : Response(javax.ws.rs.core.Response) Item(gov.usgs.cida.coastalhazards.model.Item) SLDGenerator(gov.usgs.cida.coastalhazards.sld.SLDGenerator) ItemManager(gov.usgs.cida.coastalhazards.jpa.ItemManager) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 8 with ItemManager

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;
}
Also used : ItemManager(gov.usgs.cida.coastalhazards.jpa.ItemManager) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Gson(com.google.gson.Gson) WFSService(gov.usgs.cida.coastalhazards.util.ogc.WFSService) OGCService(gov.usgs.cida.coastalhazards.util.ogc.OGCService) Service(gov.usgs.cida.coastalhazards.model.Service) Layer(gov.usgs.cida.coastalhazards.model.Layer) LinkedList(java.util.LinkedList) URISyntaxException(java.net.URISyntaxException) BadRequestException(javax.ws.rs.BadRequestException) SAXException(org.xml.sax.SAXException) JsonSyntaxException(com.google.gson.JsonSyntaxException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Response(javax.ws.rs.core.Response) AliasManager(gov.usgs.cida.coastalhazards.jpa.AliasManager) Item(gov.usgs.cida.coastalhazards.model.Item) Alias(gov.usgs.cida.coastalhazards.model.Alias) Summary(gov.usgs.cida.coastalhazards.model.summary.Summary) JsonObject(com.google.gson.JsonObject) LayerManager(gov.usgs.cida.coastalhazards.jpa.LayerManager) Path(javax.ws.rs.Path) RolesAllowed(javax.annotation.security.RolesAllowed) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 9 with ItemManager

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;
}
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 10 with ItemManager

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

ItemManager (gov.usgs.cida.coastalhazards.jpa.ItemManager)31 Item (gov.usgs.cida.coastalhazards.model.Item)26 Path (javax.ws.rs.Path)24 GET (javax.ws.rs.GET)22 Produces (javax.ws.rs.Produces)21 Response (javax.ws.rs.core.Response)21 HashMap (java.util.HashMap)11 NotFoundException (javax.ws.rs.NotFoundException)9 StatusManager (gov.usgs.cida.coastalhazards.jpa.StatusManager)8 Status (gov.usgs.cida.coastalhazards.model.util.Status)8 JsonSyntaxException (com.google.gson.JsonSyntaxException)7 BadRequestException (gov.usgs.cida.coastalhazards.exception.BadRequestException)7 Viewable (org.glassfish.jersey.server.mvc.Viewable)7 Gson (com.google.gson.Gson)6 JsonObject (com.google.gson.JsonObject)5 AliasManager (gov.usgs.cida.coastalhazards.jpa.AliasManager)5 Alias (gov.usgs.cida.coastalhazards.model.Alias)5 RolesAllowed (javax.annotation.security.RolesAllowed)5 ThumbnailManager (gov.usgs.cida.coastalhazards.jpa.ThumbnailManager)4 IOException (java.io.IOException)4