information-system-gui/src/main/java/org/gcube/informationsystem/web/rest/InformationSystemResource.java

342 lines
13 KiB
Java

package org.gcube.informationsystem.web.rest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import javax.annotation.Nullable;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.ObjectWriter;
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.informationsystem.config.TokenManager;
import org.gcube.informationsystem.model.reference.entities.Resource;
import org.gcube.informationsystem.resourceregistry.publisher.ResourceRegistryPublisher;
import org.gcube.informationsystem.resourceregistry.publisher.ResourceRegistryPublisherFactory;
import org.gcube.informationsystem.serialization.ElementMapper;
import org.gcube.informationsystem.service.InformationSystemService;
import org.gcube.informationsystem.service.dto.ContextDTO;
import org.gcube.informationsystem.service.dto.FacetSpecDTO;
import org.gcube.informationsystem.service.dto.FacetTypeDTO;
import org.gcube.informationsystem.service.dto.ResourceBuilderDTO;
import org.gcube.informationsystem.service.dto.ResourceTypeDTO;
import org.gcube.informationsystem.utils.UUIDUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriUtils;
import com.jayway.jsonpath.JsonPath;
import io.swagger.v3.core.util.Json;
import lombok.RequiredArgsConstructor;
import net.minidev.json.JSONArray;
import tech.jhipster.web.util.HeaderUtil;
@RestController
@RequestMapping("/api/is")
@RequiredArgsConstructor
public class InformationSystemResource {
private static final Logger log = LoggerFactory.getLogger(InformationSystemResource.class);
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final TokenManager tokenManager;
private final InformationSystemService informationSystemService;
private String createUmaToken(String currentContext) {
log.debug("Request uma token");
if(currentContext==null || currentContext.isBlank()) {
currentContext = tokenManager.getRootContext();
}
String umaToken = tokenManager.getUmaToken(UriUtils.encode(currentContext, "UTF-8"));
return umaToken;
}
@GetMapping("/allcontexts")
public ResponseEntity<String> allContexts() {
try {
String currentContext = SecretManagerProvider.instance.get().getContext();
informationSystemService.setUma(createUmaToken(currentContext));
List<ContextDTO> contexts = informationSystemService.getAllContexts();
ObjectMapper objectMapper = new ObjectMapper();
String sc = objectMapper.writeValueAsString(contexts);
return ResponseEntity.ok().body(sc);
} catch (Exception e) {
log.error(e.getLocalizedMessage(), e);
return ResponseEntity.noContent()
.headers(HeaderUtil.createAlert(applicationName, e.getLocalizedMessage(), "")).build();
}
}
@GetMapping("/querytemplates")
public ResponseEntity<String> testQueryTemplates(@RequestParam @Nullable String currentContext, @RequestParam String query) {
try {
informationSystemService.setUma(createUmaToken(currentContext));
String res = informationSystemService.executeQueryTemplate(query);
/*
ObjectMapper objectMapper = new ObjectMapper();
String sc = objectMapper.writeValueAsString(res);
*/
return ResponseEntity.ok().body(res);
} catch (Exception e) {
log.error(e.getLocalizedMessage(), e);
return ResponseEntity.noContent()
.headers(HeaderUtil.createAlert(applicationName, e.getLocalizedMessage(), "")).build();
}
}
@GetMapping("/resourcetypes")
public ResponseEntity<String> resourceTypes(@RequestParam @Nullable String currentContext) {
log.debug("Request resource types");
try {
informationSystemService.setUma(createUmaToken(currentContext));
ArrayList<ResourceTypeDTO> treeNode = informationSystemService.getResourceTypesTree();
ObjectMapper objectMapper = new ObjectMapper();
String sc = objectMapper.writeValueAsString(treeNode);
return ResponseEntity.ok().body(sc);
} catch (Exception e) {
log.error("****ERROR*************");
e.printStackTrace();
log.error(e.getLocalizedMessage(), e);
return ResponseEntity.noContent()
.headers(HeaderUtil.createAlert(applicationName, e.getLocalizedMessage(), "")).build();
}
}
@GetMapping("/resourcetype")
//DOES NOT WORK TO RETRIEVE FACETS
// e.g. http://localhost:8081/api/is/resourcetype?typeName=HostingNode
public ResponseEntity<String> resourceType(@RequestParam String typeName,@RequestParam @Nullable String currentContext) {
try {
informationSystemService.setUma(createUmaToken(currentContext));
ResourceTypeDTO dto = informationSystemService.getResourceType(typeName);
ObjectMapper objectMapper = new ObjectMapper();
String sc = objectMapper.writeValueAsString(dto);
return ResponseEntity.ok().body(sc);
} catch (Exception e) {
e.printStackTrace();
log.error("****ERROR*************");
log.error(e.getMessage(), e);
return ResponseEntity.noContent()
.headers(HeaderUtil.createAlert(applicationName, e.getMessage(), "ERRORE")).build();
}
}
// ritorna l'elenco delle facet e come costruirle
@GetMapping("/facetspecifications")
public ResponseEntity<String> resourceTypeComplete(@RequestParam String typeName,@RequestParam @Nullable String currentContext) {
ArrayList<FacetSpecDTO> facetSpecs = new ArrayList<FacetSpecDTO>();
try {
informationSystemService.setUma(createUmaToken(currentContext));
ResourceTypeDTO dto = informationSystemService.getResourceType(typeName);
ResourceBuilderDTO builderDto = new ResourceBuilderDTO(dto.getName(), dto.getDescription(), dto.isAstratto());
for(FacetTypeDTO ft : dto.getFacetTypes()) {
FacetSpecDTO fs = informationSystemService.getFacetSpecification(ft.getTarget());
fs.setMax(ft.getMax());
fs.setMin(ft.getMin());
fs.setRelation(ft.getRelation());
fs.setRelationOptions(informationSystemService.getFacetRelationsOptions(ft.getRelation()));
facetSpecs.add(fs);
}
builderDto.setFacetSpecs(facetSpecs);
ObjectMapper objectMapper = new ObjectMapper();
String sc = objectMapper.writeValueAsString(builderDto);
return ResponseEntity.ok().body(sc);
} catch (Exception e) {
e.printStackTrace();
log.error("****ERROR*************");
log.error(e.getMessage(), e);
return ResponseEntity.noContent()
.headers(HeaderUtil.createAlert(applicationName, e.getMessage(), "ERRORE")).build();
}
}
@GetMapping("/resourcetypejson")
// e.g. http://localhost:8081/api/is/resourcetype?typeName=HostingNode
public ResponseEntity<String> resourceTypeJson(@RequestParam String typeName,@RequestParam @Nullable String currentContext) {
try {
informationSystemService.setUma(createUmaToken(currentContext));
String raw= informationSystemService.getResourceTypeJson(typeName);
return ResponseEntity.ok().body(raw);
} catch (Exception e) {
e.printStackTrace();
log.error("****ERROR*************");
log.error(e.getMessage(), e);
return ResponseEntity.noContent()
.headers(HeaderUtil.createAlert(applicationName, e.getMessage(), "ERRORE")).build();
}
}
@GetMapping("/resourcejson")
public ResponseEntity<String> resourceInstanceJson(@RequestParam @Nullable String currentContext, @RequestParam String resourceType, @RequestParam String uid) {
log.debug("Request resource json");
try {
informationSystemService.setUma(createUmaToken(currentContext));
String rawJson = informationSystemService.getResource(resourceType, uid);
String sc = rawJson;
return ResponseEntity.ok().body(sc);
} catch (Exception e) {
log.error("****ERROR*************");
log.error(e.getLocalizedMessage(), e);
return ResponseEntity.noContent()
.headers(HeaderUtil.createAlert(applicationName, e.getLocalizedMessage(), "")).build();
}
}
/*
* returns all the instances of resources given a certain type
*/
@GetMapping("/resourceinstances")
public ResponseEntity<String> resourceInstances(@RequestParam @Nullable String currentContext, @RequestParam String resourceType) {
log.debug("Request resource instances");
DTOResourceBuilder dtoBuilder = new DTOResourceBuilder(resourceType);
List<Resource> resourceImpls = new ArrayList<Resource>();
ArrayList resultDtos = new ArrayList<>();
try {
informationSystemService.setUma(createUmaToken(currentContext));
resourceImpls = informationSystemService.getResourceInstances(resourceType);
for(Resource resImpl: resourceImpls) {
String jsonResource = ElementMapper.marshal(resImpl);
dtoBuilder.setJson(jsonResource);
resultDtos.add(dtoBuilder.build());
}
}catch(Exception e) {
log.error("ERROR WHILE FILLING RESOURCEIMPL DTO");
//e.printStackTrace();
}
try {
ObjectMapper objectMapper = new ObjectMapper();
String sc = objectMapper.writeValueAsString(resultDtos);
return ResponseEntity.ok().body(sc);
} catch (Exception e) {
log.error(e.getLocalizedMessage(), e);
return ResponseEntity.noContent()
.headers(HeaderUtil.createAlert(applicationName, e.getLocalizedMessage(), "")).build();
}
}
//CRUD - 1
@PostMapping("/createresource")
String createResource(@RequestParam String resourceType, @RequestBody String formData) throws Exception {
//NB: non serve UmaToken e context!
ArrayList<String> facetNames = new ArrayList<>();
ArrayList<String> facetRelations = new ArrayList<>();
ArrayList<JSONArray> extraProps = new ArrayList<JSONArray>();
JSONArray props = new JSONArray();
String sendingJson="";
try {
facetNames = JsonPath.parse(formData).read("$..facetName");
facetRelations = JsonPath.parse(formData).read("$..relationFacet");
extraProps = JsonPath.parse(formData).read("$..extraProps");
props = JsonPath.parse(formData).read("$..props");
ResourceDescription rd = new ResourceDescription();
rd = buildSendingJson(resourceType,facetNames,facetRelations,extraProps,props);
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
sendingJson = ow.writeValueAsString(rd);
//System.out.println(Json.pretty(rd));
}catch(Exception e) {
log.error(e.getMessage());
}
// String currentCtx = SecretManagerProvider.instance.get().getContext();
ResourceRegistryPublisher publisher = ResourceRegistryPublisherFactory.create();
String uid="";
try {
uid = publisher.createResource(sendingJson);
}catch(Exception e) {
e.printStackTrace();
log.error(e.getMessage());
}
return uid;
//TODO: GESTIRE ERRORI!
}
//CRUD - 3
@PostMapping("/deleteresource")
boolean deleteResource(@RequestParam @Nullable String currentContext, @RequestParam String resourceType, @RequestParam String uuid)throws Exception {
String currentCtx = SecretManagerProvider.instance.get().getContext();
ResourceRegistryPublisher publisher = ResourceRegistryPublisherFactory.create();
//TODO: dove setto UMA Token?? (altrimenti error 500)
UUIDUtility uuidUtil = new UUIDUtility();
return publisher.deleteResource(resourceType, uuidUtil.fromString(uuid));
//TODO: GESTIRE ERRORI!
}
ResourceDescription buildSendingJson(String resourceType, ArrayList<String> facetNames, ArrayList<String> relations, ArrayList<JSONArray> extraProps, JSONArray props ) {
ResourceDescription rd = new ResourceDescription();
rd.setType(resourceType);
for(int i=0; i<facetNames.size(); i++) {
LinkedHashMap targetMap_i = new LinkedHashMap<String, Object>();
FacetDescription facet_i = new FacetDescription();
facet_i.setType(relations.get(i));
FacetDescription facet_d = new FacetDescription();
LinkedHashMap joProp_i = (LinkedHashMap)props.get(i);
joProp_i.put("type", facetNames.get(i));
Iterator<String> keyit = (Iterator) joProp_i.keySet().iterator();
while(keyit.hasNext()) {
String key = keyit.next();
if(key.equals("optional")) {
continue;
}
targetMap_i.put(key, joProp_i.get(key).toString());
}
JSONArray extra_joProps_i = (JSONArray)extraProps.get(i);
if(extra_joProps_i.size()!=0) {
for(int j=0; j<extra_joProps_i.size(); j++) {
LinkedHashMap extraProps_ij = (LinkedHashMap)extra_joProps_i.get(j);
Iterator<String> it = (Iterator) extraProps_ij.keySet().iterator();
while(it.hasNext()) {
String key = it.next();
targetMap_i.put(extraProps_ij.get("deno").toString(),extraProps_ij.get("val").toString());//to avoid ClassCastException
}
}
}
facet_i.setTarget(targetMap_i);
if(rd.getConsistsOf()==null) {
rd.setConsistsOf(new ArrayList<FacetDescription>());
}
rd.getConsistsOf().add(facet_i);
}
return rd;
}
}