Java Code Examples for org.springframework.http.ResponseEntity

The following examples show how to use org.springframework.http.ResponseEntity. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * The handleMethodArgumentNotValid method creates a response with a list of messages that contains the fields with errors
 *
 * @param exception MethodArgumentNotValidException
 * @return 400 and a list of messages with invalid fields
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiMessageView> handleMethodArgumentNotValid(MethodArgumentNotValidException exception) {
    List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
    List<Object[]> messages = new ArrayList<>();

    for (FieldError fieldError : fieldErrors) {
        Object[] messageFields = new Object[3];
        messageFields[0] = fieldError.getField();
        messageFields[1] = fieldError.getRejectedValue();
        messageFields[2] = fieldError.getDefaultMessage();
        messages.add(messageFields);
    }

    List<ApiMessage> listApiMessage = messageService
        .createMessage("org.zowe.apiml.sampleservice.api.petMethodArgumentNotValid", messages)
        .stream()
        .map(Message::mapToApiMessage)
        .collect(Collectors.toList());

    return ResponseEntity
        .status(HttpStatus.BAD_REQUEST)
        .contentType(MediaType.APPLICATION_JSON_UTF8)
        .body(new ApiMessageView(listApiMessage));
}
 
Example 2
Source Project: openapi-generator   Source File: FakeClassnameTestApi.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * PATCH /fake_classname_test : To test class name in snake case
 * To test class name in snake case
 *
 * @param body client model (required)
 * @return successful operation (status code 200)
 */
@ApiVirtual
@ApiOperation(value = "To test class name in snake case", nickname = "testClassname", notes = "To test class name in snake case", response = Client.class, authorizations = {
    @Authorization(value = "api_key_query")
}, tags={ "fake_classname_tags 123#$%^", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "successful operation", response = Client.class) })
@RequestMapping(value = "/fake_classname_test",
    produces = { "application/json" }, 
    consumes = { "application/json" },
    method = RequestMethod.PATCH)
default ResponseEntity<Client> testClassname(@ApiParam(value = "client model" ,required=true )  @Valid @RequestBody Client body) {
    getRequest().ifPresent(request -> {
        for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) {
            if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
                String exampleString = "{ \"client\" : \"client\" }";
                ApiUtil.setExampleResponse(request, "application/json", exampleString);
                break;
            }
        }
    });
    return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);

}
 
Example 3
/**
 * Sets the.
 *
 * @param name
 *        the name
 * @param level
 *        the level
 * @return the response entity
 */
@RequestMapping(value = "set/{name}/{level}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET,
    headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<LogResponse> set(@PathVariable("name")
final String name, @PathVariable("level")
final Level level) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    synchronized (ctx) {
        final Configuration config = ctx.getConfiguration();
        LoggerConfig loggerConfig = config.getLoggerConfig(name);
        if (name.equalsIgnoreCase(loggerConfig.getName())) {
            loggerConfig.setLevel(level);
        } else {
            LoggerConfig newloggerConfig = new LoggerConfig(name, level, true);
            config.addLogger(name, newloggerConfig);
        }
        ctx.updateLoggers();
    }
    return new ResponseEntity<>(listLoggers(ctx), HttpStatus.OK);
}
 
Example 4
Source Project: poli   Source File: JdbcQueryWs.java    License: MIT License 6 votes vote down vote up
@RequestMapping(
        value = "/component/{id}",
        method = RequestMethod.POST,
        produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<QueryResult> queryComponent(
        @PathVariable("id") long componentId,
        @RequestBody List<FilterParameter> filterParams,
        HttpServletRequest request
) {
    Component component = componentDao.findById(componentId);
    if (component.getJdbcDataSourceId() == 0) {
        return new ResponseEntity(QueryResult.ofError(Constants.ERROR_NO_DATA_SOURCE_FOUND), HttpStatus.OK);
    }

    boolean isAccessValid = isComponentAccessValid(component, request);
    if (isAccessValid) {
        String sql = component.getSqlQuery();
        DataSource dataSource = jdbcDataSourceService.getDataSource(component.getJdbcDataSourceId());
        User user = (User) request.getAttribute(Constants.HTTP_REQUEST_ATTR_USER);
        List<FilterParameter> newFilterParams = addUserAttributesToFilterParams(user.getUserAttributes(), filterParams);
        QueryResult queryResult = jdbcQueryService.queryByParams(dataSource, sql, newFilterParams, Constants.QUERY_RESULT_NOLIMIT);
        return new ResponseEntity(queryResult, HttpStatus.OK);
    }

    return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
 
Example 5
@Test
public void testIdmRestApiIntegrationWithAuthentication() {
    String processDefinitionsUrl = "http://localhost:" + serverPort + "/idm-api/groups";

    HttpEntity<?> request = new HttpEntity<>(createHeaders("filiphr", "password"));
    ResponseEntity<DataResponse<GroupResponse>> response = restTemplate
        .exchange(processDefinitionsUrl, HttpMethod.GET, request, new ParameterizedTypeReference<DataResponse<GroupResponse>>() {
        });

    assertThat(response.getStatusCode())
        .as("Status code")
        .isEqualTo(HttpStatus.OK);
    DataResponse<GroupResponse> groups = response.getBody();
    assertThat(groups).isNotNull();
    assertThat(groups.getData())
        .extracting(GroupResponse::getId, GroupResponse::getType, GroupResponse::getName, GroupResponse::getUrl)
        .containsExactlyInAnyOrder(
            tuple("user", "security-role", "users", null),
            tuple("admin", "security-role", "admin", null)
        );
    assertThat(groups.getTotal()).isEqualTo(2);
}
 
Example 6
Source Project: pacbot   Source File: AssetDetailController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Fetches the details from a particular data source for a particular resource for given assetGroup
 * 
 * @param ag name of the asset group
 * @param resourceType type of the resource
 * @param resourceId id of the resource
 * 
 * @return details of ec2 resource
 */

@ApiOperation(httpMethod = "GET", value = "Get the details from a particular data source for a particular  resource")
@GetMapping(value = "v1/{assetGroup}/{resourceType}/{resourceId}/details")
public ResponseEntity<Object> getEc2ResourceDetail(@PathVariable(name = "assetGroup", required = true) String ag,
        @PathVariable(name = "resourceType", required = true) String resourceType,
        @PathVariable(name = "resourceId", required = true) String resourceId) {
    Map<String, Object> assetDetail;

    try {
        if ("ec2".equals(resourceType)) {
            assetDetail = assetService.getEc2ResourceDetail(ag, resourceId);
        } else {
            assetDetail = assetService.getGenericResourceDetail(ag, resourceType, resourceId);
        }
    } catch (Exception e) {
        LOGGER.error("Error in getEc2ResourceDetail ",e);
        assetDetail = new HashMap<>();
    }
    return ResponseUtils.buildSucessResponse(assetDetail);
}
 
Example 7
Source Project: blue-marlin   Source File: IMSController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This end-point returns hourly traffic (number of impressions) for a targeting channel.
 *
 * @param payload
 * @return
 * @throws JSONException
 */
@RequestMapping(value = "/api/chart", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity chart(@RequestBody IMSRequestQuery payload) throws JSONException
{
    DayImpression result;
    try
    {
        result = inventoryEstimateService.getInventoryDateEstimate(payload.getTargetingChannel());
    }
    catch (Exception e)
    {
        LOGGER.error(e.getMessage());
        return ResponseBuilder.buildError(e);
    }
    return ResponseBuilder.build(result, HTTP_OK_CODE);
}
 
Example 8
Source Project: portal-de-servicos   Source File: Siorg.java    License: MIT License 6 votes vote down vote up
@Cacheable("unidades-siorg")
public Unidade findUnidade(String unsafeId) {
    long orgaoId = orgaoUtils.obterId(unsafeId);

    String url = BASE_URL + orgaoId;

    ResponseEntity<Orgao> entity = restTemplate.getForEntity(url, Orgao.class);
    Orgao body = entity.getBody();

    if (body.getServico().getCodigoErro() > 0) {
        String msg = String.format("Erro ao acessar Siorg: %s", body.getServico().getMensagem());
        throw new RuntimeException(msg);
    }

    return body.getUnidade();
}
 
Example 9
@Override
public Integer register(Schema schema) {
	String path = String.format("/subjects/%s/versions",schema.getFullName());
	HttpHeaders headers = new HttpHeaders();
	headers.put("Accept", Arrays.asList("application/vnd.schemaregistry.v1+json","application/vnd.schemaregistry+json","application/json"));
	headers.add("Content-Type","application/json");
	Integer id = null;
	try {
		String payload = mapper.writeValueAsString(Collections.singletonMap("schema",schema.toString()));
		HttpEntity<String> request = new HttpEntity<>(payload,headers);
		ResponseEntity<Map> response = template.exchange(endpoint+path, HttpMethod.POST,request, Map.class);
		id = (Integer)response.getBody().get("id");
	}
	catch (JsonProcessingException e) {
		e.printStackTrace();
	}
	return id;
}
 
Example 10
Source Project: alf.io   Source File: PaymentApiController.java    License: GNU General Public License v3.0 6 votes vote down vote up
@PostMapping("/api/events/{eventName}/reservation/{reservationId}/payment/{method}/init")
public ResponseEntity<TransactionInitializationToken> initTransaction(@PathVariable("eventName") String eventName,
                                                                      @PathVariable("reservationId") String reservationId,
                                                                      @PathVariable("method") String paymentMethodStr,
                                                                      @RequestParam MultiValueMap<String, String> allParams) {

    var paymentMethod = PaymentMethod.safeParse(paymentMethodStr);
    if (paymentMethod == null) {
        return ResponseEntity.badRequest().build();
    }

    return getEventReservationPair(eventName, reservationId)
        .flatMap(pair -> ticketReservationManager.initTransaction(pair.getLeft(), reservationId, paymentMethod, allParams))
        .map(ResponseEntity::ok)
        .orElseGet(() -> ResponseEntity.notFound().build());
}
 
Example 11
Source Project: apollo   Source File: ItemSetController.java    License: Apache License 2.0 5 votes vote down vote up
@PreAcquireNamespaceLock
@PostMapping("/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/itemset")
public ResponseEntity<Void> create(@PathVariable String appId, @PathVariable String clusterName,
                                   @PathVariable String namespaceName, @RequestBody ItemChangeSets changeSet) {

  itemSetService.updateSet(appId, clusterName, namespaceName, changeSet);

  return ResponseEntity.status(HttpStatus.OK).build();
}
 
Example 12
Source Project: java-crud-api   Source File: ColumnController.java    License: MIT License 5 votes vote down vote up
@RequestMapping(value = "/{table}/{column}", method = RequestMethod.GET)
public ResponseEntity<?> getColumn(@PathVariable("table") String tableName, @PathVariable("column") String columnName) {
	logger.info("Requesting columns meta data");
	if (!service.hasTable(tableName)) {
		return responder.error(ErrorCode.TABLE_NOT_FOUND, tableName);
	}
	ReflectedTable table = service.getTable(tableName);
	if (!table.exists(columnName)) {
		return responder.error(ErrorCode.COLUMN_NOT_FOUND, columnName);
	}
	return responder.success(table.get(columnName));
}
 
Example 13
Source Project: cubeai   Source File: SolutionResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * GET  /solutions/:id : get the "id" solution.
 * @param id the id of the solution to retrieve
 * @return the ResponseEntity with status 200 (OK) and with body the solution, or with status 404 (Not Found)
 */
@GetMapping("/solutions/{id}")
@Timed
public ResponseEntity<Solution> getSolution(@PathVariable Long id) {
    log.debug("REST request to get Solution : {}", id);
    Solution solution = solutionRepository.findOne(id);
    return ResponseUtil.wrapOrNotFound(Optional.ofNullable(solution));
}
 
Example 14
Source Project: leyou   Source File: GoodsController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 通过spu_id删除商品goods
 *
 * @param spuId
 * @return
 */
@DeleteMapping("/goods/{spuId}")
public ResponseEntity<Void> deleteGoods(@PathVariable("spuId") Long spuId) {
    try {
        this.goodsService.deleteGoods(spuId);
        return ResponseEntity.ok().build();
    } catch (Exception e) {
        e.printStackTrace();
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
 
Example 15
@Test
public void ambiguousProducesPreflightRequest() throws Exception {
	this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
	ResponseEntity<String> entity = performOptions("/ambiguous-produces", this.headers, String.class);

	assertEquals(HttpStatus.OK, entity.getStatusCode());
	assertEquals("https://site1.com", entity.getHeaders().getAccessControlAllowOrigin());
	assertArrayEquals(new HttpMethod[] {HttpMethod.GET},
			entity.getHeaders().getAccessControlAllowMethods().toArray());
	assertTrue(entity.getHeaders().getAccessControlAllowCredentials());
}
 
Example 16
Source Project: biliob_backend   Source File: TracerServiceImpl.java    License: MIT License 5 votes vote down vote up
/**
 * It is the function to get authors' queue status.
 *
 * @return The authors' queue status.
 */
@Override
public ResponseEntity getAuthorQueueStatus() {
    Map<String, Long> result = new HashMap<>(1);
    Long authorCrawlTasksQueueLength = redisOps.getAuthorQueueLength();
    result.put("length", authorCrawlTasksQueueLength);
    return new ResponseEntity<>(result, HttpStatus.OK);
}
 
Example 17
@Permission(type = ResourceType.PROJECT, roles = InitRoleCode.PROJECT_OWNER)
@ApiOperation("创建component")
@PostMapping
public ResponseEntity<IssueComponentVO> createComponent(@ApiParam(value = "项目id", required = true)
                                                         @PathVariable(name = "project_id") Long projectId,
                                                        @ApiParam(value = "components对象", required = true)
                                                         @RequestBody IssueComponentVO issueComponentVO) {
    return Optional.ofNullable(issueComponentService.create(projectId, issueComponentVO))
            .map(result -> new ResponseEntity<>(result, HttpStatus.CREATED))
            .orElseThrow(() -> new CommonException("error.component.create"));
}
 
Example 18
/**
 * Delete by id UseCase2.
 */
@RequestMapping(value = "/{id}", method = DELETE, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Void> delete(@PathVariable String id) throws URISyntaxException {

    log.debug("Delete by id UseCase2 : {}", id);

    try {
        useCase2Repository.delete(id);
        return ResponseEntity.ok().build();
    } catch (Exception x) {
        // todo: dig exception, most likely org.hibernate.exception.ConstraintViolationException
        return ResponseEntity.status(HttpStatus.CONFLICT).build();
    }
}
 
Example 19
Source Project: cf-butler   Source File: OrganizationController.java    License: Apache License 2.0 5 votes vote down vote up
@GetMapping("/snapshot/organizations")
public Mono<ResponseEntity<List<Organization>>> listAllOrganizations() {
    return util.getHeaders()
            .flatMap(h -> organizationService
                                .findAll()
                                .collectList()
                                .map(orgs -> new ResponseEntity<>(orgs, h, HttpStatus.OK)))
                                .defaultIfEmpty(ResponseEntity.notFound().build());
}
 
Example 20
/**
 * Test the GET /v1/booking/{id} API for no content
 */
@Test
public void testGetById_NoContent() {

  HttpHeaders headers = new HttpHeaders();
  HttpEntity<Object> entity = new HttpEntity<>(headers);
  ResponseEntity<Map> responseE = restTemplate
      .exchange("http://localhost:" + port + "/v1/booking/99", HttpMethod.GET, entity, Map.class);

  assertNotNull(responseE);

  // Should return no content as there is no booking with id 99
  assertEquals(HttpStatus.NO_CONTENT, responseE.getStatusCode());
}
 
Example 21
Source Project: swagger-aem   Source File: PathApi.java    License: Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "", nickname = "getNode", notes = "", authorizations = {
    @Authorization(value = "aemAuth")
}, tags={ "sling", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "Default response") })
@RequestMapping(value = "/{path}/{name}",
    method = RequestMethod.GET)
default ResponseEntity<Void> getNode(@ApiParam(value = "",required=true) @PathVariable("path") String path,@ApiParam(value = "",required=true) @PathVariable("name") String name) {
    return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);

}
 
Example 22
Source Project: multiapps-controller   Source File: OperationsApi.java    License: Apache License 2.0 5 votes vote down vote up
@GetMapping(path = Endpoints.OPERATION_LOG_CONTENT, produces = MediaType.TEXT_PLAIN_VALUE)
@ApiOperation(value = "", nickname = "getMtaOperationLogContent", notes = "Retrieves the log content for Multi-Target Application operation ", response = String.class, authorizations = {
    @Authorization(value = "oauth2", scopes = {

    }) }, tags = {})
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = String.class) })
public ResponseEntity<String> getOperationLogContent(@PathVariable(PathVariables.SPACE_GUID) String spaceGuid,
                                                     @PathVariable(PathVariables.OPERATION_ID) String operationId,
                                                     @PathVariable(PathVariables.LOG_ID) String logId) {
    return delegate.getOperationLogContent(spaceGuid, operationId, logId);
}
 
Example 23
Source Project: mail-micro-service   Source File: MailLocalhostTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSendAttachmentMailLocal() throws Throwable {
    File folder = new File("F://");
    if (!folder.exists() || !folder.isDirectory()) {
        FileUtils.forceMkdir(folder);
    }

    File attachmentFile = new File(folder, "1.txt");
    if (attachmentFile.exists() && attachmentFile.isFile()) {
        FileUtils.forceDelete(attachmentFile);
    }

    FileUtils.writeStringToFile(attachmentFile, "hello \r\n mail \r\n" +
            RandomStringUtils.random(10), "utf8");
    attachmentFile.createNewFile();

    MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
    param.add("to", TEST_MAIL);
    param.add("title", RandomStringUtils.random(5));
    param.add("content", RandomStringUtils.random(256));
    param.add("attachmentName", RandomStringUtils.random(4) + ".txt");

    FileSystemResource resource = new FileSystemResource(attachmentFile);
    param.add("attachmentFile", resource);

    HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(param);

    RestTemplate rest = new RestTemplate();
    ResponseEntity<Boolean> response = rest.exchange(MAIL_URL, HttpMethod.POST,
            httpEntity, Boolean.class);

    assertTrue(response.getBody());
}
 
Example 24
Source Project: dew   Source File: WebTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testResponseFormat() throws Exception {
    Resp<String> result = Resp.generic(testRestTemplate.getForObject("/test/success?q=TEST", Resp.class), String.class);
    Assert.assertEquals("successful", result.getBody());
    result = Resp.generic(testRestTemplate.getForObject("/test/badRequest?q=TEST", Resp.class), String.class);
    Assert.assertEquals("badrequest", result.getMessage());
    ResponseEntity<Resp> resultEntity = testRestTemplate.getForEntity("/test/customError?q=TEST", Resp.class);
    Assert.assertEquals(500, resultEntity.getStatusCodeValue());
    Assert.assertEquals("A000", resultEntity.getBody().getCode());
    resultEntity = testRestTemplate.getForEntity("/test/customHttpState?q=TEST", Resp.class);
    Assert.assertEquals(401, resultEntity.getStatusCodeValue());
    Assert.assertEquals("A000", resultEntity.getBody().getCode());
}
 
Example 25
@Permission(type = ResourceType.PROJECT, roles = {InitRoleCode.PROJECT_MEMBER, InitRoleCode.PROJECT_OWNER})
@ApiOperation(value = "查询所有版本名及要删除版本issue统计")
@GetMapping(value = "/{versionId}/names")
public ResponseEntity<VersionMessageVO> queryDeleteMessageByVersionId(@ApiParam(value = "项目id", required = true)
                                                                       @PathVariable(name = "project_id") Long projectId,
                                                                      @ApiParam(value = "versionId", required = true)
                                                                       @PathVariable Long versionId) {
    return Optional.ofNullable(productVersionService.queryDeleteMessageByVersionId(projectId, versionId))
            .map(result -> new ResponseEntity<>(result, HttpStatus.OK))
            .orElseThrow(() -> new CommonException(QUERY_VERSION_NAME_ERROR));
}
 
Example 26
Source Project: pacbot   Source File: VulnerabilityController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the vulnerabilities trend.
 *
 * @param request
 *            the request
 * @return ResponseEntity<Object>
 */

@PostMapping(value = "/v1/vulnerabilities/trend")
public ResponseEntity<Object> getVulnerabilitiesTrend(@RequestBody(required = true) TrendRequest request) {

	Map<String, Object> response = new HashMap<>();
	String assetGroup = request.getAg();
	if (Strings.isNullOrEmpty(assetGroup)) {
		return ResponseUtils.buildFailureResponse(new Exception(ASSET_MANDATORY));
	}
	Date from = request.getFrom();
	Date to = request.getTo();
	Map<String, String> filter = request.getFilter();
	try {
		if (from == null && to == null) {
			Calendar cal = Calendar.getInstance();
			cal.setTimeZone(TimeZone.getTimeZone("UTC"));
			to = cal.getTime();
			cal.add(Calendar.DATE, NEG_THIRTY);
			from = cal.getTime();
		}
		response.put("ag", assetGroup);
		List<Map<String, Object>> trendList = vulnerabilityService.getVulnerabilityTrend(assetGroup, filter, from,
				to);
		response.put("trend", trendList);
	} catch (Exception e) {
		LOGGER.error(EXE_VULN, e);
		return ResponseUtils.buildFailureResponse(e);
	}
	return ResponseUtils.buildSucessResponse(response);
}
 
Example 27
Source Project: pacbot   Source File: TrendController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the vulnerabilities trend.This request expects asset group and from
 * as mandatory.If API receives asset group and from as request parameters,
 * it gives weekly based details of compliance trend from mentioned date to
 * till date for vulnerabilities
 *
 * @param request
 *            the request
 * @return ResponseEntity
 */

@RequestMapping(path = "/v1/trend/compliance/vulnerabilities", method = RequestMethod.POST)
public ResponseEntity<Object> getVulnTrend(@RequestBody(required = true) CompliantTrendRequest request) {

    Map<String, Object> response = new HashMap<>();
    String assetGroup = request.getAg();

    Date input = request.getFrom();

    if (input == null) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));
        cal.add(Calendar.DATE, NEG_THIRTY);
        input = cal.getTime();
    }

    Instant instant = input.toInstant();
    ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
    LocalDate fromDate = zdt.toLocalDate();
    LocalDate toDate = LocalDate.now();

    if (Strings.isNullOrEmpty(assetGroup)) {
        return ResponseUtils.buildFailureResponse(new Exception(ASSET_MANDATORY));
    }

    try {
        Map<String, Object> ruleTrendProgressList = trendService.getTrendProgress(assetGroup, null, fromDate,
                toDate, "vulncompliance");
        response.put(RESPONSE, ruleTrendProgressList);
    } catch (ServiceException e) {
        LOGGER.error("Exception in getVulnTrend" , e.getMessage());
        return ResponseUtils.buildFailureResponse(e);
    }
    return ResponseUtils.buildSucessResponse(response);
}
 
Example 28
Source Project: nimrod   Source File: FileRestController.java    License: MIT License 5 votes vote down vote up
/**
 * 指定文件 id,获取文件
 *
 * @param id 文件 id
 * @return ResponseEntity<FileEntity>
 */
@OperationLog(value = "指定文件 id,获取文件", type = OperationLogType.API)
@PreAuthorize("hasRole('" + SYSTEM_ADMIN + "') OR hasAuthority('" + FILE + "/ONE')")
@GetMapping(value = "/one/{id}")
public ResponseEntity<FileEntity> getOne(@PathVariable Long id) {
    return new ResponseEntity<>(fileService.getOne(id), HttpStatus.OK);
}
 
Example 29
@Test
public void adminLoads() {
	HttpHeaders headers = new HttpHeaders();
	headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

	@SuppressWarnings("rawtypes")
	ResponseEntity<Map> entity = new TestRestTemplate().exchange(
			"http://localhost:" + this.port + "/servlet" + BASE_PATH + "/env",
			HttpMethod.GET, new HttpEntity<>("parameters", headers), Map.class);
	assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
}
 
Example 30
Source Project: spring-data-dev-tools   Source File: GitHub.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Apply a {@link Predicate callback} with GitHub paging starting at {@code endpointUri}. The given
 * {@link Predicate#test(Object)} outcome controls whether paging continues by returning {@literal true} or stops.
 *
 * @param endpointUri
 * @param method
 * @param parameters
 * @param entity
 * @param type
 * @param callbackContinue
 * @param <T>
 */
private <T> void doWithPaging(String endpointUri, HttpMethod method, Map<String, Object> parameters,
		HttpEntity<?> entity, ParameterizedTypeReference<T> type, Predicate<T> callbackContinue) {

	ResponseEntity<T> exchange = operations.exchange(endpointUri, method, entity, type, parameters);

	Pattern pattern = Pattern.compile("<([^ ]*)>; rel=\"(\\w+)\"");

	while (true) {

		if (!callbackContinue.test(exchange.getBody())) {
			return;
		}

		HttpHeaders responseHeaders = exchange.getHeaders();
		List<String> links = responseHeaders.getValuesAsList("Link");

		if (links.isEmpty()) {
			return;
		}

		String nextLink = null;
		for (String link : links) {

			Matcher matcher = pattern.matcher(link);
			if (matcher.find()) {
				if (matcher.group(2).equals("next")) {
					nextLink = matcher.group(1);
					break;
				}
			}
		}

		if (nextLink == null) {
			return;
		}

		exchange = operations.exchange(nextLink, method, entity, type, parameters);
	}
}