package eu.dnetlib.uoaorcidservice.controllers; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import eu.dnetlib.uoaorcidservice.configuration.properties.OrcidConfig; import eu.dnetlib.uoaorcidservice.entities.ResultIdAndWork; import eu.dnetlib.uoaorcidservice.entities.UserTokens; import eu.dnetlib.uoaorcidservice.entities.Work; import eu.dnetlib.uoaorcidservice.handlers.ConflictException; import eu.dnetlib.uoaorcidservice.handlers.ContentNotFoundException; import eu.dnetlib.uoaorcidservice.services.UserTokensService; import eu.dnetlib.uoaorcidservice.services.WorkService; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.*; import org.springframework.security.access.AuthorizationServiceException; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.DefaultResponseErrorHandler; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.IOException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.*; @RestController @PreAuthorize("isAuthenticated()") @CrossOrigin(origins = "*") public class WorkController { private final Logger log = Logger.getLogger(this.getClass()); private final Logger orcid_log = Logger.getLogger("ORCID-"+this.getClass().getName()); @Autowired private OrcidConfig orcidConfig; @Autowired private UserTokensService userTokensService; @Autowired private WorkService workService; @RequestMapping(value = "/local/put-code", method = RequestMethod.GET) public List getPutCode(@RequestParam String[] pids) { String userOrcid = userTokensService.getCurrentUserOrcid(); List works = workService.getWorks(pids, userOrcid); if(works != null) { List putCodes = new ArrayList<>(); for(Work work : works) { putCodes.add(work.getPutCode()); } return putCodes; } return null; } @RequestMapping(value = "/local/put-codes", method = RequestMethod.POST) public List> getPutCodes(@RequestBody String[][] pids) { String userOrcid = userTokensService.getCurrentUserOrcid(); List> putCodes = new ArrayList(); for(int i=0; i works = workService.getWorks(pids[i], userOrcid); if (works != null) { List putCodesOfOneRecord = new ArrayList<>(); for(Work work : works) { putCodesOfOneRecord.add(work.getPutCode()); } putCodes.add(putCodesOfOneRecord); } else { putCodes.add(null); } } return putCodes; } @RequestMapping(value = "/local/works", method = RequestMethod.POST) public List> getLocalWorks(@RequestBody String[][] pids) { String userOrcid = userTokensService.getCurrentUserOrcid(); if(userOrcid == null) { throw new AuthorizationServiceException("User is not registered"); } List> returnedWorks = new ArrayList(); for(int i=0; i works = workService.getWorks(pids[i], userOrcid); returnedWorks.add(works); } return returnedWorks; } @RequestMapping(value = "/orcid/work/save", method = RequestMethod.POST) public Work saveWork(@RequestBody String resultString) throws Exception { log.debug("saveWork: result = " + resultString); Gson gson = new GsonBuilder().create(); ResultIdAndWork result = gson.fromJson(resultString, ResultIdAndWork.class); UserTokens userTokens = userTokensService.getUserTokens(); if(userTokens == null) { throw new AuthorizationServiceException("User is not registered"); } String userOrcid = userTokens.getOrcid(); String userAccessToken = userTokens.getAccessToken(); if(userOrcid == null || userAccessToken == null) { throw new AuthorizationServiceException("User is not registered"); } // log.debug("Access token: " + userAccessToken); // log.debug("User orcid: " + userOrcid); String url = orcidConfig.getApiURL() + userOrcid + "/work"; RestTemplate restTemplate = new RestTemplate(); // restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory()); restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { protected boolean hasError(HttpStatus statusCode) { if(statusCode == HttpStatus.UNAUTHORIZED) { orcid_log.error("ORCID service returned UNAUTHORIZED: "+HttpStatus.UNAUTHORIZED); throw new AuthorizationServiceException("User is not registered"); } return false; } }); HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Bearer " + userAccessToken); headers.add("Content-Type", "application/orcid+json;charset=UTF-8"); HttpEntity request = new HttpEntity<>(gson.toJson(result.getWork()), headers); orcid_log.info("request: "+request); orcid_log.info("url: "+url); ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, request, String.class); if (response.getStatusCode() != HttpStatus.CREATED) { orcid_log.error("Saving work response code is: " + response.getStatusCode()); orcid_log.error("Unexpected Response: "+response.getBody()); if(response.getStatusCode() == HttpStatus.UNAUTHORIZED) { throw new AuthorizationServiceException("You are not allowed to save work"); } else if(response.getStatusCode() == HttpStatus.CONFLICT) { throw new ConflictException("Work is already saved"); } else { throw new Exception("Internal server error"); } // return null; } else { orcid_log.info("Response: "+response); // log.debug("[success] Saving work response code is: " + response.getStatusCode()); // log.debug(response.toString()); Date date = new Date(); Work workToSave = new Work(); workToSave.setPids(result.getPids()); workToSave.setOrcid(userOrcid); workToSave.setCreationDate(date); workToSave.setUpdateDate(date); workToSave.setDashboard(result.getDashboard()); HttpHeaders responseHeaders = response.getHeaders(); String locationPath = responseHeaders.getLocation().toString(); String[] locationPathArray = locationPath.split("/"); workToSave.setPutCode(locationPathArray[locationPathArray.length - 1]); // log.debug(gson.toJson(result.getPids())); // log.debug(responseHeaders.getLocation().toString()); // log.debug(gson.toJson(workToSave)); workService.saveWork(workToSave); return workToSave; // return "\""+workToSave.getPutCode()+"\""; } } @RequestMapping(value = "/orcid/work/update/{putCode}", method = RequestMethod.POST) public Work updateWork(@PathVariable String putCode, @RequestBody String resultString) throws Exception { log.debug("updateWork: putCode = " + putCode); Gson gson = new GsonBuilder().create(); ResultIdAndWork result = gson.fromJson(resultString, ResultIdAndWork.class); UserTokens userTokens = userTokensService.getUserTokens(); if(userTokens == null) { throw new AuthorizationServiceException("User is not registered"); } String userOrcid = userTokens.getOrcid(); String userAccessToken = userTokens.getAccessToken(); if(userOrcid == null || userAccessToken == null) { throw new AuthorizationServiceException("User is not registered"); } // log.debug("Access token: " + userAccessToken); // log.debug("User orcid: " + userOrcid); // String url = "https://sandbox.orcid.org/v3.0/" + orcid.toString() + "/works"; // String url = "https://api.sandbox.orcid.org/v3.0/" + userOrcid + "/work/" + putCode; String url = orcidConfig.getApiURL() + userOrcid + "/work/" + putCode; RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { protected boolean hasError(HttpStatus statusCode) { return false; } }); HttpHeaders headers = new HttpHeaders(); // headers.add("Accept", "application/json"); headers.add("Authorization", "Bearer " + userAccessToken); headers.add("Content-Type", "application/orcid+json;charset=UTF-8"); HttpEntity request = new HttpEntity<>(gson.toJson(result.getWork()), headers); orcid_log.info("request: "+request); orcid_log.info("url: "+url); ResponseEntity response = restTemplate.exchange(url, HttpMethod.PUT, request, String.class); if (response.getStatusCode() != HttpStatus.OK) { orcid_log.error("Updating work response code is: " + response.getStatusCode()); orcid_log.error("Unexpected Response: "+response.getBody()); if(response.getStatusCode() == HttpStatus.NOT_FOUND) { throw new ContentNotFoundException("Work to update not found"); } else if(response.getStatusCode() == HttpStatus.UNAUTHORIZED) { throw new AuthorizationServiceException("You are not allowed to update work"); } else if(response.getStatusCode() == HttpStatus.CONFLICT) { throw new ConflictException("Work is already saved"); } else { throw new Exception("Internal server error"); } // return null; } else { orcid_log.info("Response: "+response); Date date = new Date(); Work localWork = workService.getLocalWorkByPutCode(putCode); localWork.setPids(result.getPids()); localWork.setUpdateDate(date); workService.saveWork(localWork); return localWork; // return null; } } @RequestMapping(value = "/orcid/works", method = RequestMethod.GET) public String getWorksByPutCodes(@RequestParam String put_codes) throws BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, IOException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeySpecException { log.debug("getWorksByPutCodes: put_codes = " + put_codes); UserTokens userTokens = userTokensService.getUserTokens(); if(userTokens == null) { throw new AuthorizationServiceException("User is not registered"); } String userOrcid = userTokens.getOrcid(); String userAccessToken = userTokens.getAccessToken(); if(userOrcid == null || userAccessToken == null) { throw new AuthorizationServiceException("User is not registered"); } // log.debug("Access token: " + userAccessToken); // log.debug("User orcid: " + userOrcid); // String url = "https://sandbox.orcid.org/v3.0/" + orcid.toString() + "/works"; String url = orcidConfig.getApiURL()+userOrcid+"/works/"+put_codes; RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { protected boolean hasError(HttpStatus statusCode) { return false; } }); HttpHeaders headers = new HttpHeaders(); headers.add("Accept", "application/json"); headers.add("Authorization", "Bearer " + userAccessToken); headers.add("Content-Type", "application/orcid+json;charset=UTF-8"); HttpEntity request = new HttpEntity<>(headers); orcid_log.info("request: "+request); orcid_log.info("url: "+url); ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, request, String.class); if (response.getStatusCode() != HttpStatus.OK) { orcid_log.error("Getting works response code is: " + response.getStatusCode()); orcid_log.error("Unexpected Response: "+response.getBody()); return null; } else { orcid_log.info("Response: "+response); return response.getBody().toString(); } } @RequestMapping(value = "/orcid/work/{putCode}/delete", method = RequestMethod.DELETE) public String deleteWork(@PathVariable String putCode) throws IOException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeySpecException { log.debug("deleteWork: putCode = " + putCode); UserTokens userTokens = userTokensService.getUserTokens(); if(userTokens == null) { throw new AuthorizationServiceException("User is not registered"); } String userOrcid = userTokens.getOrcid(); String userAccessToken = userTokens.getAccessToken(); if(userOrcid == null || userAccessToken == null) { throw new AuthorizationServiceException("User is not registered"); } // log.debug("Access token: " + userAccessToken); // log.debug("User orcid: " + userOrcid); String url = orcidConfig.getApiURL()+userOrcid+"/work/" + putCode; RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { protected boolean hasError(HttpStatus statusCode) { return false; } }); HttpHeaders headers = new HttpHeaders(); // headers.add("Accept", "application/json"); headers.add("Authorization", "Bearer " + userAccessToken); headers.add("Content-Type", "application/orcid+json;charset=UTF-8"); HttpEntity request = new HttpEntity<>(headers); orcid_log.info("request: "+request); orcid_log.info("url: "+url); ResponseEntity response = restTemplate.exchange(url, HttpMethod.DELETE, request, String.class); if (response.getStatusCode() != HttpStatus.NO_CONTENT) { orcid_log.error("Deleting work response code is: " + response.getStatusCode()); orcid_log.error("Unexpected Response: "+response.getBody()); if(response.getStatusCode() == HttpStatus.NOT_FOUND) { workService.deleteWork(putCode); return putCode; } if(response.getStatusCode() == HttpStatus.UNAUTHORIZED) { throw new AuthorizationServiceException("You are not allowed to delete work"); } return null; } else { orcid_log.info("Response: "+response); workService.deleteWork(putCode); return putCode; } } @RequestMapping(value = "/orcid/works/delete", method = RequestMethod.POST) public List deleteWorks(@RequestBody List putCodes) throws IOException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeySpecException { log.debug("deleteWorks: putCodes = " + putCodes); UserTokens userTokens = userTokensService.getUserTokens(); if(userTokens == null) { throw new AuthorizationServiceException("User is not registered"); } String userOrcid = userTokens.getOrcid(); String userAccessToken = userTokens.getAccessToken(); if(userOrcid == null || userAccessToken == null) { throw new AuthorizationServiceException("User is not registered"); } // log.debug("Access token: " + userAccessToken); // log.debug("User orcid: " + userOrcid); RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { protected boolean hasError(HttpStatus statusCode) { return false; } }); HttpHeaders headers = new HttpHeaders(); // headers.add("Accept", "application/json"); headers.add("Authorization", "Bearer " + userAccessToken); headers.add("Content-Type", "application/orcid+json;charset=UTF-8"); HttpEntity request = new HttpEntity<>(headers); List deletedPutCodes = new ArrayList<>(); int index = 0; for(String putCode : putCodes) { String url = orcidConfig.getApiURL()+userOrcid+"/work/" + putCode; // UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url); orcid_log.info("request: "+request); orcid_log.info("url: "+url); ResponseEntity response = restTemplate.exchange(url, HttpMethod.DELETE, request, String.class); if (response.getStatusCode() != HttpStatus.NO_CONTENT) { orcid_log.error("Deleting work response code is: " + response.getStatusCode()); orcid_log.error("Unexpected Response: "+response.getBody()); if(index == 0 && response.getStatusCode() == HttpStatus.UNAUTHORIZED) { throw new AuthorizationServiceException("You are not allowed to delete work"); } if (response.getStatusCode() == HttpStatus.NOT_FOUND) { workService.deleteWork(putCode); deletedPutCodes.add(putCode); } else { deletedPutCodes.add(null); } } else { orcid_log.info("Response: "+response); workService.deleteWork(putCode); deletedPutCodes.add(putCode); } index++; } return deletedPutCodes; } @RequestMapping(value = "/orcid/work", method = RequestMethod.GET) public List getWorksOfReuslt(@RequestParam String[] pids, @RequestParam String orcid) throws BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeySpecException, IOException { log.debug("getWorks: pids = " + pids + " - orcid = "+orcid); List works = workService.getWorks(pids, orcid); String userAccessToken = userTokensService.getUserAccessToken(orcid); // log.debug("Access token: " + userAccessToken); RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new DefaultResponseErrorHandler() { protected boolean hasError(HttpStatus statusCode) { return false; } }); HttpHeaders headers = new HttpHeaders(); headers.add("Accept", "application/json"); headers.add("Authorization", "Bearer " + userAccessToken); headers.add("Content-Type", "application/orcid+json;charset=UTF-8"); HttpEntity request = new HttpEntity<>(headers); List responseValues = new ArrayList<>(); for(Work work : works) { String url = orcidConfig.getApiURL() + orcid + "/work/" + work.getPutCode(); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url); orcid_log.info("request: "+request); orcid_log.info("url: "+url); ResponseEntity response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, request, String.class); if (response.getStatusCode() != HttpStatus.OK) { orcid_log.error("Getting work response code is: " + response.getStatusCode()); orcid_log.error("Unexpected Response: "+response.getBody()); if (response.getStatusCode() == HttpStatus.NOT_FOUND) { // work.setPutCode(null); // workService.saveWork(work); workService.deleteWork(work.getPutCode()); } responseValues.add(null); } else { orcid_log.info("Response: "+response); responseValues.add(response.getBody().toString()); } } return responseValues; } // @PreAuthorize("isAuthenticated()") // @RequestMapping(value = "/local/works", method = RequestMethod.GET) // public Map getLocalWorks(@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer size) // throws BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeySpecException, IOException { // log.debug("getWorks: page="+page+ " - size="+size); // // String userOrcid = userTokensService.getCurrentUserOrcid(); // if(userOrcid == null) { // throw new AuthorizationServiceException("User is not registered"); // } // // List works = workService.getLocalWorks(userOrcid); // // Map response = new HashMap<>(); // response.put("total", works.size()); // // if(page != null && page > 0 && size != null && size > 0) { // int from = (page-1)*size; // int to = page*size; // //// log.debug("size: "+works.size()); // if(to > works.size()) { // to = works.size(); // } //// log.debug("from="+from+" - to="+to); // //// int index = 0; //// Iterator iterator = works.iterator(); //// while(iterator.hasNext()) { //// iterator.next(); //// if(index < from || index > to) { //// iterator.remove(); //// } //// index++; //// } // if(from < to) { // response.put("results", works.subList(from, to)); // return response; // } // } // response.put("results", works); // return response; // } @RequestMapping(value = "/local/works", method = RequestMethod.GET) public List getMyLocalWorks() { log.debug("getMyWorks"); // String userOrcid = userTokensService.getCurrentUserOrcid(); if(userOrcid == null) { throw new AuthorizationServiceException("User is not registered"); } // List works = workService.getLocalWorks(userOrcid); // return works; } }