Example usage for org.springframework.http HttpMethod POST

List of usage examples for org.springframework.http HttpMethod POST

Introduction

In this page you can find the example usage for org.springframework.http HttpMethod POST.

Prototype

HttpMethod POST

To view the source code for org.springframework.http HttpMethod POST.

Click Source Link

Usage

From source file:com.toptal.conf.SecurityConfiguration.java

@Override
protected final void configure(final HttpSecurity http) throws Exception {
    final String format = "%s/*";
    http.csrf().disable();/*  w w w  .  jav a  2 s.  com*/
    http.httpBasic();
    http.authorizeRequests().antMatchers(HttpMethod.POST, SignupController.PATH).anonymous()
            .antMatchers(UserController.PATH).hasRole(Role.ROLE_MANAGER.text())
            .antMatchers(String.format(format, UserController.PATH)).hasRole(Role.ROLE_MANAGER.text())
            .antMatchers(EntryController.PATH).hasRole(Role.ROLE_USER.text())
            .antMatchers(String.format(format, EntryController.PATH)).hasRole(Role.ROLE_USER.text());
}

From source file:fi.okm.mpass.shibboleth.profile.impl.BuildMetaRestResponseTest.java

/**
 * Runs action with unsupported HTTP method.
 * @throws UnsupportedEncodingException/*w  ww  .j  av a2  s.  co  m*/
 * @throws ComponentInitializationException
 */
@Test
public void testInvalidMethod() throws UnsupportedEncodingException, ComponentInitializationException {
    final MockHttpServletRequest httpRequest = new MockHttpServletRequest();
    httpRequest.setMethod(HttpMethod.POST.toString());
    action.setHttpServletRequest(httpRequest);
    verifyErrorDTO(action, HttpStatus.SC_METHOD_NOT_ALLOWED);
}

From source file:org.openlmis.fulfillment.service.referencedata.UserReferenceDataServiceTest.java

@Test
public void shouldReturnNullIfUserCannotBeFound() {
    // given//from  w  w  w .ja  v  a  2s.c o m
    String name = "userName";

    ResponseEntity response = mock(ResponseEntity.class);

    Map<String, Object> payload = new HashMap<>();
    payload.put("username", name);

    // when
    when(restTemplate.exchange(any(URI.class), eq(HttpMethod.POST), any(HttpEntity.class),
            any(ParameterizedTypeReference.class))).thenReturn(response);

    PageDto<UserDto> page = new PageDto<>(new PageImpl<>(Collections.emptyList()));
    when(response.getBody()).thenReturn(page);

    UserDto user = service.findUser(name);

    // then
    verify(restTemplate).exchange(uriCaptor.capture(), eq(HttpMethod.POST), entityCaptor.capture(),
            any(ParameterizedTypeReference.class));

    URI uri = uriCaptor.getValue();
    String url = service.getServiceUrl() + service.getUrl() + "search";

    assertThat(uri.toString(), is(equalTo(url)));
    assertThat(user, is(nullValue()));

    assertAuthHeader(entityCaptor.getValue());
    assertThat(entityCaptor.getValue().getBody(), is(payload));
}

From source file:com.example.DatastoreSampleApplicationTests.java

@Test
public void basicTest() throws Exception {
    Singer johnDoe = new Singer(null, "John", "Doe", null);
    Singer janeDoe = new Singer(null, "Jane", "Doe", null);
    Singer richardRoe = new Singer(null, "Richard", "Roe", null);
    Singer frodoBaggins = new Singer(null, "Frodo", "Baggins", null);

    List<Singer> singersAsc = getSingers("/singers?sort=lastName,ASC");
    assertThat(singersAsc).as("Verify ASC order").containsExactly(johnDoe, janeDoe, richardRoe);

    List<Singer> singersDesc = getSingers("/singers?sort=lastName,DESC");
    assertThat(singersDesc).as("Verify DESC order").containsExactly(richardRoe, johnDoe, janeDoe);

    sendRequest("/singers",
            "{\"singerId\": \"singerFrodo\", \"firstName\":" + " \"Frodo\", \"lastName\": \"Baggins\"}",
            HttpMethod.POST);

    Awaitility.await().atMost(15, TimeUnit.SECONDS)
            .until(() -> getSingers("/singers?sort=lastName,ASC").size() == 4);

    List<Singer> singersAfterInsertion = getSingers("/singers?sort=lastName,ASC");
    assertThat(singersAfterInsertion).as("Verify post").containsExactly(frodoBaggins, johnDoe, janeDoe,
            richardRoe);//from w  ww .  ja va  2 s  . c o  m

    sendRequest("/singers/singer1", null, HttpMethod.DELETE);

    Awaitility.await().atMost(15, TimeUnit.SECONDS)
            .until(() -> getSingers("/singers?sort=lastName,ASC").size() == 3);

    List<Singer> singersAfterDeletion = getSingers("/singers?sort=lastName,ASC");
    assertThat(singersAfterDeletion).as("Verify Delete").containsExactly(frodoBaggins, janeDoe, richardRoe);

    assertThat(baos.toString()).as("Verify relationships saved in transaction")
            .contains("Relationship links "
                    + "were saved between a singer, bands, and instruments in a single transaction: "
                    + "Singer{singerId='singer2', firstName='Jane', lastName='Doe', "
                    + "albums=[Album{albumName='a', date=2012-01-20}, Album{albumName='b', "
                    + "date=2018-02-12}], firstBand=General Band, bands=General Band,Big Bland Band, "
                    + "personalInstruments=recorder,cow bell}");

    assertThat(this.singerRepository.findById("singer2").get().getPersonalInstruments().stream()
            .map(Instrument::getType).collect(Collectors.toList())).containsExactlyInAnyOrder("recorder",
                    "cow bell");

    assertThat(this.singerRepository.findById("singer2").get().getBands().stream().map(Band::getName)
            .collect(Collectors.toList())).containsExactlyInAnyOrder("General Band", "Big Bland Band");

    Singer singer3 = this.singerRepository.findById("singer3").get();

    assertThat(singer3.getPersonalInstruments().stream().map(Instrument::getType).collect(Collectors.toList()))
            .containsExactlyInAnyOrder("triangle", "marimba");

    assertThat(singer3.getBands().stream().map(Band::getName).collect(Collectors.toList()))
            .containsExactlyInAnyOrder("Crooked Still", "Big Bland Band");

    assertThat(singer3.getLastModifiedTime()).isAfter(LocalDateTime.parse("2000-01-01T00:00:00"));

    assertThat(baos.toString())
            .contains("Query by example\n" + "Singer{singerId='singer1', firstName='John', lastName='Doe', "
                    + "albums=[], firstBand=null, bands=, personalInstruments=}\n"
                    + "Singer{singerId='singer2', firstName='Jane', lastName='Doe', "
                    + "albums=[Album{albumName='a', date=2012-01-20}");

    assertThat(baos.toString()).contains(
            "Using Pageable parameter\n" + "Singer{singerId='singer1', firstName='John', lastName='Doe', "
                    + "albums=[], firstBand=null, bands=, personalInstruments=}\n"
                    + "Singer{singerId='singer2', firstName='Jane', lastName='Doe', "
                    + "albums=[Album{albumName='a', date=2012-01-20}");

    assertThat(baos.toString()).contains("This concludes the sample.");
}

From source file:com.consol.citrus.admin.connector.WebSocketPushMessageListenerTest.java

@Test
public void testNoContext() throws Exception {
    Message inbound = new DefaultMessage("Hello Citrus!");

    reset(restTemplate, context);/* ww w.  j  av  a  2  s . c  om*/
    when(restTemplate.exchange(eq("http://localhost:8080/connector/message/inbound?processId="),
            eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))).thenAnswer(invocation -> {
                HttpEntity request = (HttpEntity) invocation.getArguments()[2];

                Assert.assertEquals(request.getBody().toString(), inbound.toString());

                return ResponseEntity.ok().build();
            });

    pushMessageListener.onInboundMessage(inbound, null);
    pushMessageListener.onInboundMessage(inbound, context);

    verify(restTemplate, times(2)).exchange(eq("http://localhost:8080/connector/message/inbound?processId="),
            eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class));
}

From source file:org.openlmis.fulfillment.service.stockmanagement.StockEventStockManagementServiceTest.java

@Test(expected = DataRetrievalException.class)
public void shouldReturnDataRetrievalExceptionOnOtherErrorResponseCodes() throws IOException {
    when(restTemplate.exchange(any(URI.class), eq(HttpMethod.POST), any(HttpEntity.class), eq(UUID.class)))
            .thenThrow(new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR));

    service.submit(new StockEventDto());
}

From source file:io.fabric8.che.starter.client.CheRestClient.java

public Workspace createWorkspace(String cheServerURL, String name, String stack, String repo, String branch)
        throws IOException {

    // The first step is to create the workspace
    String url = generateURL(cheServerURL, CheRestEndpoints.CREATE_WORKSPACE);
    String jsonTemplate = workspaceTemplate.createRequest().setName(name).setStack(stack)
            .setDescription(workspaceHelper.getDescription(repo, branch)).getJSON();

    RestTemplate template = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> entity = new HttpEntity<String>(jsonTemplate, headers);

    ResponseEntity<Workspace> workspaceResponse = template.exchange(url, HttpMethod.POST, entity,
            Workspace.class);
    Workspace workspace = workspaceResponse.getBody();

    LOG.info("Workspace has been created: {}", workspace);

    workspace.setName(workspace.getConfig().getName());
    workspace.setDescription(workspace.getConfig().getDescription());

    for (WorkspaceLink link : workspace.getLinks()) {
        if (WORKSPACE_LINK_IDE_URL.equals(link.getRel())) {
            workspace.setWorkspaceIdeUrl(link.getHref());
            break;
        }/*w w w. jav a  2  s .  c  o m*/
    }

    return workspace;
}

From source file:architecture.user.spring.config.SecurityConfig.java

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/decorators/**").antMatchers("/images/**").antMatchers("/fonts/**")
            .antMatchers("/includes/**").antMatchers("/js/**").antMatchers("/styles/**").antMatchers("/index.*")
            .antMatchers("/main.*").antMatchers(HttpMethod.POST, "/accounts/login");
}

From source file:com.orange.ngsi.client.NotifyContextRequestTest.java

@Test
public void notifyContextRequestOK() throws Exception {

    ngsiClient.protocolRegistry.unregisterHost(baseUrl);

    String responseBody = json(jsonConverter, createNotifyContextResponseTempSensor());

    this.mockServer.expect(requestTo(baseUrl + "/ngsi10/notifyContext")).andExpect(method(HttpMethod.POST))
            .andExpect(jsonPath("$.subscriptionId").value("1"))
            .andExpect(jsonPath("$.originator").value("http://iotAgent"))
            .andExpect(jsonPath("$.contextResponses[*]", hasSize(1)))
            .andExpect(jsonPath("$.contextResponses[0].contextElement.id").value("S1"))
            .andExpect(jsonPath("$.contextResponses[0].contextElement.type").value("TempSensor"))
            .andExpect(jsonPath("$.contextResponses[0].contextElement.isPattern").value("false"))
            .andExpect(jsonPath("$.contextResponses[0].contextElement.attributes[*]", hasSize(1)))
            .andExpect(jsonPath("$.contextResponses[0].contextElement.attributes[0].name").value("temp"))
            .andExpect(jsonPath("$.contextResponses[0].contextElement.attributes[0].type").value("float"))
            .andExpect(jsonPath("$.contextResponses[0].contextElement.attributes[0].value").value("15.5"))
            .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON));

    NotifyContextResponse response = ngsiClient.notifyContext(baseUrl, null, createNotifyContextTempSensor(0))
            .get();/*  w w w .j av  a2s .  com*/
    this.mockServer.verify();

    Assert.assertEquals(CodeEnum.CODE_200.getLabel(), response.getResponseCode().getCode());
}

From source file:org.dawnsci.marketplace.config.SecurityConfiguration.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.formLogin().loginPage("/signin").loginProcessingUrl("/signin/authenticate")
            .failureUrl("/signin?param.error=bad_credentials").and().logout().logoutUrl("/signout")
            .deleteCookies("JSESSIONID").and().authorizeRequests().antMatchers("/**").permitAll()
            .antMatchers(HttpMethod.POST, "/**").authenticated().antMatchers(HttpMethod.PUT, "/**")
            .authenticated().antMatchers(HttpMethod.DELETE, "/**").authenticated().and().httpBasic().and()
            .rememberMe();/*w  w w .  j  a  v  a2 s.c o m*/
}