Example usage for org.springframework.http HttpMethod HEAD

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

Introduction

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

Prototype

HttpMethod HEAD

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

Click Source Link

Usage

From source file:com.frequentis.maritime.mcsr.config.SecurityConfiguration.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    //super.configure(http);
    log.debug("Configuring HttpSecurity");
    log.debug("RememberMe service {}", rememberMeServices);
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .sessionAuthenticationStrategy(sessionAuthenticationStrategy()).and()
            .addFilterBefore(basicAuthenticationFilter(), LogoutFilter.class)
            .addFilterBefore(new SkippingFilter(keycloakPreAuthActionsFilter()), LogoutFilter.class)
            .addFilterBefore(new SkippingFilter(keycloakAuthenticationProcessingFilter()),
                    X509AuthenticationFilter.class)
            .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()).and()
            //            .addFilterAfter(new CsrfCookieGeneratorFilter(), CsrfFilter.class)
            //            .exceptionHandling()
            //            .accessDeniedHandler(new CustomAccessDeniedHandler())
            //            .authenticationEntryPoint(authenticationEntryPoint)
            //        .and()
            .rememberMe().rememberMeServices(rememberMeServices).rememberMeParameter("remember-me")
            .key(jHipsterProperties.getSecurity().getRememberMe().getKey()).and().formLogin()
            .loginProcessingUrl("/api/authentication").successHandler(ajaxAuthenticationSuccessHandler)
            .failureHandler(ajaxAuthenticationFailureHandler).usernameParameter("j_username")
            .passwordParameter("j_password").permitAll().and().logout().logoutUrl("/api/logout")
            .logoutSuccessHandler(ajaxLogoutSuccessHandler).deleteCookies("JSESSIONID", "CSRF-TOKEN")
            .permitAll().and().headers().frameOptions().disable().and().authorizeRequests()
            .antMatchers("/api/register").hasAuthority(AuthoritiesConstants.ADMIN)
            .antMatchers("/api/elasticsearch/**").permitAll().antMatchers("/api/activate").permitAll()
            .antMatchers("/api/authenticate").permitAll()
            .antMatchers("/api/account/reset_password/inactivateit").permitAll()
            .antMatchers("/api/account/reset_password/finish").permitAll().antMatchers("/api/profile-info")
            .permitAll().antMatchers("/websocket/tracker").hasAuthority(AuthoritiesConstants.ADMIN)
            .antMatchers("/websocket/**").permitAll().antMatchers("/management/**")
            .hasAuthority(AuthoritiesConstants.ADMIN).antMatchers("/v2/api-docs/**").permitAll()
            .antMatchers(HttpMethod.PUT, "/api/**").authenticated().antMatchers(HttpMethod.POST, "/api/**")
            .authenticated().antMatchers(HttpMethod.DELETE, "/api/**").authenticated()
            .antMatchers(HttpMethod.TRACE, "/api/**").authenticated().antMatchers(HttpMethod.HEAD, "/api/**")
            .authenticated().antMatchers(HttpMethod.PATCH, "/api/**").authenticated()
            .antMatchers(HttpMethod.OPTIONS, "/api/**").permitAll().antMatchers(HttpMethod.GET, "/api/**")
            .permitAll().antMatchers("/swagger-resources/configuration/ui").permitAll()
            .antMatchers("/swagger-ui/index.html").permitAll().and().csrf().disable();

}

From source file:com.netflix.genie.web.services.impl.HttpFileTransferImplTest.java

/**
 * Make sure can get the last update time of a file.
 *
 * @throws GenieException On error//from ww  w .  j a v a 2s .com
 */
@Test
public void canGetLastModifiedTimeIfNoHeader() throws GenieException {
    final long time = Instant.now().toEpochMilli() - 1;
    this.server.expect(MockRestRequestMatchers.requestTo(TEST_URL))
            .andExpect(MockRestRequestMatchers.method(HttpMethod.HEAD))
            .andRespond(MockRestResponseCreators.withSuccess());
    Assert.assertTrue(this.httpFileTransfer.getLastModifiedTime(TEST_URL) > time);
    Mockito.verify(this.metadataTimerId, Mockito.times(1)).withTags(MetricsUtils.newSuccessTagsMap());
    Mockito.verify(this.metadataTimer, Mockito.times(1)).record(Mockito.anyLong(),
            Mockito.eq(TimeUnit.NANOSECONDS));
}

From source file:org.cloudfoundry.client.lib.rest.CloudControllerClientImpl.java

private String doGetFileByRange(String urlPath, Object app, String instance, String filePath, int start,
        int end, String range) {

    boolean supportsRanges;
    try {//from   w  ww .  j  av a 2 s  . c om
        supportsRanges = getRestTemplate().execute(getUrl(urlPath), HttpMethod.HEAD, new RequestCallback() {
            public void doWithRequest(ClientHttpRequest request) throws IOException {
                request.getHeaders().set("Range", "bytes=0-");
            }
        }, new ResponseExtractor<Boolean>() {
            public Boolean extractData(ClientHttpResponse response) throws IOException {
                return response.getStatusCode().equals(HttpStatus.PARTIAL_CONTENT);
            }
        }, app, instance, filePath);
    } catch (CloudFoundryException e) {
        if (e.getStatusCode().equals(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE)) {
            // must be a 0 byte file
            return "";
        } else {
            throw e;
        }
    }
    HttpHeaders headers = new HttpHeaders();
    if (supportsRanges) {
        headers.set("Range", range);
    }
    HttpEntity<Object> requestEntity = new HttpEntity<Object>(headers);
    ResponseEntity<String> responseEntity = getRestTemplate().exchange(getUrl(urlPath), HttpMethod.GET,
            requestEntity, String.class, app, instance, filePath);
    String response = responseEntity.getBody();
    boolean partialFile = false;
    if (responseEntity.getStatusCode().equals(HttpStatus.PARTIAL_CONTENT)) {
        partialFile = true;
    }
    if (!partialFile && response != null) {
        if (start == -1) {
            return response.substring(response.length() - end);
        } else {
            if (start >= response.length()) {
                if (response.length() == 0) {
                    return "";
                }
                throw new CloudFoundryException(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE,
                        "The starting position " + start + " is past the end of the file content.");
            }
            if (end != -1) {
                if (end >= response.length()) {
                    end = response.length() - 1;
                }
                return response.substring(start, end + 1);
            } else {
                return response.substring(start);
            }
        }
    }
    return response;
}

From source file:org.haiku.haikudepotserver.support.URLHelper.java

public static long payloadLength(URL url) throws IOException {
    Preconditions.checkArgument(null != url, "the url must be supplied");

    long result = -1;
    HttpURLConnection connection = null;

    switch (url.getProtocol()) {

    case "http":
    case "https":

        try {/* ww w  .ja va2  s  . co  m*/
            connection = (HttpURLConnection) url.openConnection();

            connection.setConnectTimeout(PAYLOAD_LENGTH_CONNECT_TIMEOUT);
            connection.setReadTimeout(PAYLOAD_LENGTH_READ_TIMEOUT);
            connection.setRequestMethod(HttpMethod.HEAD.name());
            connection.connect();

            String contentLengthHeader = connection.getHeaderField(HttpHeaders.CONTENT_LENGTH);

            if (!Strings.isNullOrEmpty(contentLengthHeader)) {
                long contentLength;

                try {
                    contentLength = Long.parseLong(contentLengthHeader);

                    if (contentLength > 0) {
                        result = contentLength;
                    } else {
                        LOGGER.warn("bad content length; {}", contentLength);
                    }
                } catch (NumberFormatException nfe) {
                    LOGGER.warn("malformed content length; {}", contentLengthHeader);
                }
            } else {
                LOGGER.warn("unable to get the content length header");
            }

        } finally {
            if (null != connection) {
                connection.disconnect();
            }
        }
        break;

    case "file":
        File file = new File(url.getPath());

        if (file.exists() && file.isFile()) {
            result = file.length();
        } else {
            LOGGER.warn("unable to find the local file; {}", url.getPath());
        }
        break;

    }

    LOGGER.info("did obtain length for url; {} - {}", url, result);

    return result;
}

From source file:org.springframework.http.server.reactive.ReactorHttpHandlerAdapter.java

@Override
public Mono<Void> apply(HttpServerRequest request, HttpServerResponse response) {

    NettyDataBufferFactory bufferFactory = new NettyDataBufferFactory(response.alloc());
    ServerHttpRequest adaptedRequest;/*from  w ww.  ja  va  2  s  .com*/
    ServerHttpResponse adaptedResponse;
    try {
        adaptedRequest = new ReactorServerHttpRequest(request, bufferFactory);
        adaptedResponse = new ReactorServerHttpResponse(response, bufferFactory);
    } catch (URISyntaxException ex) {
        logger.error("Invalid URL " + ex.getMessage(), ex);
        response.status(HttpResponseStatus.BAD_REQUEST);
        return Mono.empty();
    }

    if (HttpMethod.HEAD.equals(adaptedRequest.getMethod())) {
        adaptedResponse = new HttpHeadResponseDecorator(adaptedResponse);
    }

    return this.httpHandler.handle(adaptedRequest, adaptedResponse)
            .doOnError(ex -> logger.error("Handling completed with error", ex))
            .doOnSuccess(aVoid -> logger.debug("Handling completed with success"));
}

From source file:org.springframework.http.server.reactive.ServletHttpHandlerAdapter.java

@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    if (DispatcherType.ASYNC.equals(request.getDispatcherType())) {
        Throwable ex = (Throwable) request.getAttribute(WRITE_ERROR_ATTRIBUTE_NAME);
        throw new ServletException("Write publisher error", ex);
    }/*from   w  ww.j  a  v a 2  s  .  co m*/

    // Start async before Read/WriteListener registration
    AsyncContext asyncContext = request.startAsync();
    asyncContext.setTimeout(-1);

    ServerHttpRequest httpRequest = createRequest(((HttpServletRequest) request), asyncContext);
    ServerHttpResponse httpResponse = createResponse(((HttpServletResponse) response), asyncContext);

    if (HttpMethod.HEAD.equals(httpRequest.getMethod())) {
        httpResponse = new HttpHeadResponseDecorator(httpResponse);
    }

    AtomicBoolean isCompleted = new AtomicBoolean();
    HandlerResultAsyncListener listener = new HandlerResultAsyncListener(isCompleted);
    asyncContext.addListener(listener);

    HandlerResultSubscriber subscriber = new HandlerResultSubscriber(asyncContext, isCompleted);
    this.httpHandler.handle(httpRequest, httpResponse).subscribe(subscriber);
}

From source file:org.springframework.http.server.reactive.UndertowHttpHandlerAdapter.java

@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {

    ServerHttpRequest request = new UndertowServerHttpRequest(exchange, getDataBufferFactory());
    ServerHttpResponse response = new UndertowServerHttpResponse(exchange, getDataBufferFactory());

    if (HttpMethod.HEAD.equals(request.getMethod())) {
        response = new HttpHeadResponseDecorator(response);
    }//from w  w  w .  j ava2  s .  c om

    HandlerResultSubscriber resultSubscriber = new HandlerResultSubscriber(exchange);
    this.httpHandler.handle(request, response).subscribe(resultSubscriber);
}

From source file:org.springframework.test.web.reactive.server.HttpHandlerConnector.java

private ServerHttpResponse prepareResponse(ServerHttpResponse response, ServerHttpRequest request) {
    return HttpMethod.HEAD.equals(request.getMethod()) ? new HttpHeadResponseDecorator(response) : response;
}

From source file:org.springframework.web.client.RestTemplate.java

public HttpHeaders headForHeaders(String url, Object... urlVariables) throws RestClientException {
    return execute(url, HttpMethod.HEAD, null, this.headersExtractor, urlVariables);
}

From source file:org.springframework.web.client.RestTemplate.java

public HttpHeaders headForHeaders(String url, Map<String, ?> urlVariables) throws RestClientException {
    return execute(url, HttpMethod.HEAD, null, this.headersExtractor, urlVariables);
}