类org.springframework.http.ResponseEntity源码实例Demo

下面列出了怎么用org.springframework.http.ResponseEntity的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: api-layer   文件: PetControllerExceptionHandler.java
/**
 * 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));
}
 
源代码2 项目: openapi-generator   文件: FakeClassnameTestApi.java
/**
 * 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);

}
 
源代码3 项目: GreenSummer   文件: Log4JController.java
/**
 * 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);
}
 
源代码4 项目: poli   文件: JdbcQueryWs.java
@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);
}
 
@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);
}
 
源代码6 项目: pacbot   文件: AssetDetailController.java
/**
 * 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);
}
 
源代码7 项目: blue-marlin   文件: IMSController.java
/**
 * 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);
}
 
源代码8 项目: portal-de-servicos   文件: Siorg.java
@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();
}
 
@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;
}
 
源代码10 项目: alf.io   文件: PaymentApiController.java
@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());
}
 
源代码11 项目: apollo   文件: ItemSetController.java
@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();
}
 
源代码12 项目: java-crud-api   文件: ColumnController.java
@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));
}
 
源代码13 项目: cubeai   文件: SolutionResource.java
/**
 * 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));
}
 
源代码14 项目: leyou   文件: GoodsController.java
/**
 * 通过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);
    }
}
 
@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());
}
 
源代码16 项目: biliob_backend   文件: TracerServiceImpl.java
/**
 * 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);
}
 
@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"));
}
 
/**
 * 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();
    }
}
 
源代码19 项目: cf-butler   文件: OrganizationController.java
@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());
}
 
/**
 * 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());
}
 
源代码21 项目: swagger-aem   文件: PathApi.java
@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);

}
 
源代码22 项目: multiapps-controller   文件: OperationsApi.java
@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);
}
 
源代码23 项目: mail-micro-service   文件: MailLocalhostTest.java
@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());
}
 
源代码24 项目: dew   文件: WebTest.java
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());
}
 
@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));
}
 
源代码26 项目: pacbot   文件: VulnerabilityController.java
/**
 * 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);
}
 
源代码27 项目: pacbot   文件: TrendController.java
/**
 * 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);
}
 
源代码28 项目: nimrod   文件: FileRestController.java
/**
 * 指定文件 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);
}
 
@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);
}
 
源代码30 项目: spring-data-dev-tools   文件: GitHub.java
/**
 * 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);
	}
}
 
 类所在包
 同包方法