@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);
  }
Exemplo n.º 2
0
  @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();
  }
 @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());
 }
  @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()));
  }
  @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);
    }
  }
  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;
    }
  }
  @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 = "/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");
  }
  /**
   * 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()));
  }
  @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()));
  }
Exemplo n.º 12
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);
 }
Exemplo n.º 13
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);
  }
Exemplo n.º 14
0
 @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;
 }
Exemplo n.º 15
0
  @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;
    }
  }
Exemplo n.º 16
0
  @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 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 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));
  }
Exemplo n.º 20
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);
  }
Exemplo n.º 21
0
  @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();
  }
  @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());
  }
Exemplo n.º 23
0
 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;
 }
Exemplo n.º 24
0
  @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());
  }
Exemplo n.º 25
0
  /*
   * (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;
  }
  @Test
  public void updatesDevice() {
    // @formatter:off
    given()
        .pathParam("apiVersion", apiVersion)
        .pathParam("uuid", uuid)
        .body(new DevicePutJsonImpl())
        .contentType(ContentType.JSON)
        .when()
        .put(URL)
        .then()
        .statusCode(HttpStatus.OK.value());
    // @formatter:on

    List<DeviceEntity> devices = deviceJpaRepository.findAllByOrderByCreationDateDesc();
    assertThat(devices.size()).isEqualTo(1);
    DeviceEntity deviceEntity = devices.get(0);
    assertThat(deviceEntity.getName()).isEqualTo(UPDATED_NAME);
    assertThat(deviceEntity.getDescription().get()).isEqualTo(UPDATED_DESCRIPTION);
    assertThat(deviceEntity.getLocation().get()).isEqualTo(UPDATED_LOCATION);
    assertThat(deviceEntity.getId()).isEqualTo(uuid);
    assertThat(deviceEntity.getVersion()).isEqualTo(version + 1);
  }
Exemplo n.º 27
0
 @Test
 public void testUpdateUser() throws Exception {
   updateUser(scimReadWriteToken, HttpStatus.OK.value());
 }
Exemplo n.º 28
0
 @Test
 public void testUpdateUserWithUaaAdminToken() throws Exception {
   updateUser(uaaAdminToken, HttpStatus.OK.value());
 }
Exemplo n.º 29
0
  @RequestMapping(path = "/system/sync")
  public ResponseEntity<RestResponse> sync(
      Authentication authentication, HttpServletRequest request) throws Throwable {
    String json = org.apache.commons.io.IOUtils.toString(request.getInputStream(), "UTF-8");
    Sync sync = this.gson.fromJson(json, Sync.class);
    if (sync == null) {
      sync = new Sync();
    }
    List<String> pageIds = new ArrayList<>();
    List<String> restIds = new ArrayList<>();
    try (Connection connection = sql2o.open()) {
      if (sync.getPages() != null && !sync.getPages().isEmpty()) {
        for (Page clientPage : sync.getPages()) {
          Query query =
              connection.createQuery(
                  "select groovy.java_class as javaClass, page.path as mountPath, groovy.groovy_id as groovyId, page.page_id as pageId, html as serverHtml, html_crc32 as serverHtmlCrc32, groovy.script as serverGroovy, groovy.script_crc32 as serverGroovyCrc32 from page inner join groovy on page.groovy_id = groovy.groovy_id where page.page_id = :pageId");
          query.addParameter("pageId", clientPage.getPageId());
          Page serverPage = query.executeAndFetchFirst(Page.class);
          boolean groovyConflicted =
              !clientPage.getServerGroovyCrc32().equals(serverPage.getServerGroovyCrc32());
          boolean htmlConflicted =
              !clientPage.getServerHtmlCrc32().equals(serverPage.getServerHtmlCrc32());
          pageIds.add(clientPage.getPageId());
          clientPage.setGroovyConflicted(groovyConflicted);
          clientPage.setHtmlConflicted(htmlConflicted);
          String path = StringUtils.replaceChars(serverPage.getJavaClass(), '.', '/');
          clientPage.setHtmlPath(path + ".html");
          clientPage.setGroovyPath(path + ".groovy");
          if (!groovyConflicted
              && !htmlConflicted
              && Strings.isNullOrEmpty(clientPage.getClientGroovyCrc32())
              && Strings.isNullOrEmpty(clientPage.getClientHtmlCrc32())) {
            // delete command
            clientPage.setServerGroovyCrc32(null);
            clientPage.setServerGroovy(null);
            clientPage.setServerHtmlCrc32(null);
            clientPage.setServerHtml(null);
            classLoader.removeSourceCache(serverPage.getGroovyId());
            classLoader.removeClassCache(serverPage.getJavaClass());
            connection
                .createQuery("delete from page where page_id = :page_id")
                .addParameter("page_id", serverPage.getPageId())
                .executeUpdate();
            connection
                .createQuery("delete from groovy where groovy_id = :groovy_id")
                .addParameter("groovy_id", serverPage.getGroovyId())
                .executeUpdate();
            Application.get().unmount(serverPage.getMountPath());
            Application.get().getMarkupSettings().getMarkupFactory().getMarkupCache().clear();
          } else {
            if (!groovyConflicted) {
              // update command
              classLoader.removeSourceCache(serverPage.getGroovyId());
              classLoader.removeClassCache(serverPage.getJavaClass());
              GroovyCodeSource source =
                  new GroovyCodeSource(
                      Strings.isNullOrEmpty(clientPage.getClientGroovy())
                          ? serverPage.getServerGroovy()
                          : clientPage.getClientGroovy(),
                      serverPage.getGroovyId(),
                      "/groovy/script");
              source.setCachable(true);
              Class<?> pageClass = classLoader.parseClass(source, true);
              Application.get()
                  .mountPage(
                      serverPage.getMountPath(),
                      (Class<? extends org.apache.wicket.Page>) pageClass);
              connection
                  .createQuery(
                      "update groovy set script = :script, script_crc32 = :script_crc32, java_class = :java_class where groovy_id = :groovy_id")
                  .addParameter(
                      "script",
                      Strings.isNullOrEmpty(clientPage.getClientGroovy())
                          ? serverPage.getServerGroovy()
                          : clientPage.getClientGroovy())
                  .addParameter("script_crc32", clientPage.getClientGroovyCrc32())
                  .addParameter("java_class", pageClass.getName())
                  .addParameter("groovy_id", serverPage.getGroovyId())
                  .executeUpdate();
              clientPage.setServerGroovyCrc32(clientPage.getClientGroovyCrc32());
              clientPage.setServerGroovy(
                  Strings.isNullOrEmpty(clientPage.getClientGroovy())
                      ? serverPage.getServerGroovy()
                      : clientPage.getClientGroovy());
            } else {
              clientPage.setServerGroovyCrc32(serverPage.getServerGroovyCrc32());
              clientPage.setServerGroovy(serverPage.getServerGroovy());
              if (Strings.isNullOrEmpty(clientPage.getClientGroovy())
                  && Strings.isNullOrEmpty(clientPage.getClientGroovyCrc32())) {
                clientPage.setGroovyConflicted(false);
              }
            }

            if (!htmlConflicted) {
              // update command
              connection
                  .createQuery(
                      "update page set html = :html, html_crc32 = :html_crc32 where page_id = :page_id")
                  .addParameter(
                      "html",
                      Strings.isNullOrEmpty(clientPage.getClientHtml())
                          ? serverPage.getServerHtml()
                          : clientPage.getClientHtml())
                  .addParameter("html_crc32", clientPage.getClientHtmlCrc32())
                  .addParameter("page_id", serverPage.getPageId())
                  .executeUpdate();
              Application.get().getMarkupSettings().getMarkupFactory().getMarkupCache().clear();
              clientPage.setServerHtmlCrc32(clientPage.getClientHtmlCrc32());
              clientPage.setServerHtml(
                  Strings.isNullOrEmpty(clientPage.getClientHtml())
                      ? serverPage.getServerHtml()
                      : clientPage.getClientHtml());
            } else {
              clientPage.setServerHtmlCrc32(serverPage.getServerHtmlCrc32());
              clientPage.setServerHtml(serverPage.getServerHtml());
            }
          }
        }
      }
      if (sync.getRests() != null && !sync.getRests().isEmpty()) {
        for (Rest clientRest : sync.getRests()) {
          restIds.add(clientRest.getRestId());
          Query query =
              connection.createQuery(
                  "select groovy.java_class as javaClass, groovy.groovy_id as groovyId, rest.rest_id as restId, groovy.script as serverGroovy, groovy.script_crc32 as serverGroovyCrc32 from rest inner join groovy on rest.groovy_id = groovy.groovy_id where rest.rest_id = :restId");
          query.addParameter("restId", clientRest.getRestId());
          Rest serverRest = query.executeAndFetchFirst(Rest.class);
          boolean groovyConflicted =
              !clientRest.getServerGroovyCrc32().equals(serverRest.getServerGroovyCrc32());
          clientRest.setGroovyConflicted(groovyConflicted);
          String path = StringUtils.replaceChars(serverRest.getJavaClass(), '.', '/');
          clientRest.setGroovyPath(path + ".groovy");
          if (!groovyConflicted && Strings.isNullOrEmpty(clientRest.getClientGroovyCrc32())) {
            // delete command
            clientRest.setServerGroovy(null);
            clientRest.setServerGroovyCrc32(null);
            classLoader.removeSourceCache(serverRest.getGroovyId());
            classLoader.removeClassCache(serverRest.getJavaClass());
            connection
                .createQuery("delete from rest where rest_id = :rest_id")
                .addParameter("rest_id", serverRest.getRestId())
                .executeUpdate();
            connection
                .createQuery("delete from groovy where groovy_id = :groovy_id")
                .addParameter("groovy_id", serverRest.getGroovyId())
                .executeUpdate();
          } else {
            if (!groovyConflicted) {
              // update command
              classLoader.removeSourceCache(serverRest.getGroovyId());
              classLoader.removeClassCache(serverRest.getJavaClass());
              GroovyCodeSource source =
                  new GroovyCodeSource(
                      Strings.isNullOrEmpty(clientRest.getClientGroovy())
                          ? serverRest.getServerGroovy()
                          : clientRest.getClientGroovy(),
                      serverRest.getGroovyId(),
                      "/groovy/script");
              source.setCachable(true);
              Class<?> serviceClass = classLoader.parseClass(source, true);
              connection
                  .createQuery(
                      "update groovy set script = :script, script_crc32 = :script_crc32, java_class = :java_class where groovy_id = :groovy_id")
                  .addParameter(
                      "script",
                      Strings.isNullOrEmpty(clientRest.getClientGroovy())
                          ? serverRest.getServerGroovy()
                          : clientRest.getClientGroovy())
                  .addParameter("script_crc32", clientRest.getClientGroovyCrc32())
                  .addParameter("java_class", serviceClass.getName())
                  .addParameter("groovy_id", serverRest.getGroovyId())
                  .executeUpdate();
              clientRest.setServerGroovyCrc32(clientRest.getClientGroovyCrc32());
              clientRest.setServerGroovy(
                  Strings.isNullOrEmpty(clientRest.getClientGroovy())
                      ? serverRest.getServerGroovy()
                      : clientRest.getClientGroovy());
            } else {
              clientRest.setServerGroovyCrc32(serverRest.getServerGroovyCrc32());
              clientRest.setServerGroovy(serverRest.getServerGroovy());
            }
          }
        }
      }

      List<Page> serverPages;
      if (!pageIds.isEmpty()) {
        Query query =
            connection.createQuery(
                "select groovy.java_class as javaClass, page.page_id as pageId, html as serverHtml, html_crc32 as serverHtmlCrc32, groovy.script as serverGroovy, groovy.script_crc32 as serverGroovyCrc32 from page inner join groovy on page.groovy_id = groovy.groovy_id where page.system = false and page.page_id not in (:pageId)");
        query.addParameter("pageId", pageIds);
        serverPages = query.executeAndFetch(Page.class);
      } else {
        Query query =
            connection.createQuery(
                "select groovy.java_class as javaClass, page.page_id as pageId, html as serverHtml, html_crc32 as serverHtmlCrc32, groovy.script as serverGroovy, groovy.script_crc32 as serverGroovyCrc32 from page inner join groovy on page.groovy_id = groovy.groovy_id where page.system = false");
        serverPages = query.executeAndFetch(Page.class);
      }
      if (serverPages != null && !serverPages.isEmpty()) {
        for (Page serverPage : serverPages) {
          String path = StringUtils.replaceChars(serverPage.getJavaClass(), '.', '/');
          serverPage.setHtmlPath(path + ".html");
          serverPage.setGroovyPath(path + ".groovy");
          serverPage.setGroovyConflicted(false);
          serverPage.setHtmlConflicted(false);
          sync.addPage(serverPage);
        }
      }

      List<Rest> serverRests;
      if (!restIds.isEmpty()) {
        Query query =
            connection.createQuery(
                "select groovy.java_class as javaClass, rest.rest_id as restId, groovy.script as serverGroovy, groovy.script_crc32 as serverGroovyCrc32 from rest inner join groovy on rest.groovy_id = groovy.groovy_id where rest.system = false and rest.rest_id not in (:restId)");
        query.addParameter("restId", restIds);
        serverRests = query.executeAndFetch(Rest.class);
      } else {
        Query query =
            connection.createQuery(
                "select groovy.java_class as javaClass, rest.rest_id as restId, groovy.script as serverGroovy, groovy.script_crc32 as serverGroovyCrc32 from rest inner join groovy on rest.groovy_id = groovy.groovy_id where rest.system = false");
        serverRests = query.executeAndFetch(Rest.class);
      }
      if (serverRests != null && !serverRests.isEmpty()) {
        for (Rest restPage : serverRests) {
          String path = StringUtils.replaceChars(restPage.getJavaClass(), '.', '/');
          restPage.setGroovyPath(path + ".groovy");
          restPage.setGroovyConflicted(false);
          sync.addRest(restPage);
        }
      }
    }
    RestResponse response = new RestResponse();
    response.setData(sync);
    response.setResultCode(HttpStatus.OK.value());
    response.setResultMessage(HttpStatus.OK.getReasonPhrase());
    return ResponseEntity.ok(response);
  }
  @Test
  public void test() throws IOException {
    // rest assured: given/expect/when
    //

    Widget w = new Widget();
    w.setName("widget-" + System.currentTimeMillis());

    // post (create)
    given()
        .log()
        .all()
        .contentType("application/json")
        .body(w)
        .expect()
        .log()
        .all()
        .statusCode(HttpStatus.OK.value())
        .when()
        .post(widgetPath);

    // get all
    // given().log().all().expect().log().all().statusCode(HttpStatus.OK.value()).and().body("",
    // hasSize(1)).when().get(widgetPath);
    // String json = get(widgetPath).asString();
    // List<Widget>

    // get all
    Widget[] widgetArray = get(widgetPath).as(Widget[].class);

    System.out.println("widget-array: " + widgetArray);
    List<Widget> widgets = Arrays.asList(widgetArray);
    for (Widget widget : widgets) {
      if (widget.getName().equals(w.getName())) {
        w = widget;
        break;
      }
    }

    System.out.println("widget-2: " + w);
    // String json = get(widgetPath).asString();
    // List<Map<String, Object>> result =
    // with(json).get("findAll { it.name == '" + w.getName() + "'}");

    // assertTrue(widgetArray.length == 1);
    // Widget w2 = widgetArray[0];

    // assertTrue(widgets.size() == 1);
    // List<Map<String, Object>> widgets = with(json).get("");
    // System.out.println("widgets: " + widgets);

    // get one
    // given().log().all().expect().log().all().statusCode(HttpStatus.OK.value()).and().body("",
    // hasSize(1)).when().get(widgetPath + "/" + );

    w.setName(w.getName() + "-2");

    // put (update)
    given()
        .log()
        .all()
        .contentType("application/json")
        .body(w)
        .expect()
        .log()
        .all()
        .statusCode(HttpStatus.OK.value())
        .when()
        .put(widgetPath + "/" + w.getId());

    // get single
    given()
        .log()
        .all()
        .expect()
        .log()
        .all()
        .statusCode(HttpStatus.OK.value())
        .body("name", equalTo(w.getName()))
        .when()
        .get(widgetPath + "/" + w.getId());

    // delete
    given()
        .log()
        .all()
        .expect()
        .log()
        .all()
        .statusCode(HttpStatus.OK.value())
        .when()
        .delete(widgetPath + "/" + w.getId());
  }