Search in sources :

Example 1 with LayerManager

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

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

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

the class LayerResource method createRasterLayer.

@POST
@Path("/raster")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
@RolesAllowed({ CoastalHazardsTokenBasedSecurityFilter.CCH_ADMIN_ROLE })
public Response createRasterLayer(@Context HttpServletRequest req, @FormDataParam("metadata") String metadata, @FormDataParam("file") InputStream zipFileStream, @FormDataParam("file") FormDataContentDisposition fileDisposition) {
    List<Service> services = new ArrayList<>();
    try {
        log.info("Raster layer upload - about to parseRequest");
        String newId = IdGenerator.generate();
        String metadataId;
        if (metadata == null || metadata.isEmpty()) {
            throw new ServerErrorException("Metadata file is missing or empty.", Status.INTERNAL_SERVER_ERROR);
        }
        try {
            log.info("Raster layer create - about to doCSWInsertFromString");
            metadataId = MetadataUtil.doCSWInsertFromString(metadata);
        } catch (IOException | ParserConfigurationException | SAXException ex) {
            throw new ServerErrorException("Error inserting metadata to the CSW server.", Status.INTERNAL_SERVER_ERROR, ex);
        }
        log.info("Raster layer create - about to makeCSWServiceForUrl with metadataId: " + metadataId);
        services.add(MetadataUtil.makeCSWServiceForUrl(MetadataUtil.getMetadataByIdUrl(metadataId)));
        Bbox bbox = MetadataUtil.getBoundingBoxFromFgdcMetadata(metadata);
        log.info("Starting CRS Identifier Lookup");
        long startTime = System.nanoTime();
        String EPSGcode = CRS.lookupIdentifier(MetadataUtil.getCrsFromFgdcMetadata(metadata), true);
        long endTime = System.nanoTime();
        // divide by 1000000 to get milliseconds
        long duration = (endTime - startTime) / 1000000;
        log.info("Finished CRS Identifier Lookup. Took " + duration + "ms.");
        if (bbox == null || EPSGcode == null) {
            throw new ServerErrorException("Unable to identify bbox or epsg code from metadata.", Status.INTERNAL_SERVER_ERROR);
        }
        log.info("Raster layer create - about to addRasterLayer to geoserver with an id of: " + newId);
        log.info("Raster layer create - about to addRasterLayer to geoserver with a  bbox: " + bbox.getBbox());
        log.info("Raster layer create - about to addRasterLayer to geoserver with an EPSG of: " + EPSGcode);
        Service rasterService = GeoserverUtil.addRasterLayer(geoserverEndpoint, zipFileStream, newId, bbox, EPSGcode);
        if (null == rasterService) {
            throw new ServerErrorException("Unable to create a store and/or layer in GeoServer.", Status.INTERNAL_SERVER_ERROR);
        } else {
            services.add(rasterService);
        }
        if (!services.isEmpty()) {
            Layer layer = new Layer();
            layer.setId(newId);
            layer.setServices(services);
            layer.setBbox(bbox);
            try (LayerManager manager = new LayerManager()) {
                manager.save(layer);
            }
            return Response.created(layerURI(layer)).build();
        } else {
            throw new ServerErrorException("Unable to create layer", Status.INTERNAL_SERVER_ERROR);
        }
    } catch (JAXBException | FactoryException | IOException ex) {
        throw new ServerErrorException("Error parsing upload request", Status.INTERNAL_SERVER_ERROR, ex);
    }
}
Also used : FactoryException(org.opengis.referencing.FactoryException) JAXBException(javax.xml.bind.JAXBException) ArrayList(java.util.ArrayList) WFSService(gov.usgs.cida.coastalhazards.util.ogc.WFSService) Service(gov.usgs.cida.coastalhazards.model.Service) IOException(java.io.IOException) Layer(gov.usgs.cida.coastalhazards.model.Layer) SAXException(org.xml.sax.SAXException) Bbox(gov.usgs.cida.coastalhazards.model.Bbox) ServerErrorException(javax.ws.rs.ServerErrorException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) LayerManager(gov.usgs.cida.coastalhazards.jpa.LayerManager) Path(javax.ws.rs.Path) RolesAllowed(javax.annotation.security.RolesAllowed) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 4 with LayerManager

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

the class LayerResource method createVectorLayer.

@POST
@Path("/")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Produces(MediaType.TEXT_PLAIN)
@RolesAllowed({ CoastalHazardsTokenBasedSecurityFilter.CCH_ADMIN_ROLE })
public Response createVectorLayer(@Context HttpServletRequest req, InputStream postBody) {
    Response response = null;
    String newId = IdGenerator.generate();
    List<Service> added = null;
    try {
        log.info("Vector layer upload - about to parseRequest");
        byte[] inmemory = IOUtils.toByteArray(postBody);
        try (ByteArrayInputStream bais = new ByteArrayInputStream(inmemory)) {
            log.info("Vector layer create - about to doCSWInsertFromString");
            String metadataId = MetadataUtil.doCSWInsertFromString(MetadataUtil.extractMetadataFromShp(bais));
            bais.reset();
            log.info("Vector layer create - about to do GeoserverUtil.addVectorLayer with Id: " + newId);
            added = GeoserverUtil.addVectorLayer(bais, newId);
            log.info("Vector layer create - about to makeCSWServiceForUrl with metadataId: " + metadataId);
            added.add(MetadataUtil.makeCSWServiceForUrl(MetadataUtil.getMetadataByIdUrl(metadataId)));
        } finally {
            // just in case
            inmemory = null;
        }
    } catch (IOException | ParserConfigurationException | SAXException | IllegalArgumentException e) {
        log.error("Problem creating services from input", e);
    }
    if (added != null && !added.isEmpty()) {
        WFSService wfs = (WFSService) Service.ogcHelper(Service.ServiceType.proxy_wfs, added);
        Bbox bbox = null;
        try {
            bbox = WFSIntrospector.getBbox(wfs);
        } catch (IOException ex) {
            log.debug("Error determining bounding box", ex);
        }
        Layer layer = new Layer();
        layer.setId(newId);
        layer.setServices(added);
        layer.setBbox(bbox);
        try (LayerManager manager = new LayerManager()) {
            manager.save(layer);
        }
        response = Response.created(layerURI(layer)).build();
    } else {
        response = Response.serverError().entity("Unable to create layer").build();
    }
    return response;
}
Also used : WFSService(gov.usgs.cida.coastalhazards.util.ogc.WFSService) Service(gov.usgs.cida.coastalhazards.model.Service) IOException(java.io.IOException) Layer(gov.usgs.cida.coastalhazards.model.Layer) SAXException(org.xml.sax.SAXException) Response(javax.ws.rs.core.Response) ByteArrayInputStream(java.io.ByteArrayInputStream) Bbox(gov.usgs.cida.coastalhazards.model.Bbox) WFSService(gov.usgs.cida.coastalhazards.util.ogc.WFSService) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) LayerManager(gov.usgs.cida.coastalhazards.jpa.LayerManager) Path(javax.ws.rs.Path) RolesAllowed(javax.annotation.security.RolesAllowed) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 5 with LayerManager

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

the class LayerResource method getLayer.

@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getLayer(@Context HttpServletRequest req, @PathParam("id") String id) {
    Response response = null;
    try (LayerManager manager = new LayerManager()) {
        Layer layer = manager.load(id);
        if (layer == null) {
            throw new NotFoundException();
        }
        response = Response.ok(GsonUtil.getDefault().toJson(layer), MediaType.APPLICATION_JSON).build();
    }
    return response;
}
Also used : Response(javax.ws.rs.core.Response) NotFoundException(javax.ws.rs.NotFoundException) Layer(gov.usgs.cida.coastalhazards.model.Layer) LayerManager(gov.usgs.cida.coastalhazards.jpa.LayerManager) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

LayerManager (gov.usgs.cida.coastalhazards.jpa.LayerManager)5 Path (javax.ws.rs.Path)5 Layer (gov.usgs.cida.coastalhazards.model.Layer)4 IOException (java.io.IOException)4 RolesAllowed (javax.annotation.security.RolesAllowed)4 Produces (javax.ws.rs.Produces)4 Response (javax.ws.rs.core.Response)4 Service (gov.usgs.cida.coastalhazards.model.Service)3 WFSService (gov.usgs.cida.coastalhazards.util.ogc.WFSService)3 Consumes (javax.ws.rs.Consumes)3 POST (javax.ws.rs.POST)3 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)3 SAXException (org.xml.sax.SAXException)3 JsonObject (com.google.gson.JsonObject)2 ItemManager (gov.usgs.cida.coastalhazards.jpa.ItemManager)2 Bbox (gov.usgs.cida.coastalhazards.model.Bbox)2 Item (gov.usgs.cida.coastalhazards.model.Item)2 LinkedList (java.util.LinkedList)2 GET (javax.ws.rs.GET)2 Gson (com.google.gson.Gson)1