Search in sources :

Example 51 with ResponseBody

use of org.springframework.web.bind.annotation.ResponseBody in project ORCID-Source by ORCID.

the class ManageProfileController method getDefaultPreference.

@RequestMapping(value = "/preferences.json", method = RequestMethod.GET)
@ResponseBody
public Map<String, Object> getDefaultPreference(HttpServletRequest request) {
    Map<String, Object> preferences = new HashMap<String, Object>();
    ProfileEntity entity = profileEntityCacheManager.retrieve(getCurrentUserOrcid());
    preferences.put("email_frequency", String.valueOf(entity.getSendEmailFrequencyDays()));
    preferences.put("default_visibility", entity.getActivitiesVisibilityDefault());
    preferences.put("developer_tools_enabled", entity.getEnableDeveloperTools());
    preferences.put("notifications_enabled", entity.getEnableNotifications() == null ? false : entity.getEnableNotifications());
    preferences.put("send_administrative_change_notifications", entity.getSendAdministrativeChangeNotifications() == null ? false : entity.getSendAdministrativeChangeNotifications());
    preferences.put("send_change_notifications", entity.getSendChangeNotifications() == null ? false : entity.getSendChangeNotifications());
    preferences.put("send_member_update_requests", entity.getSendMemberUpdateRequests() == null ? false : entity.getSendMemberUpdateRequests());
    preferences.put("send_orcid_news", entity.getSendOrcidNews() == null ? false : entity.getSendOrcidNews());
    return preferences;
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 52 with ResponseBody

use of org.springframework.web.bind.annotation.ResponseBody in project nhin-d by DirectProject.

the class PoliciesController method checkPolicyContent.

@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(value = "/checkPolicyContent", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public String checkPolicyContent(@RequestHeader(value = "X-Requested-With", required = false) String requestedWith, HttpServletResponse response, HttpServletRequest request, Object command) throws Exception {
    final org.nhindirect.policy.PolicyLexicon parseLexicon;
    String jsonResponse = "";
    String content = request.getParameter("content");
    String lexicon = "";
    if (log.isDebugEnabled()) {
        log.debug("Checking policy content for format and validation");
    }
    lexicon = request.getParameter("lexicon");
    org.nhind.config.PolicyLexicon lex = null;
    // Check the file for three types of policies
    if (lexicon.isEmpty()) {
        lex = org.nhind.config.PolicyLexicon.SIMPLE_TEXT_V1;
    } else {
        try {
            // Convert string of file contents to lexicon object
            lex = org.nhind.config.PolicyLexicon.fromString(lexicon);
        } catch (Exception e) {
            log.error("Invalid lexicon name.");
        }
    }
    // Determine lexicon type
    if (lex.equals(org.nhind.config.PolicyLexicon.JAVA_SER)) {
        parseLexicon = org.nhindirect.policy.PolicyLexicon.JAVA_SER;
    } else if (lex.equals(org.nhind.config.PolicyLexicon.SIMPLE_TEXT_V1)) {
        parseLexicon = org.nhindirect.policy.PolicyLexicon.SIMPLE_TEXT_V1;
    } else {
        parseLexicon = org.nhindirect.policy.PolicyLexicon.XML;
    }
    InputStream inStr = null;
    try {
        // Convert policy file upload to byte stream
        inStr = new ByteArrayInputStream(content.getBytes());
        // Initialize parser engine
        final PolicyLexiconParser parser = PolicyLexiconParserFactory.getInstance(parseLexicon);
        // Attempt to parse the lexicon file for validity
        parser.parse(inStr);
    } catch (PolicyParseException e) {
        log.error("Syntax error in policy content " + " : " + e.getMessage());
        jsonResponse = "{\"Status\":\"Policy content was not valid.\",\"Error\":\"" + e.getMessage() + "\"}";
    } finally {
        IOUtils.closeQuietly(inStr);
    }
    if (jsonResponse.isEmpty()) {
        jsonResponse = "{\"Status\":\"Success\"}";
    }
    return jsonResponse;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) PolicyLexicon(org.nhindirect.policy.PolicyLexicon) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) PolicyLexiconParser(org.nhindirect.policy.PolicyLexiconParser) URISyntaxException(java.net.URISyntaxException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PolicyParseException(org.nhindirect.policy.PolicyParseException) MalformedURLException(java.net.MalformedURLException) ServiceException(org.nhindirect.common.rest.exceptions.ServiceException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) FileUploadException(org.apache.commons.fileupload.FileUploadException) PolicyParseException(org.nhindirect.policy.PolicyParseException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 53 with ResponseBody

use of org.springframework.web.bind.annotation.ResponseBody in project nhin-d by DirectProject.

the class PoliciesController method checkLexiconFile.

/*********************************
     *
     * Check Lexicon File Method
     *
     *********************************/
@PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(value = "/checkLexiconFile", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public String checkLexiconFile(@RequestHeader(value = "X-Requested-With", required = false) String requestedWith, HttpServletResponse response, Object command, @RequestHeader(value = "lexicon", required = false) String lexicon, MultipartHttpServletRequest request) throws FileUploadException, IOException, Exception {
    final org.nhindirect.policy.PolicyLexicon parseLexicon;
    String jsonResponse = "";
    String uploadToString = "";
    if (log.isDebugEnabled()) {
        log.debug("Checking uploaded lexicon file for format and validation");
    }
    // Grab uploaded file from the post submission
    UploadedFile ufile = new UploadedFile();
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf = request.getFile(itr.next());
    try {
        ufile.length = mpf.getBytes().length;
        ufile.bytes = mpf.getBytes();
        ufile.type = mpf.getContentType();
        ufile.name = mpf.getOriginalFilename();
    } catch (IOException e) {
    }
    // Convert upload content to string
    uploadToString = new String(ufile.bytes);
    uploadToString = JSONObject.escape(uploadToString);
    lexicon = request.getParameter("lexicon");
    org.nhind.config.PolicyLexicon lex = null;
    // Check the file for three types of policies
    if (lexicon.isEmpty()) {
        lex = org.nhind.config.PolicyLexicon.SIMPLE_TEXT_V1;
    } else {
        try {
            // Convert string of file contents to lexicon object
            lex = org.nhind.config.PolicyLexicon.fromString(lexicon);
        } catch (Exception e) {
            log.error("Invalid lexicon name.");
        }
    }
    // Determine lexicon type
    if (lex.equals(org.nhind.config.PolicyLexicon.JAVA_SER)) {
        parseLexicon = org.nhindirect.policy.PolicyLexicon.JAVA_SER;
    } else if (lex.equals(org.nhind.config.PolicyLexicon.SIMPLE_TEXT_V1)) {
        parseLexicon = org.nhindirect.policy.PolicyLexicon.SIMPLE_TEXT_V1;
    } else {
        parseLexicon = org.nhindirect.policy.PolicyLexicon.XML;
    }
    InputStream inStr = null;
    try {
        // Convert policy file upload to byte stream
        inStr = new ByteArrayInputStream(ufile.bytes);
        // Initialize parser engine
        final PolicyLexiconParser parser = PolicyLexiconParserFactory.getInstance(parseLexicon);
        // Attempt to parse the lexicon file for validity
        parser.parse(inStr);
    } catch (PolicyParseException e) {
        log.error("Syntax error in policy file " + " : " + e.getMessage());
        jsonResponse = "{\"Status\":\"File was not a valid file.\",\"Content\":\"" + uploadToString + "\"}";
    } finally {
        IOUtils.closeQuietly(inStr);
    }
    if (jsonResponse.isEmpty()) {
        jsonResponse = "{\"Status\":\"Success\",\"Content\":\"" + uploadToString + "\"}";
    }
    return jsonResponse;
}
Also used : PolicyLexicon(org.nhindirect.policy.PolicyLexicon) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PolicyParseException(org.nhindirect.policy.PolicyParseException) MalformedURLException(java.net.MalformedURLException) ServiceException(org.nhindirect.common.rest.exceptions.ServiceException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) FileUploadException(org.apache.commons.fileupload.FileUploadException) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) ByteArrayInputStream(java.io.ByteArrayInputStream) PolicyLexiconParser(org.nhindirect.policy.PolicyLexiconParser) PolicyParseException(org.nhindirect.policy.PolicyParseException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 54 with ResponseBody

use of org.springframework.web.bind.annotation.ResponseBody in project symmetric-ds by JumpMind.

the class RestService method invokeJob.

/**
     * Execute the named job.  This can be used to control when jobs are run via and external application.  You would typically 
     * disable the job first so it no longer runs automatically.  
     */
@ApiOperation(value = "Execute the named job.  This can be used to control when jobs are run via and external application.  " + "You would typically disable the job first so it no longer runs automatically.  Jobs you might want to control include: " + "job.route, job.push, job.pull, job.offline.push, job.offline.pull")
@RequestMapping(value = "engine/{engine}/invokejob", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public boolean invokeJob(@PathVariable("engine") String engineName, @RequestParam("jobname") String jobName) {
    IJobManager jobManager = getSymmetricEngine(engineName).getJobManager();
    IJob job = jobManager.getJob(jobName);
    if (job == null) {
        log.warn("Could not find a job with the name '{}' in the '{}' engine", jobName, engineName);
        return false;
    } else if (!job.isRunning()) {
        log.info("Invoking '{}' via the REST API", jobName);
        return job.invoke(true);
    } else {
        log.info("Could not invoke the '{}' job via the REST API because it is already running", jobName);
        return false;
    }
}
Also used : IJob(org.jumpmind.symmetric.job.IJob) IJobManager(org.jumpmind.symmetric.job.IJobManager) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 55 with ResponseBody

use of org.springframework.web.bind.annotation.ResponseBody in project geode by apache.

the class FunctionAccessController method execute.

/**
   * Execute a function on Gemfire data node using REST API call. Arguments to the function are
   * passed as JSON string in the request body.
   * 
   * @param functionId represents function to be executed
   * @param region list of regions on which function to be executed.
   * @param members list of nodes on which function to be executed.
   * @param groups list of groups on which function to be executed.
   * @param filter list of keys which the function will use to determine on which node to execute
   *        the function.
   * @param argsInBody function argument as a JSON document
   *
   * @return result as a JSON document
   */
@RequestMapping(method = RequestMethod.POST, value = "/{functionId:.+}", produces = { MediaType.APPLICATION_JSON_VALUE })
@ApiOperation(value = "execute function", notes = "Execute function with arguments on regions, members, or group(s). By default function will be executed on all nodes if none of (onRegion, onMembers, onGroups) specified", response = void.class)
@ApiResponses({ @ApiResponse(code = 200, message = "OK."), @ApiResponse(code = 401, message = "Invalid Username or Password."), @ApiResponse(code = 403, message = "Insufficient privileges for operation."), @ApiResponse(code = 500, message = "if GemFire throws an error or exception"), @ApiResponse(code = 400, message = "if Function arguments specified as JSON document in the request body is invalid") })
@ResponseBody
@ResponseStatus(HttpStatus.OK)
@PreAuthorize("@securityService.authorize('DATA', 'WRITE')")
public ResponseEntity<String> execute(@PathVariable("functionId") String functionId, @RequestParam(value = "onRegion", required = false) String region, @RequestParam(value = "onMembers", required = false) final String[] members, @RequestParam(value = "onGroups", required = false) final String[] groups, @RequestParam(value = "filter", required = false) final String[] filter, @RequestBody(required = false) final String argsInBody) {
    Execution function = null;
    functionId = decode(functionId);
    if (StringUtils.hasText(region)) {
        logger.debug("Executing Function ({}) with arguments ({}) on Region ({})...", functionId, ArrayUtils.toString(argsInBody), region);
        region = decode(region);
        try {
            function = FunctionService.onRegion(getRegion(region));
        } catch (FunctionException fe) {
            throw new GemfireRestException(String.format("The Region identified by name (%1$s) could not found!", region), fe);
        }
    } else if (ArrayUtils.isNotEmpty(members)) {
        logger.debug("Executing Function ({}) with arguments ({}) on Member ({})...", functionId, ArrayUtils.toString(argsInBody), ArrayUtils.toString(members));
        try {
            function = FunctionService.onMembers(getMembers(members));
        } catch (FunctionException fe) {
            throw new GemfireRestException("Could not found the specified members in distributed system!", fe);
        }
    } else if (ArrayUtils.isNotEmpty(groups)) {
        logger.debug("Executing Function ({}) with arguments ({}) on Groups ({})...", functionId, ArrayUtils.toString(argsInBody), ArrayUtils.toString(groups));
        try {
            function = FunctionService.onMembers(groups);
        } catch (FunctionException fe) {
            throw new GemfireRestException("no member(s) are found belonging to the provided group(s)!", fe);
        }
    } else {
        // Default case is to execute function on all existing data node in DS, document this.
        logger.debug("Executing Function ({}) with arguments ({}) on all Members...", functionId, ArrayUtils.toString(argsInBody));
        try {
            function = FunctionService.onMembers(getAllMembersInDS());
        } catch (FunctionException fe) {
            throw new GemfireRestException("Distributed system does not contain any valid data node to run the specified  function!", fe);
        }
    }
    if (!ArrayUtils.isEmpty(filter)) {
        logger.debug("Executing Function ({}) with filter ({})", functionId, ArrayUtils.toString(filter));
        Set filter1 = ArrayUtils.asSet(filter);
        function = function.withFilter(filter1);
    }
    final ResultCollector<?, ?> results;
    try {
        if (argsInBody != null) {
            Object[] args = jsonToObjectArray(argsInBody);
            // execute function with specified arguments
            if (args.length == 1) {
                results = function.setArguments(args[0]).execute(functionId);
            } else {
                results = function.setArguments(args).execute(functionId);
            }
        } else {
            // execute function with no args
            results = function.execute(functionId);
        }
    } catch (ClassCastException cce) {
        throw new GemfireRestException("Key is of an inappropriate type for this region!", cce);
    } catch (NullPointerException npe) {
        throw new GemfireRestException("Specified key is null and this region does not permit null keys!", npe);
    } catch (LowMemoryException lme) {
        throw new GemfireRestException("Server has encountered low memory condition!", lme);
    } catch (IllegalArgumentException ie) {
        throw new GemfireRestException("Input parameter is null! ", ie);
    } catch (FunctionException fe) {
        throw new GemfireRestException("Server has encountered error while executing the function!", fe);
    }
    try {
        final HttpHeaders headers = new HttpHeaders();
        headers.setLocation(toUri("functions", functionId));
        Object functionResult = null;
        if (results instanceof NoResult)
            return new ResponseEntity<>("", headers, HttpStatus.OK);
        functionResult = results.getResult();
        if (functionResult instanceof List<?>) {
            try {
                @SuppressWarnings("unchecked") String functionResultAsJson = JSONUtils.convertCollectionToJson((ArrayList<Object>) functionResult);
                return new ResponseEntity<>(functionResultAsJson, headers, HttpStatus.OK);
            } catch (JSONException e) {
                throw new GemfireRestException("Could not convert function results into Restful (JSON) format!", e);
            }
        } else {
            throw new GemfireRestException("Function has returned results that could not be converted into Restful (JSON) format!");
        }
    } catch (FunctionException fe) {
        fe.printStackTrace();
        throw new GemfireRestException("Server has encountered an error while processing function execution!", fe);
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) Set(java.util.Set) FunctionException(org.apache.geode.cache.execute.FunctionException) JSONException(org.json.JSONException) GemfireRestException(org.apache.geode.rest.internal.web.exception.GemfireRestException) ResponseEntity(org.springframework.http.ResponseEntity) Execution(org.apache.geode.cache.execute.Execution) ArrayList(java.util.ArrayList) List(java.util.List) NoResult(org.apache.geode.internal.cache.execute.NoResult) LowMemoryException(org.apache.geode.cache.LowMemoryException) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ApiResponses(io.swagger.annotations.ApiResponses) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Aggregations

ResponseBody (org.springframework.web.bind.annotation.ResponseBody)1991 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)1700 HashMap (java.util.HashMap)458 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)212 IOException (java.io.IOException)207 JSONObject (com.alibaba.fastjson.JSONObject)200 Map (java.util.Map)172 ApiOperation (io.swagger.annotations.ApiOperation)170 ArrayList (java.util.ArrayList)169 GetMapping (org.springframework.web.bind.annotation.GetMapping)112 ResponseEntity (org.springframework.http.ResponseEntity)102 ApiRest (build.dream.common.api.ApiRest)101 ResultCodeException (eu.bcvsolutions.idm.core.api.exception.ResultCodeException)101 AuthPassport (com.ngtesting.platform.util.AuthPassport)99 PostMapping (org.springframework.web.bind.annotation.PostMapping)94 ResponseStatus (org.springframework.web.bind.annotation.ResponseStatus)87 Date (java.util.Date)81 UserVo (com.ngtesting.platform.vo.UserVo)78 LogDetail (com.bc.pmpheep.annotation.LogDetail)71 ResponseBean (com.bc.pmpheep.controller.bean.ResponseBean)65