Example usage for org.springframework.http HttpHeaders HttpHeaders

List of usage examples for org.springframework.http HttpHeaders HttpHeaders

Introduction

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

Prototype

public HttpHeaders() 

Source Link

Document

Construct a new, empty instance of the HttpHeaders object.

Usage

From source file:org.jodconverter.sample.springboot.ConverterController.java

@PostMapping("/converter")
public Object convert(@RequestParam("inputFile") final MultipartFile inputFile,
        @RequestParam(name = "outputFormat", required = false) final String outputFormat,
        final RedirectAttributes redirectAttributes) {

    if (inputFile.isEmpty()) {
        redirectAttributes.addFlashAttribute(ATTRNAME_ERROR_MESSAGE, "Please select a file to upload.");
        return ON_ERROR_REDIRECT;
    }/*w ww  .jav a 2  s.co m*/

    if (StringUtils.isBlank(outputFormat)) {
        redirectAttributes.addFlashAttribute(ATTRNAME_ERROR_MESSAGE, "Please select an output format.");
        return ON_ERROR_REDIRECT;
    }

    // Here, we could have a dedicated service that would convert document
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

        final DocumentFormat targetFormat = DefaultDocumentFormatRegistry.getFormatByExtension(outputFormat);
        converter.convert(inputFile.getInputStream())
                .as(DefaultDocumentFormatRegistry
                        .getFormatByExtension(FilenameUtils.getExtension(inputFile.getOriginalFilename())))
                .to(baos).as(targetFormat).execute();

        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(targetFormat.getMediaType()));
        headers.add("Content-Disposition",
                "attachment; filename=" + FilenameUtils.getBaseName(inputFile.getOriginalFilename()) + "."
                        + targetFormat.getExtension());
        return new ResponseEntity<>(baos.toByteArray(), headers, HttpStatus.OK);

    } catch (OfficeException | IOException e) {
        redirectAttributes.addFlashAttribute(ATTRNAME_ERROR_MESSAGE,
                "Unable to convert the file " + inputFile.getOriginalFilename() + ". Cause: " + e.getMessage());
    }

    return ON_ERROR_REDIRECT;
}

From source file:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.CreateDisease.java

/**
 * Method, where Disease information is pushed to server in order to create user.
 * All heavy lifting is made here.//from w  w w. j a v a  2  s .co  m
 *
 * @param diseases only one Disease object is accepted
 * @return information about created disease
 */
@Override
protected Disease doInBackground(Disease... diseases) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_DISEASES;

    setState(RUNNING, R.string.working_ws_create_disease);
    HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAuthorization(authHeader);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
    requestHeaders.setContentType(MediaType.APPLICATION_XML);

    SSLSimpleClientHttpRequestFactory factory = new SSLSimpleClientHttpRequestFactory();
    // Create a new RestTemplate instance
    RestTemplate restTemplate = new RestTemplate(factory);
    restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter());

    Disease disease = diseases[0];

    try {
        Log.d(TAG, url);

        HttpEntity<Disease> entity = new HttpEntity<Disease>(disease, requestHeaders);
        // Make the network request
        return restTemplate.postForObject(url, entity, Disease.class);
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return null;
}

From source file:org.trustedanalytics.h2oscoringengine.publisher.http.HttpCommunicationTest.java

private HttpEntity<String> createExpectedBasicAuthRequest(String basicAuthToken) {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + basicAuthToken);

    return new HttpEntity<>(headers);
}

From source file:com.biz.report.controller.ReportController.java

@RequestMapping(value = "/years")
public ResponseEntity<List<String>> readYears() {
    List<String> list = reportService.readYears();

    HttpHeaders headers = new HttpHeaders();
    headers.add("success", "Success");
    return new ResponseEntity<List<String>>(list, headers, HttpStatus.OK);
}

From source file:io.github.howiefh.jeews.modules.oauth2.controller.AuthorizeController.java

@RequestMapping("/authentication")
public Object authorize(HttpServletRequest request) throws URISyntaxException, OAuthSystemException {
    try {//from   w  w w.  ja va 2s .c o  m

        // OAuth ?
        OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);

        // id?
        if (!oAuthService.checkClientId(oauthRequest.getClientId())) {
            OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                    .setError(OAuthError.TokenResponse.INVALID_CLIENT)
                    .setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION).buildJSONMessage();
            return new ResponseEntity<String>(response.getBody(),
                    HttpStatus.valueOf(response.getResponseStatus()));
        }

        Subject subject = SecurityUtils.getSubject();
        // ?
        if (!subject.isAuthenticated()) {
            if (!login(subject, request)) {// ?
                // TODO
                HttpHeaders headers = new HttpHeaders();
                headers.setLocation(new URI(loginUrl));
                return new ResponseEntity<Object>(headers, HttpStatus.UNAUTHORIZED);
            }
        }

        String username = (String) subject.getPrincipal();
        // ???
        String authorizationCode = null;
        // responseType??CODE?TOKEN
        String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
        OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
        // OAuth?
        OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse
                .authorizationResponse(request, HttpServletResponse.SC_FOUND);
        if (responseType.equals(ResponseType.CODE.toString())) {
            authorizationCode = oauthIssuerImpl.authorizationCode();
            oAuthService.addAuthCode(authorizationCode, username);
            // ??
            builder.setCode(authorizationCode);
        } else if (responseType.equals(ResponseType.TOKEN.toString())) {
            final String accessToken = oauthIssuerImpl.accessToken();
            oAuthService.addAccessToken(accessToken, username);
            builder.setAccessToken(accessToken);
            builder.setParam("token_type", TokenType.BEARER.toString());
            builder.setExpiresIn(oAuthService.getExpireIn());
        }

        // ???
        String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);

        // ?
        final OAuthResponse response = builder.location(redirectURI).buildQueryMessage();

        // ?OAuthResponseResponseEntity?
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(new URI(response.getLocationUri()));
        return new ResponseEntity<Object>(headers, HttpStatus.valueOf(response.getResponseStatus()));
    } catch (OAuthProblemException e) {
        // ?
        String redirectUri = e.getRedirectUri();
        if (OAuthUtils.isEmpty(redirectUri)) {
            // redirectUri
            return new ResponseEntity<String>("OAuth callback url needs to be provided by client!!!",
                    HttpStatus.NOT_FOUND);
        }

        // ??error=
        final OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).error(e)
                .location(redirectUri).buildQueryMessage();
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(new URI(response.getLocationUri()));
        return new ResponseEntity<Object>(headers, HttpStatus.valueOf(response.getResponseStatus()));
    }
}

From source file:ch.wisv.areafiftylan.products.controller.OrderRestController.java

/**
 * When a User does a POST request to /orders, a new Order is created. The requestbody is a TicketDTO, so an order
 * always contains at least one ticket. Optional next tickets should be added to the order by POSTing to the
 * location provided.//from w w w. j a v a2s.c  o  m
 *
 * @param auth      The User that is currently logged in
 * @param ticketDTO Object containing information about the Ticket that is being ordered.
 *
 * @return A message informing about the result of the request
 */
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/orders", method = RequestMethod.POST)
@JsonView(View.OrderOverview.class)
public ResponseEntity<?> createOrder(Authentication auth, @RequestBody @Validated TicketDTO ticketDTO) {
    HttpHeaders headers = new HttpHeaders();
    User user = (User) auth.getPrincipal();

    // You can't buy non-buyable Tickts for yourself, this should be done via the createAdminOrder() method.
    if (!ticketDTO.getType().isBuyable()) {
        return createResponseEntity(HttpStatus.FORBIDDEN,
                "Can't order tickets with type " + ticketDTO.getType().getText());
    }

    Order order = orderService.create(user.getId(), ticketDTO);

    headers.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
            .buildAndExpand(order.getId()).toUri());

    return createResponseEntity(HttpStatus.CREATED, headers,
            "Ticket available and order successfully created at " + headers.getLocation(), order);
}

From source file:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.CreateArtifact.java

/**
 * Method, where artifact information is pushed to server in order to create user.
 * All heavy lifting is made here./*from  w  w  w  . ja  v a 2  s .c  o  m*/
 *
 * @param artifacts only one Artifact object is accepted
 * @return information about created artifact
 */
@Override
protected Artifact doInBackground(Artifact... artifacts) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_ARTIFACTS;

    setState(RUNNING, R.string.working_ws_create_artifact);
    HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAuthorization(authHeader);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
    requestHeaders.setContentType(MediaType.APPLICATION_XML);

    SSLSimpleClientHttpRequestFactory factory = new SSLSimpleClientHttpRequestFactory();
    // Create a new RestTemplate instance
    RestTemplate restTemplate = new RestTemplate(factory);
    restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter());

    Artifact artifact = artifacts[0];

    try {
        Log.d(TAG, url);

        HttpEntity<Artifact> entity = new HttpEntity<Artifact>(artifact, requestHeaders);
        // Make the network request
        return restTemplate.postForObject(url, entity, Artifact.class);
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return null;
}

From source file:org.akaademiwolof.ConfigurationTests.java

@SuppressWarnings("static-access")
//@Test/* ww w  .j  av  a  2 s  .  c om*/
public void shouldUpdateWordWhenSendingRequestToController() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    JSONObject requestJson = new JSONObject();
    requestJson.wrap(json);
    System.out.print(requestJson.toString());

    headers.setContentType(MediaType.APPLICATION_JSON);

    HttpEntity<String> entity = new HttpEntity<String>(json, headers);

    ResponseEntity<String> loginResponse = restTemplate.exchange(localhostUrl, HttpMethod.POST, entity,
            String.class);
    if (loginResponse.getStatusCode() == HttpStatus.OK) {
        JSONObject wordJson = new JSONObject(loginResponse.getBody());
        System.out.print(loginResponse.getStatusCode());
        assertThat(wordJson != null);

    } else if (loginResponse.getStatusCode() == HttpStatus.BAD_REQUEST) {
        System.out.print(loginResponse.getStatusCode());
    }

}

From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsServiceEnabledPredefinedTests.java

@Test
public void basicAuthenticationServiceTestInvalidCredentials() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Basic " + new String(Base64.encode("user:badpassword".getBytes("UTF-8"))));
    HttpEntity<String> entity = new HttpEntity<String>("headers", headers);

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