@RequestMapping(value = "/employee", method = { RequestMethod.POST }, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<MyResponse> addEmployee(@RequestBody Employee employee) { MyResponse resp = new MyResponse(); empService.create(employee); if(HttpStatus.OK.is2xxSuccessful()){ resp.setStatus(HttpStatus.OK.value()); resp.setMessage("Succesfuly created an employee object"); return new ResponseEntity<MyResponse>(resp, HttpStatus.OK); } else{ resp.setStatus(HttpStatus.OK.value()); resp.setMessage("Error while creating an employee object"); return new ResponseEntity<MyResponse>(resp, HttpStatus.INTERNAL_SERVER_ERROR); } }
@ResponseBody @RequestMapping(value = "/vcf/variation/load", method = RequestMethod.POST) @ApiOperation( value = "Returns extended data for a variation", notes = "Provides extended data about the particular variation: </br>" + "info field : Additional information that is presented in INFO column</br>" + "genotypeInfo field : Genotype information for a specific sample</br>", produces = MediaType.APPLICATION_JSON_VALUE) @ApiResponses( value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION) }) public Result<Variation> loadVariation(@RequestBody final VariationQuery query, @RequestParam(required = false) final String fileUrl, @RequestParam(required = false) final String indexUrl) throws FeatureFileReadingException { if (fileUrl == null) { return Result.success(vcfManager.loadVariation(query)); } else { return Result.success(vcfManager.loadVariation(query, fileUrl, indexUrl)); } }
@Test public void testHttpAddSuccess() throws Exception { final SapClient sapClient = mockSdk.getErpSystem().getSapClient(); final String newCostCenterJson = getNewCostCenterAsJson(DEMO_COSTCENTER_ID); final RequestBuilder newCostCenterRequest = MockMvcRequestBuilders .request(HttpMethod.POST, "/api/v1/rest/client/"+sapClient+"/controllingarea/"+DEMO_CONTROLLING_AREA+"/costcenters") .param("testRun", "true") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content(newCostCenterJson); mockSdk.requestContextExecutor().execute(new Executable() { @Override public void execute() throws Exception { mockMvc.perform(newCostCenterRequest).andExpect(MockMvcResultMatchers.status().isOk()); } }); }
@Test public void testSaveTalker() throws Exception{ String talkerAsJson = this.mapper.writeValueAsString(this.talkerAny); when(this.talkerServiceMock.save(this.talkerAny)).thenReturn(this.talkerAny); ResultActions resultActions = mockMvc.perform(post("/api/talker") .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) .content(talkerAsJson)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)); assertNotNull("[resultActions] should not be null", resultActions); MockHttpServletResponse response = resultActions.andReturn().getResponse(); assertNotNull("[ContentAsString] should not be null", response.getContentAsString()); Talker talkerFromJson = this.mapper.readValue(response.getContentAsString(), Talker.class); assertEquals("[talkerFromJson] should be equals to [talkerAny]", this.talkerAny, talkerFromJson); verify(this.talkerServiceMock, times(1)).save(this.talkerAny); }
@Test public void testListenTalkBasic() throws Exception { Phrase phrase = new Phrase(); phrase.setAppContext("app_context"); phrase.setUrl("the_url"); phrase.setResponse(JSON_RESPONSE); Gson gson = new Gson(); String json = gson.toJson(phrase); // Listen mockMvc.perform(post("/listen").contentType(MediaType.APPLICATION_JSON).content(json)) .andExpect(status().isOk()) .andExpect(content().string("OK")); // Talk mockMvc.perform(get("/talk/app_context/the_url")) .andExpect(status().isOk()) .andExpect(content().string(JSON_RESPONSE)); }
@Test public void testAddPrivilegeToRole() throws Exception { final RoleEntity role = new RoleEntity() .setId("role123") .setCode("role123"); when(roleService.addPrivilegeToRole("role123", "privilege123")).thenReturn(role); ResultActions resultActions = mockMvc.perform(put("/api/roles/role123/privileges") .content("{\"privilege\": \"privilege123\"}") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andDo(document("role-privilege-create")); MockHttpServletResponse response = resultActions .andReturn() .getResponse(); verify(roleService).addPrivilegeToRole("role123", "privilege123"); assertThat(response.getContentAsByteArray()) .isEqualTo(objectMapper.writeValueAsBytes(RoleRestData.builder().fromRoleEntity(role).build())); }
@Override public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) { if (!canRead(mediaType)) { return false; } JavaType javaType = getJavaType(type, contextClass); if (!jackson23Available || !logger.isWarnEnabled()) { return this.objectMapper.canDeserialize(javaType); } AtomicReference<Throwable> causeRef = new AtomicReference<Throwable>(); if (this.objectMapper.canDeserialize(javaType, causeRef)) { return true; } Throwable cause = causeRef.get(); if (cause != null) { String msg = "Failed to evaluate Jackson deserialization for type " + javaType; if (logger.isDebugEnabled()) { logger.warn(msg, cause); } else { logger.warn(msg + ": " + cause); } } return false; }
@ResponseBody @RequestMapping(value = "/externaldb/ncbi/variation/region", method = RequestMethod.POST) @ApiOperation( value = "NCBI: Retrieves information on variations located in given interval", notes = "NCBI snp database is being queried for variations in given interval" + "in a proper way and returned by service.<br/><br/>" + PARAMETERS_NOTE + "<b>species</b> - species name (e.g. \"human\")<br/>" + "<b>chromosome</b> - chromosome name (e.g. \"1\")<br/>" + "<b>start</b> - start coordinate in a given chromosome (e.g. 140424943)<br/>" + "<b>finish</b> - end coordinate in a given chromosome (e.g. 140624564)<br/>" + RSID_DESCRIPTION_NOTE, produces = MediaType.APPLICATION_JSON_VALUE) @ApiResponses(value = { @ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION) }) public Result<List<Variation>> fetchNCBIVariationInfoOnInterval(@RequestBody final RegionQuery regionQuery) throws ExternalDbUnavailableException { String chromosome = regionQuery.getChromosome(); String start = regionQuery.getStart(); String finish = regionQuery.getFinish(); String species = regionQuery.getSpecies(); List<Variation> variations = ncbiShortVarManager.fetchVariationsOnRegion(species, start, finish, chromosome); return Result.success(variations, getMessage(SUCCESS, NCBI)); }
@Override public void save(final String userName, final String secretKey, final int validationCode, final List<Integer> scratchCodes) { final MultifactorAuthenticationProperties.GAuth.Rest rest = gauth.getRest(); final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.put("username", Arrays.asList(userName)); headers.put("validationCode", Arrays.asList(String.valueOf(validationCode))); headers.put("secretKey", Arrays.asList(secretKey)); headers.put("scratchCodes", scratchCodes.stream().map(String::valueOf).collect(Collectors.toList())); final HttpEntity<String> entity = new HttpEntity<>(headers); final ResponseEntity<Boolean> result = restTemplate.exchange(rest.getEndpointUrl(), HttpMethod.POST, entity, Boolean.class); if (result.getStatusCodeValue() == HttpStatus.OK.value()) { LOGGER.debug("Posted google authenticator account successfully"); } LOGGER.warn("Failed to save google authenticator account successfully"); }
@Override protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception { HttpServletRequest request = (HttpServletRequest) servletRequest; String token = jwtHelper.getToken(request); String username = jwtHelper.getUsernameFromToken(token); StatelessToken accessToken = new StatelessToken(username, token); try { getSubject(servletRequest, servletResponse).login(accessToken); } catch (AuthenticationException e) { HttpServletResponse response = (HttpServletResponse) servletResponse; response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); objectMapper.writeValue(response.getWriter(), Result.fail(ResultCode.UNAUTHORIZED)); return false; } getSubject(servletRequest, servletResponse).isPermitted(request.getRequestURI()); return true; }
@Test @Transactional public void getAllOperinoComponents() throws Exception { // Initialize the database operinoComponentRepository.saveAndFlush(operinoComponent); // Get all the operinoComponentList restOperinoComponentMockMvc.perform(get("/api/operino-components?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(operinoComponent.getId().intValue()))) .andExpect(jsonPath("$.[*].hosting").value(hasItem(DEFAULT_HOSTING.toString()))) .andExpect(jsonPath("$.[*].availability").value(hasItem(DEFAULT_AVAILABILITY.booleanValue()))) .andExpect(jsonPath("$.[*].applyLimits").value(hasItem(DEFAULT_APPLY_LIMITS.booleanValue()))) .andExpect(jsonPath("$.[*].recordsNumber").value(hasItem(DEFAULT_RECORDS_NUMBER.intValue()))) .andExpect(jsonPath("$.[*].transactionsLimit").value(hasItem(DEFAULT_TRANSACTIONS_LIMIT.intValue()))) .andExpect(jsonPath("$.[*].diskSpace").value(hasItem(DEFAULT_DISK_SPACE.intValue()))) .andExpect(jsonPath("$.[*].computeResourceLimit").value(hasItem(DEFAULT_COMPUTE_RESOURCE_LIMIT.intValue()))) .andExpect(jsonPath("$.[*].type").value(hasItem(DEFAULT_TYPE.toString()))); }
@Test @Transactional public void getXmEntity() throws Exception { // Initialize the database xmEntityRepository.saveAndFlush(xmEntity); // Get the xmEntity restXmEntityMockMvc.perform(get("/api/xm-entities/{id}", xmEntity.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(xmEntity.getId().intValue())) .andExpect(jsonPath("$.key").value(DEFAULT_KEY.toString())) .andExpect(jsonPath("$.typeKey").value(DEFAULT_TYPE_KEY.toString())) .andExpect(jsonPath("$.stateKey").value(DEFAULT_STATE_KEY.toString())) .andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString())) .andExpect(jsonPath("$.startDate").value(DEFAULT_START_DATE.toString())) .andExpect(jsonPath("$.updateDate").value(DEFAULT_UPDATE_DATE.toString())) .andExpect(jsonPath("$.endDate").value(DEFAULT_END_DATE.toString())) .andExpect(jsonPath("$.avatarUrl").value(containsString("aaaaa.jpg"))) .andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION.toString())) .andExpect(jsonPath("$.data.AAAAAAAAAA").value("BBBBBBBBBB")) .andExpect(jsonPath("$.removed").value(DEFAULT_REMOVED.booleanValue())); }
@RequestMapping ( "/metricIntervals/{type}" ) public void getMetricsIntervals ( @PathVariable ( value = "type" ) String reqType, HttpServletRequest request, HttpServletResponse response ) throws IOException { response.setContentType( MediaType.APPLICATION_JSON_VALUE ); ArrayNode samplesArray = jacksonMapper.createArrayNode(); String type = reqType; if ( reqType.startsWith( "jmx" ) ) { type = "jmx"; } for ( Integer sampleInterval : csapApp.lifeCycleSettings() .getMetricToSecondsMap() .get( type ) ) { samplesArray.add( sampleInterval ); } response.getWriter() .println( jacksonMapper.writeValueAsString( samplesArray ) ); }
@Test public void getStreamer() throws Exception { // Initialize the database streamerRepository.save(streamer); // Get the streamer restStreamerMockMvc.perform(get("/api/streamers/{id}", streamer.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(streamer.getId())) .andExpect(jsonPath("$.provider").value(DEFAULT_PROVIDER)) .andExpect(jsonPath("$.name").value(DEFAULT_NAME)) .andExpect(jsonPath("$.league").value(DEFAULT_LEAGUE)) .andExpect(jsonPath("$.division").value(DEFAULT_DIVISION)) .andExpect(jsonPath("$.titleFilter").value(DEFAULT_TITLE_FILTER)) .andExpect(jsonPath("$.announcement").value(DEFAULT_ANNOUNCEMENT)) .andExpect(jsonPath("$.lastAnnouncement").value(sameInstant(DEFAULT_LAST_ANNOUNCEMENT))) .andExpect(jsonPath("$.enabled").value(DEFAULT_ENABLED)) .andExpect(jsonPath("$.lastStreamId").value(DEFAULT_LAST_STREAM_ID.intValue())); }
@Test public void getNonExistingAuditsByDate() throws Exception { // Initialize the database auditEventRepository.save(auditEvent); // Generate dates for selecting audits by date, making sure the period will not contain the sample audit String fromDate = SAMPLE_TIMESTAMP.minusSeconds(2*SECONDS_PER_DAY).toString().substring(0,10); String toDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0,10); // Query audits but expect no results restAuditMockMvc.perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(header().string("X-Total-Count", "0")); }
@Test public void should_upload_a_gif_ani_and_retrieve_a_supported_image_thumbnail() throws Exception { final MockHttpServletResponse response = mvc.perform(fileUpload("/documents") .file(gifAniFile) .param("classification", Classifications.PRIVATE.toString()) .headers(headers)) .andReturn().getResponse(); final String url = getThumbnailUrlFromResponse(response); mvc.perform(get(url) .headers(headers)) .andExpect(content().contentType(MediaType.IMAGE_JPEG_VALUE)); }
@Test public void get() throws Exception { MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/account/get/1").accept(MediaType.APPLICATION_JSON)).andReturn(); int status = mvcResult.getResponse().getStatus(); String content = mvcResult.getResponse().getContentAsString(); System.out.println(status + "--" + content); }
/** * GET /userProfiles/:id -> get the "id" userProfile. */ @RequestMapping(value = "/userProfiles/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<UserProfile> getUserProfile(@PathVariable Long id) { log.debug("REST request to get UserProfile : {}", id); return Optional.ofNullable(userProfileRepository.findOne(id)) .map(userProfile -> new ResponseEntity<>( userProfile, HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); }
private void updateGraphVersionState(String url, String graphName, String version, State state, Integer segmentsCount) throws RestClientException { Map<String, Object> requestParams = new HashMap<String, Object>(); String graphVersionStateUpdateUrl = createSetGraphVersionStateUrl(url, graphName, version, state.toString(), segmentsCount); // TODO: Set Credentials HttpHeaders headers = getHeaders(graphVersionStateUpdateUrl); //, subscription.getUser(), subscription.getPassword()); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String,Object>>(requestParams, headers); restTemplate.put(graphVersionStateUpdateUrl, request); }
/** * POST /imageCompletionExercises -> Create a new imageCompletionExercise. */ @RequestMapping(value = "/imageCompletionExercises", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<ImageCompletionExercise> createImageCompletionExercise(@RequestBody ImageCompletionExercise imageCompletionExercise) throws URISyntaxException { log.debug("REST request to save ImageCompletionExercise : {}", imageCompletionExercise); if (imageCompletionExercise.getId() != null) { return ResponseEntity.badRequest().header("Failure", "A new imageCompletionExercise cannot already have an ID").body(null); } ImageCompletionExercise result = imageCompletionExerciseRepository.save(imageCompletionExercise); return ResponseEntity.created(new URI("/api/imageCompletionExercises/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert("imageCompletionExercise", result.getId().toString())) .body(result); }
@Test public void shouldRegisterNewAccount() throws Exception { final User user = new User(); user.setUsername("test"); user.setPassword("password"); String json = mapper.writeValueAsString(user); System.out.println(json); mockMvc.perform(post("/").principal(new UserPrincipal("test")).contentType(MediaType.APPLICATION_JSON).content(json)) .andExpect(status().isOk()); }
/** * POST /multipleChoiceAnswers -> Create a new multipleChoiceAnswer. */ @RequestMapping(value = "/multipleChoiceAnswers", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<MultipleChoiceAnswer> createMultipleChoiceAnswer(@Valid @RequestBody MultipleChoiceAnswer multipleChoiceAnswer) throws URISyntaxException { log.debug("REST request to save MultipleChoiceAnswer : {}", multipleChoiceAnswer); if (multipleChoiceAnswer.getId() != null) { return ResponseEntity.badRequest().header("Failure", "A new multipleChoiceAnswer cannot already have an ID").body(null); } MultipleChoiceAnswer result = multipleChoiceAnswerRepository.save(multipleChoiceAnswer); return ResponseEntity.created(new URI("/api/multipleChoiceAnswers/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert("multipleChoiceAnswer", result.getId().toString())) .body(result); }
/** * GET /hangManExerciseHints -> get all the hangManExerciseHints. */ @RequestMapping(value = "/hangManExerciseHints", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public List<HangManExerciseHint> getAllHangManExerciseHints() { log.debug("REST request to get all HangManExerciseHints"); return hangManExerciseHintRepository.findAll(); }
/** * HTTP GET ALL */ @RequestMapping(value = "/api/todolist", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<?> getAllTodoItems() { try { return new ResponseEntity<List<TodoItem>>(todoItemRepository.findAll(), HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<String>("Nothing found", HttpStatus.NOT_FOUND); } }
/** * ueditor编辑器 */ @RequestMapping("ueditor") public ResponseEntity<String> ueditor(HttpServletRequest request) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_HTML); String json = ueditorService.exec(request); return new ResponseEntity<String>(json, headers, HttpStatus.OK); }
@GetMapping("/{currpair}/orderbook") public Mono<String> getOrderbook(@PathVariable String currpair,HttpServletRequest request) { if(!WebUtils.checkOBRequest(request, WebUtils.LASTOBCALLBF)) { return Mono.just("{\n" + " \"bids\":[],\n" + " \"asks\":[]\n" + "}"); } WebClient wc = WebUtils.buildWebClient(URLBF); return wc.get().uri("/v1/book/"+currpair+"/").accept(MediaType.APPLICATION_JSON).exchange().flatMap(res -> res.bodyToMono(String.class)); }
@Test public void should_upload_a_jpg_and_retrieve_a_supported_image_thumbnail() throws Exception { final MockHttpServletResponse response = mvc.perform(fileUpload("/documents") .file(jpgFile) .param("classification", Classifications.PRIVATE.toString()) .headers(headers)) .andReturn().getResponse(); final String url = getThumbnailUrlFromResponse(response); mvc.perform(get(url) .headers(headers)) .andExpect(content().contentType(MediaType.IMAGE_JPEG_VALUE)); }
/** * 参考链接:Spring MVC测试框架详解——服务端测试 * <URL>http://jinnianshilongnian.iteye.com/blog/2004660</URL> */ @Test public void index() throws Exception { MvcResult result = this.mockMvc.perform(MockMvcRequestBuilders .get("/") .accept(MediaType.TEXT_HTML)) .andDo(MockMvcResultHandlers.print()) .andReturn(); }
public Client build() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); //prepare ROPC request MultiValueMap<String, String> params = new LinkedMultiValueMap(); params.add(CLIENT_ID_PARAM, clientId); params.add(CLIENT_SECRET_PARAM, clientSecret); params.add(GRANT_TYPE_PARAM, "password"); params.add(USERNAME_PARAM, username); params.add(PASSWORD_PARAM, password); System.out.println("PARAMS: " + params.toString()); RestTemplate restTemplate = new RestTemplate(); HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity(params, headers); String tokenUrl = String.format("%s/oauth2/v1/token", baseUrl); System.out.println("tokenURL: " + tokenUrl); try { //obtain access token and return client instance Client client = restTemplate .exchange(tokenUrl, HttpMethod.POST, entity, Client.class) .getBody(); client.init(baseUrl); return client; } catch(Exception ex){ ex.printStackTrace(); return null; } }
/** * Sets the default {@code Content-Type} to be used for writing. * @throws IllegalArgumentException if the given content type is not supported by the Java Image I/O API */ public void setDefaultContentType(MediaType defaultContentType) { Assert.notNull(defaultContentType, "'contentType' must not be null"); Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByMIMEType(defaultContentType.toString()); if (!imageWriters.hasNext()) { throw new IllegalArgumentException( "Content-Type [" + defaultContentType + "] is not supported by the Java Image I/O API"); } this.defaultContentType = defaultContentType; }
/** * GET /exerciseTips/:id -> get the "id" exerciseTip. */ @RequestMapping(value = "/exerciseTips/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<ExerciseTip> getExerciseTip(@PathVariable Long id) { log.debug("REST request to get ExerciseTip : {}", id); return Optional.ofNullable(exerciseTipRepository.findOne(id)) .map(exerciseTip -> new ResponseEntity<>( exerciseTip, HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); }
@Test @Transactional public void getSubCategory() throws Exception { // Initialize the database subCategoryRepository.saveAndFlush(subCategory); // Get the subCategory restSubCategoryMockMvc.perform(get("/api/sub-categories/{id}", subCategory.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(subCategory.getId().intValue())) .andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString())); }
@Test @Transactional public void getMultipleChoiceAnswer() throws Exception { // Initialize the database multipleChoiceAnswerRepository.saveAndFlush(multipleChoiceAnswer); // Get the multipleChoiceAnswer restMultipleChoiceAnswerMockMvc.perform(get("/api/multipleChoiceAnswers/{id}", multipleChoiceAnswer.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id").value(multipleChoiceAnswer.getId().intValue())) .andExpect(jsonPath("$.answer").value(DEFAULT_ANSWER.toString())) .andExpect(jsonPath("$.isRight").value(DEFAULT_IS_RIGHT.booleanValue())) .andExpect(jsonPath("$.source").value(DEFAULT_SOURCE.toString())); }
@Test public void testNonAuthenticatedUser() throws Exception { restUserMockMvc.perform(get("/api/authenticate") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string("")); }
/** * SEARCH /_search/projects?query=:query : search for the project corresponding * to the query. * * @param query the query of the project search * @return the result of the search */ @RequestMapping(value = "/projects", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<List<ProjectDTO>> searchprojects(@RequestParam(required = false) String query) throws URISyntaxException { log.debug("REST request to search projects for query {}", query); Map<String, Long> projects = customSearchRepository.aggregateByRawField("project", query); List<ProjectDTO> listProjectDTO = new LinkedList<>(); projects.forEach((key, value) -> listProjectDTO.add(new ProjectDTO(key, value))); return new ResponseEntity<>(listProjectDTO, HttpStatus.OK); }
@RequestMapping(value="/users", method=RequestMethod.POST, produces={ MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<Object> createUser(@Valid @RequestBody User user) { User maybeUser = userRepository.findByEmail(user.getEmail()); if (maybeUser != null) return ResponseEntity .status(HttpStatus.BAD_REQUEST) .contentType(MediaType.APPLICATION_JSON) .body("{ \"error\" : \"User already exist\" }"); return ResponseEntity.ok(userRepository.save(user)); }
@Test public void getAllAudits() throws Exception { // Initialize the database auditEventRepository.save(auditEvent); // Get all the audits restAuditMockMvc.perform(get("/management/audits")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); }
@Test @Transactional public void getContent() throws Exception { // Initialize the database contentRepository.saveAndFlush(content); // Get the content restContentMockMvc.perform(get("/api/contents/{id}", content.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(content.getId().intValue())) .andExpect(jsonPath("$.value").value(Base64Utils.encodeToString(DEFAULT_VALUE))); }