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:org.echocat.marquardt.example.ServiceLoginIntegrationTest.java

private void whenSignedContentIsSent() throws IOException {
    getClient().sendSignedPayloadTo(baseUriOfApp() + "/exampleservice/someProtectedResourceWithPayload",
            HttpMethod.POST.name(), _payloadToSign, String.class, _certificate);
}

From source file:com.card.loop.xyz.controller.LearningObjectController.java

public void uploadAllLOToInformatron() {
    try {/*  w  w w.  j a  v a  2s  . c  o m*/
        SimpleClientHttpRequestFactory rf = new SimpleClientHttpRequestFactory();
        ClientHttpRequest req = rf.createRequest(
                URI.create(AppConfig.LOOP_URL + "/loop-XYZ/loop/LO/availableLO"), HttpMethod.GET);
        ClientHttpResponse response = req.execute();

        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(response.getBody()));
        ClientHttpRequest req2 = rf.createRequest(
                URI.create(AppConfig.INFORMATRON_URL + "/InformatronYX/informatron/LO/upload/availableLOs"),
                HttpMethod.POST);
        BufferedWriter req2Writer = new BufferedWriter(new OutputStreamWriter(req2.getBody()));
        String string = br.readLine();
        br.close();

        req2Writer.write(string);
        req2Writer.close();
        req2.getHeaders().add("Content-Type", "application/json");
        System.out.println(string);
        ClientHttpResponse response2 = req2.execute();
        BufferedReader reader = new BufferedReader(new InputStreamReader(response2.getBody()));

        try {
            String str = reader.readLine();
            if (str.equals("true"))
                System.out.println("SUCCESS!!");
            else
                System.err.println("FAILL!!");
        } catch (Exception ex) {
            Logger.getLogger(LearningObjectController.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (IOException ex) {
        Logger.getLogger(LearningObjectController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.ng200.openolympus.WebSecurityConfig.java

@Override
protected void configure(final HttpSecurity http) throws Exception {
    http.addFilterBefore(this.characterEncodingFilter(), ChannelProcessingFilter.class).csrf().disable()
            .headers().xssProtection().and().formLogin().loginPage("/login").failureUrl("/login-failure")
            .loginProcessingUrl("/login").usernameParameter("username").passwordParameter("password")
            .permitAll().and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessUrl("/").permitAll().and().rememberMe().rememberMeServices(this.rememberMeServices())
            .tokenRepository(this.persistentTokenRepository).key(this.persistentTokenKey).and()
            .authorizeRequests().antMatchers(WebSecurityConfig.permittedAny).permitAll().and()
            .authorizeRequests().antMatchers(HttpMethod.POST, WebSecurityConfig.authorisedPost).authenticated()
            .and().authorizeRequests().antMatchers(HttpMethod.GET, WebSecurityConfig.authorisedGet)
            .authenticated().and().authorizeRequests()
            .antMatchers(HttpMethod.GET, WebSecurityConfig.permittedGet).permitAll().and().authorizeRequests()
            .antMatchers(WebSecurityConfig.administrativeAny).hasAuthority(Role.SUPERUSER).and().httpBasic();
}

From source file:com.teradata.benchto.driver.DriverAppIntegrationTest.java

private void verifyBenchmarkStart(String benchmarkName, String uniqueBenchmarkName) {
    restServiceServer/* w w w. j  a  v a  2  s  . co m*/
            .expect(matchAll(requestTo("http://benchmark-service:8080/v1/benchmark/generate-unique-names"),
                    method(HttpMethod.POST), jsonPath("$.[0].name", is(benchmarkName))))
            .andRespond(withSuccess().contentType(APPLICATION_JSON).body("[\"" + uniqueBenchmarkName + "\"]"));

    restServiceServer
            .expect(matchAll(requestTo("http://benchmark-service:8080/v1/time/current-time-millis"),
                    method(HttpMethod.POST)))
            .andRespond(request -> withSuccess().contentType(APPLICATION_JSON)
                    .body("" + System.currentTimeMillis()).createResponse(request));

    restServiceServer
            .expect(matchAll(
                    requestTo("http://benchmark-service:8080/v1/benchmark/" + uniqueBenchmarkName
                            + "/BEN_SEQ_ID/start"),
                    method(HttpMethod.POST), jsonPath("$.name", is(benchmarkName)),
                    jsonPath("$.environmentName", is("TEST_ENV"))))
            .andRespond(withSuccess());

    restServiceServer
            .expect(matchAll(requestTo("http://graphite:18088/events/"), method(HttpMethod.POST),
                    jsonPath("$.what", is("Benchmark " + uniqueBenchmarkName + " started")),
                    jsonPath("$.tags", is("benchmark started TEST_ENV")), jsonPath("$.data", is(""))))
            .andRespond(withSuccess());
}

From source file:org.obiba.mica.core.service.MailService.java

private synchronized void sendEmail(String subject, String templateName, Map<String, String> context,
        String recipient) {//w w w .  jav a  2  s .  c o m
    try {
        RestTemplate template = newRestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set(APPLICATION_AUTH_HEADER, getApplicationAuth());
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        StringBuilder form = new StringBuilder(Strings.isNullOrEmpty(recipient) ? "" : recipient + "&");
        form.append("subject=").append(encode(subject, "UTF-8")).append("&template=")
                .append(encode(templateName, "UTF-8"));
        context.forEach((k, v) -> {
            try {
                form.append("&").append(k).append("=").append(encode(v, "UTF-8"));
            } catch (UnsupportedEncodingException ignored) {
            }
        });
        HttpEntity<String> entity = new HttpEntity<>(form.toString(), headers);

        ResponseEntity<String> response = template.exchange(getNotificationsUrl(), HttpMethod.POST, entity,
                String.class);

        if (response.getStatusCode().is2xxSuccessful()) {
            log.info("Email sent via Agate");
        } else {
            log.error("Sending email via Agate failed with status: {}", response.getStatusCode());
        }
    } catch (Exception e) {
        log.error("Agate connection failure: {}", e.getMessage());
    }
}

From source file:com.cloudera.nav.sdk.client.NavApiCient.java

/**
 * {@link #getRelationBatch(MetadataQuery) getRelationBatch} with entities
 */// ww  w  . jav  a  2  s. co m
public ResultsBatch<Map<String, Object>> getEntityBatch(MetadataQuery metadataQuery) {
    String fullUrlPost = pagingUrl("entities");
    return sendRequest(fullUrlPost, HttpMethod.POST, EntityResultsBatch.class, metadataQuery);
}

From source file:org.echocat.marquardt.authority.AuthorityIntegrationTest.java

private void doPost(final String url, final Object content) throws Exception {
    final byte[] bytes;
    try (final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
        _objectMapper.writeValue(byteArrayOutputStream, content);
        byteArrayOutputStream.flush();//from   ww  w .  j ava 2s.c om
        bytes = byteArrayOutputStream.toByteArray();
    }
    final URI urlToPost = new URI(url);
    final ClientHttpRequest request = new OkHttpClientHttpRequestFactory().createRequest(urlToPost,
            HttpMethod.POST);
    request.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
    request.getHeaders().add(X_CERTIFICATE.getHeaderName(), Base64.encodeBase64URLSafeString(CERTIFICATE));
    request.getBody().write(bytes);
    final ClientHttpResponse response = request.execute();
    _status = response.getStatusCode().value();
    try (final InputStream inputStream = response.getBody()) {
        try (final InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charsets.UTF_8)) {
            _response = CharStreams.toString(inputStreamReader);
        }
    }
}

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

@Test
public void unsubscribeContextRequestOK_XML() throws Exception {

    ngsiClient.protocolRegistry.registerHost(baseUrl);

    String responseBody = xml(xmlConverter,
            createUnsubscribeContextResponse(CodeEnum.CODE_200, subscriptionID));

    this.mockServer.expect(requestTo(baseUrl + "/ngsi10/unsubscribeContext")).andExpect(method(HttpMethod.POST))
            .andExpect(header("Content-Type", MediaType.APPLICATION_XML_VALUE))
            .andExpect(header("Accept", MediaType.APPLICATION_XML_VALUE))
            .andExpect(xpath("unsubscribeContextRequest/subscriptionId").string(subscriptionID))
            .andRespond(withSuccess(responseBody, MediaType.APPLICATION_XML));

    UnsubscribeContextResponse response = ngsiClient.unsubscribeContext(baseUrl, null, subscriptionID).get();

    this.mockServer.verify();

    Assert.assertEquals(subscriptionID, response.getSubscriptionId());
    Assert.assertEquals(CodeEnum.CODE_200.getLabel(), response.getStatusCode().getCode());
}

From source file:aiai.ai.station.LaunchpadRequester.java

/**
 * this scheduler is being run at the station side
 *
 * long fixedDelay()/* www.  j av  a 2s  .c o  m*/
 * Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.
 */
public void fixedDelay() {
    if (globals.isUnitTesting) {
        return;
    }
    if (!globals.isStationEnabled) {
        return;
    }

    ExchangeData data = new ExchangeData();
    String stationId = stationService.getStationId();
    if (stationId == null) {
        data.setCommand(new Protocol.RequestStationId());
    }
    data.setStationId(stationId);

    if (stationId != null) {
        // always report about current active sequences, if we have actual stationId
        data.setCommand(stationTaskService.produceStationSequenceStatus());
        data.setCommand(stationService.produceReportStationStatus());
        final boolean b = stationTaskService.isNeedNewExperimentSequence(stationId);
        if (b) {
            data.setCommand(new Protocol.RequestTask(globals.isAcceptOnlySignedSnippets));
        }
        if (System.currentTimeMillis() - lastRequestForMissingResources > 15_000) {
            data.setCommand(new Protocol.CheckForMissingOutputResources());
            lastRequestForMissingResources = System.currentTimeMillis();
        }
    }

    reportSequenceProcessingResult(data);

    List<Command> cmds;
    synchronized (commands) {
        cmds = new ArrayList<>(commands);
        commands.clear();
    }
    data.setCommands(cmds);

    // !!! always use data.setCommand() for correct initializing stationId !!!

    // we have to pull new tasks from server constantly
    try {
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        headers.setContentType(MediaType.APPLICATION_JSON);
        if (globals.isSecureRestUrl) {
            String auth = globals.restUsername + '=' + globals.restToken + ':' + globals.stationRestPassword;
            byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.US_ASCII));
            String authHeader = "Basic " + new String(encodedAuth);
            headers.set("Authorization", authHeader);
        }

        HttpEntity<ExchangeData> request = new HttpEntity<>(data, headers);

        ResponseEntity<ExchangeData> response = restTemplate.exchange(globals.serverRestUrl, HttpMethod.POST,
                request, ExchangeData.class);
        ExchangeData result = response.getBody();

        addCommands(commandProcessor.processExchangeData(result).getCommands());
        log.debug("fixedDelay(), {}", result);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            log.error("Error 401 accessing url {}, globals.isSecureRestUrl: {}", globals.serverRestUrl,
                    globals.isSecureRestUrl);
        } else {
            throw e;
        }
    } catch (RestClientException e) {
        log.error("Error accessing url: {}", globals.serverRestUrl);
        log.error("Stacktrace", e);
    }
}

From source file:org.appverse.web.framework.backend.test.util.frontfacade.BaseAbstractAuthenticationRequiredTest.java

protected TestLoginInfo simpleLogin() throws Exception {
    CredentialsVO credentialsVO = new CredentialsVO();
    credentialsVO.setUsername(getUsername());
    credentialsVO.setPassword(getPassword());
    HttpEntity<CredentialsVO> entity = new HttpEntity<CredentialsVO>(credentialsVO);

    ResponseEntity<AuthorizationData> responseEntity = restTemplate.exchange(
            "http://localhost:" + port + baseApiPath + simpleAuthenticationEndpointPath, HttpMethod.POST,
            entity, AuthorizationData.class);
    assertEquals(HttpStatus.OK, responseEntity.getStatusCode());

    List<String> xsrfTokenHeaders = responseEntity.getHeaders().get(DEFAULT_CSRF_HEADER_NAME);
    assertNotNull(xsrfTokenHeaders);/*  ww w. j av  a2s.co m*/
    assertEquals(xsrfTokenHeaders.size(), 1);
    assertNotNull(xsrfTokenHeaders.get(0));
    AuthorizationData authorizationData = responseEntity.getBody();
    assertNotNull(authorizationData);
    List<String> roles = authorizationData.getRoles();
    assertNotNull(roles);
    assertEquals(roles.size() > 0, true);
    assertEquals(roles.contains(getAnUserRole()), true);

    TestLoginInfo loginInfo = new TestLoginInfo();
    loginInfo.setXsrfToken(xsrfTokenHeaders.get(0));
    loginInfo.setAuthorizationData(authorizationData);
    loginInfo.setJsessionid(responseEntity.getHeaders().getFirst("Set-Cookie"));
    return loginInfo;
}