List of usage examples for org.springframework.http HttpHeaders set
@Override public void set(String headerName, @Nullable String headerValue)
From source file:eu.freme.broker.eservices.ELink.java
@RequestMapping(value = "/e-link/templates", method = RequestMethod.POST) @Secured({ "ROLE_USER", "ROLE_ADMIN" }) public ResponseEntity<String> createTemplate( @RequestHeader(value = "Accept", required = false) String acceptHeader, @RequestHeader(value = "Content-Type", required = false) String contentTypeHeader, // @RequestParam(value = "informat", required=false) String // informat, // @RequestParam(value = "f", required=false) String f, // @RequestParam(value = "outformat", required=false) String // outformat, // @RequestParam(value = "o", required=false) String o, // Type was moved as endpoint-type field of the template. // @RequestParam(value = "visibility", required=false) String // visibility, // Type was moved as endpoint-type field of the template. // @RequestParam(value = "type", required=false) String type, @RequestParam Map<String, String> allParams, @RequestBody String postBody) { try {/* w w w. j a va2 s .c o m*/ NIFParameterSet nifParameters = this.normalizeNif(postBody, acceptHeader, contentTypeHeader, allParams, false); // NOTE: informat was defaulted to JSON before! Now it is TURTLE. // NOTE: outformat was defaulted to turtle, if acceptHeader=="*/*" // and informat==null, otherwise to JSON. Now it is TURTLE. // NOTE: switched back to JSON since we use MySQL and RDF is no // longer supported, but JSON only. nifParameters.setInformat(RDFSerialization.JSON); nifParameters.setOutformat(RDFSerialization.JSON); Template template; if (nifParameters.getInformat().equals(RDFConstants.RDFSerialization.JSON)) { JSONObject jsonObj = new JSONObject(nifParameters.getInput()); templateValidator.validateTemplateEndpoint(jsonObj.getString("endpoint")); // AccessDeniedException can be thrown, if current // authentication is the anonymousUser template = new Template(jsonObj); } else { throw new BadRequestException("Other formats then JSON are no longer supported for templates."); // Model model = // rdfConversionService.unserializeRDF(nifParameters.getInput(), // nifParameters.getInformat()); // template = new Template( // OwnedResource.Visibility.getByString(visibility), // Template.Type.getByString(jsonObj.getString("endpoint-type")), // model); // templateValidator.validateTemplateEndpoint(template.getEndpoint()); } template = templateDAO.save(template); String serialization; if (nifParameters.getOutformat().equals(RDFConstants.RDFSerialization.JSON)) { ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); serialization = ow.writeValueAsString(template); } else { // Should never fail to. serialization = rdfConversionService.serializeRDF(template.getRDF(), nifParameters.getOutformat()); } HttpHeaders responseHeaders = new HttpHeaders(); URI location = new URI("/e-link/templates/" + template.getId()); responseHeaders.setLocation(location); responseHeaders.set("Content-Type", nifParameters.getOutformat().contentType()); // String serialization = // rdfConversionService.serializeRDF(template.getRDF(), // nifParameters.getOutformat()); return new ResponseEntity<>(serialization, responseHeaders, HttpStatus.OK); } catch (AccessDeniedException ex) { logger.error(ex.getMessage(), ex); throw new eu.freme.broker.exception.AccessDeniedException(ex.getMessage()); } catch (BadRequestException ex) { logger.error(ex.getMessage(), ex); throw ex; } catch (URISyntaxException | org.json.JSONException ex) { logger.error(ex.getMessage(), ex); throw new BadRequestException(ex.getMessage()); } catch (InvalidTemplateEndpointException ex) { logger.error(ex.getMessage(), ex); throw new InvalidTemplateEndpointException(ex.getMessage()); } catch (Exception ex) { logger.error(ex.getMessage(), ex); throw new InternalServerErrorException(ex.getMessage()); } }
From source file:aiai.ai.station.LaunchpadRequester.java
/** * this scheduler is being run at the station side * * long fixedDelay()//from ww w .j a v a2 s . c om * 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:comsat.sample.ui.method.SampleMethodSecurityApplicationTests.java
@Test public void testDenied() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.set("username", "user"); form.set("password", "user"); getCsrf(form, headers);/* ww w. ja v a 2 s .c om*/ ResponseEntity<String> entity = new TestRestTemplate().exchange("http://localhost:" + this.port + "/login", HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(form, headers), String.class); assertEquals(HttpStatus.FOUND, entity.getStatusCode()); String cookie = entity.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); ResponseEntity<String> page = new TestRestTemplate().exchange(entity.getHeaders().getLocation(), HttpMethod.GET, new HttpEntity<Void>(headers), String.class); assertEquals(HttpStatus.FORBIDDEN, page.getStatusCode()); assertTrue("Wrong body (message doesn't match):\n" + entity.getBody(), page.getBody().contains("Access denied")); }
From source file:org.apigw.authserver.AuthorizationCodeProviderIntegrationtest.java
@Test public void testAuthorizationRequestRedirectsToLogin() throws Exception { log.debug("testAuthorizationRequestRedirectsToLogin"); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); String location = helper.getAuthorizeUrl(CLIENT_ID, REDIRECT_URL, SCOPE); ResponseEntity<Void> result = serverRunning.getForResponse(location, headers); assertEquals(HttpStatus.FOUND, result.getStatusCode()); location = result.getHeaders().getLocation().toString(); if (result.getHeaders().containsKey("Set-Cookie")) { String cookie = result.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); }// w ww .ja v a 2 s . c o m ResponseEntity<String> response = serverRunning.getForString(location, headers); // should be directed to the login screen... assertTrue(response.getBody().contains("/login.do")); assertTrue(response.getBody().contains("j_username")); assertTrue(response.getBody().contains("j_password")); }
From source file:net.paslavsky.springrest.HttpHeadersHelper.java
private void setContentDisposition(HttpHeaders headers, String headerName, Object headerValue) { String name;/*from w w w. j ava 2 s . c om*/ String filename = null; if (headerValue instanceof String) { name = (String) headerValue; } else if (headerValue instanceof String[]) { name = ((String[]) headerValue)[0]; filename = ((String[]) headerValue)[1]; } else { throw new SpringRestClientException( String.format("Can't cast %s to the java.lang.String[]", headerValue.getClass().getName())); } if (name.toLowerCase().startsWith("form-data;")) { headers.set(headerName, name); } else { headers.setContentDispositionFormData(name, filename); } }