Example #1
0
 @RequestMapping(path = "/system/monitor")
 public ResponseEntity<RestResponse> monitor(
     Authentication authentication, HttpServletRequest request) throws Throwable {
   Map<String, Object> monitor = new HashMap<>();
   monitor.put(
       "time", DateFormatUtils.ISO_8601_EXTENDED_DATETIME_TIME_ZONE_FORMAT.format(new Date()));
   RestResponse response = new RestResponse();
   response.setResultCode(HttpStatus.OK.value());
   response.setResultMessage(HttpStatus.OK.getReasonPhrase());
   response.setData(monitor);
   return ResponseEntity.ok(response);
 }
  @Test
  public void testUserSelfAccess_Get_and_Post() throws Exception {
    ScimUser user = getScimUser();
    user.setPassword("secret");
    user = createUser(user, scimReadWriteToken, IdentityZone.getUaa().getSubdomain());

    String selfToken =
        testClient.getUserOAuthAccessToken("cf", "", user.getUserName(), "secret", "");

    user.setName(new ScimUser.Name("Given1", "Family1"));
    user = updateUser(selfToken, HttpStatus.OK.value(), user);

    user = getAndReturnUser(HttpStatus.OK.value(), user, selfToken);
  }
  protected HttpResponse setupHttpClient(InputStream benefitStatementsStream, String contentType)
      throws IOException, ClientProtocolException {
    final HttpResponse httpResponse = mock(HttpResponse.class);
    when(httpClient.execute(any(HttpUriRequest.class), any(HttpContext.class)))
        .thenReturn(httpResponse);
    when(httpResponse.getStatusLine())
        .thenReturn(
            new BasicStatusLine(
                HttpVersion.HTTP_1_1, HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase()));
    when(httpResponse.getAllHeaders())
        .thenReturn(new Header[] {new BasicHeader("Content-Type", contentType)});
    when(httpResponse.getEntity()).thenReturn(new InputStreamEntity(benefitStatementsStream, -1));

    return httpResponse;
  }
  @Test
  public void shouldGetAllEnrollments() throws Exception {
    CampaignEnrollment enrollment1 = new CampaignEnrollment("47sf6a", "PREGNANCY");
    enrollment1.setDeliverTime(new Time(20, 1));
    enrollment1.setReferenceDate(new LocalDate(2012, 1, 2));
    enrollment1.setId(9001L);

    CampaignEnrollment enrollment2 = new CampaignEnrollment("d6gt40", "PREGNANCY");
    enrollment2.setDeliverTime(new Time(10, 0));
    enrollment2.setReferenceDate(new LocalDate(2012, 2, 15));
    enrollment2.setId(9002L);

    CampaignEnrollment enrollment3 = new CampaignEnrollment("o34j6f", "CHILD_DEVELOPMENT");
    enrollment3.setDeliverTime(new Time(10, 0));
    enrollment3.setReferenceDate(new LocalDate(2012, 3, 13));
    enrollment3.setId(9003L);

    when(enrollmentRestController.getAllEnrollments(
            CampaignEnrollmentStatus.ACTIVE.name(), null, null))
        .thenReturn(new EnrollmentList(asList(enrollment1, enrollment2, enrollment3)));

    final String expectedResponse = loadJson("rest/enrollments/enrollmentList.json");

    controller
        .perform(get("/enrollments/users"))
        .andExpect(status().is(HttpStatus.OK.value()))
        .andExpect(content().type(APPLICATION_JSON_UTF8))
        .andExpect(content().string(jsonMatcher(expectedResponse)));

    verify(enrollmentRestController)
        .getAllEnrollments(CampaignEnrollmentStatus.ACTIVE.name(), null, null);
  }
  @Test
  public void canGetStatusOnlyByGet() {
    when()
        .post(CurrentRaceController.STATUS_URL)
        .then()
        .statusCode(HttpStatus.METHOD_NOT_ALLOWED.value());
    when()
        .delete(CurrentRaceController.STATUS_URL)
        .then()
        .statusCode(HttpStatus.METHOD_NOT_ALLOWED.value());
    when()
        .put(CurrentRaceController.STATUS_URL)
        .then()
        .statusCode(HttpStatus.METHOD_NOT_ALLOWED.value());
    when()
        .patch(CurrentRaceController.STATUS_URL)
        .then()
        .statusCode(HttpStatus.METHOD_NOT_ALLOWED.value());

    CurrentRaceStatus currentRaceStatus = new CurrentRaceStatus();
    currentRaceStatus.setState(RaceStatus.State.ACTIVE);
    repository.save(currentRaceStatus);

    when()
        .get(CurrentRaceController.STATUS_URL)
        .then()
        .statusCode(HttpStatus.OK.value())
        .body("state", is(RaceStatus.State.ACTIVE.name()));
  }
  @Test
  public void shouldGetContents() throws Exception {
    StringContent stringContent = new StringContent(STRING_LANGUAGE, STRING_NAME, STRING_VALUE);
    StreamContent streamContent =
        new StreamContent(STREAM_LANGUAGE, STREAM_NAME, null, STREAM_CHECKSUM, STREAM_CONTENT_TYPE);
    GridSettings settings = createGridSettings("", true, true, "", 5, 1, "", "asc");
    List<ResourceDto> resourceDtos =
        asList(new ResourceDto(streamContent), new ResourceDto(stringContent));

    String expectedResponse = createResponse(new Resources(settings, resourceDtos));

    when(cmsLiteService.getAllContents()).thenReturn(asList(streamContent, stringContent));

    controller
        .perform(
            get(
                "/resource?name={name}&string={string}&stream={stream}&languages={languages}&rows={rows}&page={page}&sortColumn={sortColumn}&sortDirection={sortDirection}",
                "",
                true,
                true,
                "",
                5,
                1,
                "",
                "asc"))
        .andExpect(status().is(HttpStatus.OK.value()))
        .andExpect(content().type(APPLICATION_JSON_UTF8))
        .andExpect(content().string(jsonMatcher(expectedResponse)));

    verify(cmsLiteService).getAllContents();
  }
  protected ScimUser updateUser(String token, int status, ScimUser user) throws Exception {
    MockHttpServletRequestBuilder put =
        put("/Users/" + user.getId())
            .header("Authorization", "Bearer " + token)
            .header("If-Match", "\"" + user.getVersion() + "\"")
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            .content(JsonUtils.writeValueAsBytes(user));
    if (status == HttpStatus.OK.value()) {
      String json =
          getMockMvc()
              .perform(put)
              .andExpect(status().isOk())
              .andExpect(header().string("ETag", "\"1\""))
              .andExpect(jsonPath("$.userName").value(user.getUserName()))
              .andExpect(jsonPath("$.emails[0].value").value(user.getPrimaryEmail()))
              .andExpect(jsonPath("$.name.givenName").value(user.getGivenName()))
              .andExpect(jsonPath("$.name.familyName").value(user.getFamilyName()))
              .andReturn()
              .getResponse()
              .getContentAsString();

      return JsonUtils.readValue(json, ScimUser.class);
    } else {
      getMockMvc().perform(put).andExpect(status().is(status));
      return null;
    }
  }
  @Override
  protected void renderMergedOutputModel(
      Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    response.setStatus(HttpStatus.OK.value());
    // output stream
    OutputStream stream =
        (this.updateContentLength ? createTemporaryOutputStream() : response.getOutputStream());

    // model
    Map<String, Object> value = null;
    PagerInfo pagerInfo =
        (PagerInfo) request.getAttribute(PagerInfo.DEFAULT_PAGER_INFO_ATTRIBUTE_KEY);

    Throwable exception = (Throwable) model.get(JsonConstant.EXCEPTION);
    if (exception != null) {
      logger.debug(">>>>>>>>>>>>>>> exception:{}", exception);
      value = getModelForFail(exception, model);
    } else {
      value = getModelForSuccess(model, pagerInfo);
    }

    // write
    writeContent(stream, value);
    if (this.updateContentLength) {
      writeToResponse(response, (ByteArrayOutputStream) stream);
    }
  }
 @RequestMapping(value = "log", method = RequestMethod.POST)
 public void log(@RequestBody JLogs logs, HttpServletResponse response) {
   for (String s : logs.getLogs()) {
     LOG.info(s);
   }
   response.setStatus(HttpStatus.OK.value());
 }
Example #10
0
  @RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
  public @ResponseBody MensagemRetornoAPI update(String pedidoJSON)
      throws APIException, JsonParseException, JsonMappingException, IOException {

    Pedido pedido = convertStringJsonToObject(pedidoJSON);
    pedidoService.update(pedido);
    return new MensagemRetornoAPI(HttpStatus.OK.toString(), "Pedido atualizado com sucesso");
  }
  @RequestMapping(value = "/passwordResetConfirm", method = RequestMethod.POST)
  public RestSuccess confirmPasswordReset(
      @RequestParam("token") String token, @RequestParam("new_password") String newPassword) {

    return new RestSuccess(
        HttpStatus.OK.value(),
        customerService.confirmPasswordReset(token, newPassword),
        "You have changed your password successfully");
  }
  @Test
  public void shouldDeleteEnrollment() throws Exception {
    controller
        .perform(
            delete("/enrollments/{campaignName}/users/{externalId}", CAMPAIGN_NAME, EXTERNAL_ID))
        .andExpect(status().is(HttpStatus.OK.value()));

    verify(enrollmentRestController).removeEnrollment(CAMPAIGN_NAME, EXTERNAL_ID);
  }
  @RequestMapping(
      value = "/addSport", /*produces = MediaType.APPLICATION_JSON_VALUE,
            consumes = MediaType.APPLICATION_JSON_VALUE,*/
      method = RequestMethod.POST)
  public @ResponseBody String saveSport(
      @RequestBody Sport sport, ModelMap model, BindingResult result) {

    return HttpStatus.OK.name();
    /*return "admin/sports";*/
  }
  /**
   * Testing controller geocode.xml with valid data in case when requested object is not already
   * precashed in local DB.
   *
   * @throws ServletException
   * @throws IOException
   * @throws UnsupportedEncodingException
   * @throws JsonMappingException
   * @throws JsonGenerationException
   * @throws JAXBException
   * @throws Exception
   */
  @Test
  public void testGeoCodeXmlWithValidDataNotCatchedCode()
      throws JsonGenerationException, JsonMappingException, UnsupportedEncodingException,
          IOException, ServletException, JAXBException {

    // data preparing
    final String zipCode = "postcode1";
    final Integer houseNumber = 1;

    mockRequest.setMethod(RequestMethod.GET.name());
    mockRequest.setRequestURI("/api/address.xml");
    mockRequest.setParameter("zipcode", zipCode);
    mockRequest.setParameter("number", houseNumber.toString());

    // calling method
    final String responseContent = processRequest(null, null, mockRequest, mockResponse);

    // asserting
    Assert.assertEquals(HttpStatus.OK.value(), mockResponse.getStatus());

    final AddressDTO locationDto = (AddressDTO) um.unmarshal(new StringReader(responseContent));
    Assert.assertNotNull(locationDto);

    final Address createdEntity =
        locationDao.findByCountryPostalCodeAndNumber(
            LocationService.NL_COUNTRY_CODE, zipCode, houseNumber);

    assertObject(
        createdEntity,
        notNull(Address.ID),
        notNull(Address.CREATION_DATE),
        changed(Address.COUNTRY_CODE, LocationService.NL_COUNTRY_CODE),
        changed(Address.NUMBER, houseNumber),
        notNull(Address.NUMBER_POSTFIX),
        changed(Address.POSTAL_CODE, zipCode),
        notNull(Address.LATITUDE),
        notNull(Address.LONGITUDE),
        notNull(Address.VALID_FROM),
        notNull(Address.VALID_TO),
        notNull(Address.CITY),
        notNull(Address.STREET));

    assertObject(
        locationDto,
        changed(AddressDTO.COUNTRY_CODE, createdEntity.getCountryCode()),
        changed(AddressDTO.NUMBER, createdEntity.getNumber()),
        changed(AddressDTO.NUMBER_POSTFIX, createdEntity.getNumberPostfix()),
        changed(AddressDTO.POSTAL_CODE, createdEntity.getPostalCode()),
        changed(AddressDTO.LATITUDE, createdEntity.getLatitude()),
        changed(AddressDTO.LONGITUDE, createdEntity.getLongitude()),
        changed(AddressDTO.VALID_FROM, createdEntity.getValidFrom()),
        changed(AddressDTO.VALID_TO, createdEntity.getValidTo()),
        changed(AddressDTO.CITY, createdEntity.getCity()),
        changed(AddressDTO.STREET, createdEntity.getStreet()));
  }
Example #15
0
  @RequestMapping(
      value = "/create",
      method = RequestMethod.POST,
      headers = {"Content-type=application/json"})
  public @ResponseBody MensagemRetornoAPI create(@RequestBody String pedidoJSON)
      throws APIException, JsonParseException, JsonMappingException, IOException {

    Pedido pedido = convertStringJsonToObject(pedidoJSON);
    pedidoService.salvarPedido(pedido);
    return new MensagemRetornoAPI(HttpStatus.OK.toString(), "Pedido efetuado com sucesso");
  }
  @Test
  public void shouldDeleteRecord() throws Exception {

    when(mockService.get(argThat(isString(TEST_ID)))).thenReturn(Record.instanceOf(10));

    Response response = recordResource.deleteRecord(TEST_ID);

    verify(mockService, times(1)).delete(argThat(isString(TEST_ID)));

    assertThat(response.getStatus(), is(HttpStatus.OK.value()));
  }
 @Test
 public void testList() {
   testCreate();
   ProjectServiceResponse response =
       restTemplate.getForObject(
           baseURL + "/list", ProjectServiceResponse.class, new Object[] {null});
   // ProjectServiceResponse response = client.create(project);
   assertNotNull(response);
   assertEquals(HttpStatus.OK.toString(), response.getHttpStatusCode());
   assertTrue(response.getProjects().size() > 0);
 }
  @Test
  public void shouldRemoveStringContent() throws Exception {
    StringContent stringContent = new StringContent(STRING_LANGUAGE, STRING_NAME, STRING_VALUE);
    when(cmsLiteService.getStringContent(STRING_LANGUAGE, STRING_NAME)).thenReturn(stringContent);

    controller
        .perform(
            delete("/resource/{type}/{language}/{name}", STRING_TYPE, STRING_LANGUAGE, STRING_NAME))
        .andExpect(status().is(HttpStatus.OK.value()));

    verify(cmsLiteService).removeStringContent(STRING_LANGUAGE, STRING_NAME);
  }
 @RequestMapping(
     value = {"/company/{companyId}/graph/{graphId}"},
     method = {RequestMethod.DELETE})
 @ResponseBody
 public Graph deleteGraph(
     @PathVariable("companyId") int companyId,
     @PathVariable("graphId") int graphId,
     HttpServletResponse httpResponse_p)
     throws Exception {
   graphService.deleteGraph(companyId, graphId);
   httpResponse_p.setStatus(HttpStatus.OK.value());
   return null;
 }
  @RequestMapping(value = "passes/{passTypeId}/{serialNo}", method = RequestMethod.GET)
  public void getPass(
      WebRequest webRequest,
      HttpServletResponse response,
      @PathVariable String passTypeId,
      @PathVariable String serialNo,
      @RequestHeader(value = "Authorization", defaultValue = "not_provided") String authorization)
      throws IOException {

    final String authToken = getAuthToken(authorization);
    //        if (null == authToken) {
    //            response.sendError(HttpStatus.UNAUTHORIZED.value());
    //            return;
    //        }

    try {
      //            final AbstractPassEntity pass = passbookService.getPass(passTypeId, serialNo,
      // authToken);
      //
      //            final long lastModified = pass.getUpdatedDate().getTime();
      //            if (webRequest.checkNotModified(lastModified)) {
      //                // shortcut exit - no further processing necessary
      //                return;
      //            }

      // write the .pkpass to the response
      ServletOutputStream out = response.getOutputStream();
      response.setContentType(CONTENT_TYPE_PASS);
      response.setHeader(CONTENT_DISPOSITION__NAME, CONTENT_DISPOSITION_VALUE);
      int length = passbookService.writePass(out, passTypeId, serialNo);
      out.flush();
      out.close();
      response.setStatus(HttpStatus.OK.value());
      LOG.info("Wrote pass of {} bytes", length);
      return;

      //        } catch (NoSuchPassException ex) {
      //            response.sendError(HttpStatus.NOT_FOUND.value());
      //            return;
    } catch (NoSuchPassTypeException ex) {
      response.sendError(HttpStatus.UNPROCESSABLE_ENTITY.value());
      return;
      //        } catch (InvalidAuthTokenException ex) {
      //            response.sendError(HttpStatus.UNAUTHORIZED.value());
      //            return;
    } catch (Exception ex) {
      LOG.error("Exception thrown by Service.writePass", ex);
      response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
      return;
    }
  }
  @Test
  public void shouldReturnLanguagesStartedWithGivenTerm() throws Exception {
    String expectedResponse = createResponse(asList(STREAM_LANGUAGE));

    controller
        .perform(
            get(
                "/resource/available/{field}?term={term}",
                "language",
                STREAM_LANGUAGE.toLowerCase().substring(0, 2)))
        .andExpect(status().is(HttpStatus.OK.value()))
        .andExpect(content().type(APPLICATION_JSON_UTF8))
        .andExpect(content().string(jsonMatcher(expectedResponse)));
  }
  protected String buildSuccessResponse(String message) {
    String response = null;

    RedirectAuthResponse redirectAuthResponse = new RedirectAuthResponse();
    ResponseHeader responseHeader = new ResponseHeader();
    responseHeader.setCode(HttpStatus.OK.toString());
    responseHeader.setStatus(HttpServletResponse.SC_OK);
    responseHeader.setMessage(message);
    redirectAuthResponse.setHeader(responseHeader);

    Gson gson = new GsonFactory().createGson();
    response = gson.toJson(redirectAuthResponse);

    return response;
  }
  @Test
  public void shouldGetRecord() throws Exception {

    Record record = Record.instanceOf(10);

    when(mockService.get(argThat(isString(TEST_ID)))).thenReturn(record);

    Response response = recordResource.getRecord(TEST_ID);

    assertThat(response.getStatus(), is(HttpStatus.OK.value()));

    RecordPayload recordPayload = (RecordPayload) response.getEntity();

    assertThat(recordPayload.getNumber(), is(10));
  }
  @Test
  public void shouldGetAll() throws Exception {

    List<Record> records = new ArrayList<Record>();

    when(mockService.getAll()).thenReturn(records);

    Response response = recordResource.getAll();

    assertThat(response.getStatus(), is(HttpStatus.OK.value()));

    List<RecordPayload> list = (List<RecordPayload>) response.getEntity();

    assertThat(list.size(), is(0));
  }
  @Test
  public void shouldReturnStringContent() throws Exception {
    StringContent stringContent = new StringContent(STRING_LANGUAGE, STRING_NAME, STRING_VALUE);
    String expectedResponse = createResponse(stringContent);

    when(cmsLiteService.getStringContent(STRING_LANGUAGE, STRING_NAME)).thenReturn(stringContent);

    controller
        .perform(
            get("/resource/{type}/{language}/{name}", STRING_TYPE, STRING_LANGUAGE, STRING_NAME))
        .andExpect(status().is(HttpStatus.OK.value()))
        .andExpect(content().type(APPLICATION_JSON_UTF8))
        .andExpect(content().string(jsonMatcher(expectedResponse)));

    verify(cmsLiteService).getStringContent(STRING_LANGUAGE, STRING_NAME);
  }
  @Test
  public void shouldCreateEnrollment() throws Exception {
    controller
        .perform(
            post("/enrollments/{campaignName}/users", CAMPAIGN_NAME)
                .contentType(MediaType.APPLICATION_JSON)
                .param("externalId", EXTERNAL_ID)
                .param("enrollmentId", "9001"))
        .andExpect(status().is(HttpStatus.OK.value()));

    ArgumentCaptor<EnrollmentRequest> captor = ArgumentCaptor.forClass(EnrollmentRequest.class);
    verify(enrollmentRestController)
        .enrollOrUpdateUser(eq(CAMPAIGN_NAME), eq(EXTERNAL_ID), captor.capture());

    assertEquals(DateUtil.today(), captor.getValue().getReferenceDate());
    assertEquals(new Long(9001L), captor.getValue().getEnrollmentId());
  }
  @Test
  public void shouldReturnNamesStartedWithGivenTerm() throws Exception {
    StringContent stringContent = new StringContent(STRING_LANGUAGE, STRING_NAME, STRING_VALUE);
    StreamContent streamContent =
        new StreamContent(STREAM_LANGUAGE, STREAM_NAME, null, STREAM_CHECKSUM, STREAM_CONTENT_TYPE);
    String expectedResponse = createResponse(asList(STRING_NAME));

    when(cmsLiteService.getAllContents()).thenReturn(asList(streamContent, stringContent));

    controller
        .perform(get("/resource/available/{field}?term={term}", "name", "valid-stri"))
        .andExpect(status().is(HttpStatus.OK.value()))
        .andExpect(content().type(APPLICATION_JSON_UTF8))
        .andExpect(content().string(jsonMatcher(expectedResponse)));

    verify(cmsLiteService).getAllContents();
  }
 private Response postToReportUrl(ReportParameters params, String reportType, User user) {
   final String authToken = devHelper.login(user.username).token;
   final Response whenPostingToReportUrl =
       given()
           .contentType(ContentType.JSON)
           .accept(MEDIA_TYPE_EXCEL)
           .header(authorization(authToken))
           .body(params)
           .when()
           .post(UrlSchema.REPORT, reportType);
   whenPostingToReportUrl
       .then()
       .assertThat()
       .statusCode(HttpStatus.OK.value())
       .assertThat()
       .contentType(MEDIA_TYPE_EXCEL);
   return whenPostingToReportUrl;
 }
  @Test
  public void shouldEditStringContent() throws Exception {
    StringContent stringContent = new StringContent(STRING_LANGUAGE, STRING_NAME, STRING_VALUE);

    when(cmsLiteService.getStringContent(STRING_LANGUAGE, STRING_NAME)).thenReturn(stringContent);

    controller
        .perform(
            post("/resource/string/{language}/{name}", STRING_LANGUAGE, STRING_NAME)
                .param("value", "new value"))
        .andExpect(status().is(HttpStatus.OK.value()));

    ArgumentCaptor<StringContent> captor = ArgumentCaptor.forClass(StringContent.class);

    verify(cmsLiteService).addContent(captor.capture());
    stringContent.setValue("new value");

    assertEquals(stringContent, captor.getValue());
  }
  /*
   * (non-Javadoc)
   * @see com.xmdevelopments.services.AuthService#submit()
   */
  @Override
  public Response submit() {
    String prefix = " submit()";
    logger.info(prefix + "->called");

    Response response = new Response();
    ResponseError responseError = new ResponseError();
    try {
      // Assumed that passed the WSSE validation
      // TODO authentication procedure
      response.setResponseCode(HttpStatus.OK.value());
      response.setData("Authentication successful");
    } catch (Exception ex) {
      response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
      responseError.setMessage(ex.getMessage());
      responseError.setErrorCode(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()));
      response.setData(responseError);
      logger.error(prefix, ex);
    }
    return response;
  }