@Override protected boolean authorize(Request request, Response response) { if (request.getMethod() == Method.OPTIONS) return true; if (request.getAttributes().get("account") != null) return true; String accessToken = request.getHeaders().getFirstValue(HttpHeaders.AUTHORIZATION); if (accessToken == null) return true; try { accessToken.replace("OAuth ", ""); AccountBean acc = mAccounts.getAccountFromToken(accessToken); if (acc != null) { request.getAttributes().put("account", acc); return true; } } catch (Exception e) { Main.LOGGER.log(Level.WARNING, "Error while handling OAuth authentification", e); return false; } return false; }
@Override public int verify(Request request, Response response) { if (request.getMethod() == Method.OPTIONS) return RESULT_VALID; if (request.getAttributes().get("account") != null) return RESULT_VALID; String accessToken = request.getHeaders().getFirstValue(HttpHeaders.AUTHORIZATION); if (accessToken == null) return RESULT_MISSING; try { accessToken.replace("OAuth ", ""); AccountBean acc = mAccounts.getAccountFromToken(accessToken); if (acc != null) { request.getAttributes().put("account", acc); return RESULT_VALID; } } catch (Exception e) { Main.LOGGER.log(Level.WARNING, "Error while handling OAuth authentification", e); return RESULT_INVALID; } return RESULT_INVALID; }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { UriInfo uriInfo = requestContext.getUriInfo(); UriBuilder hostUriBuilder = uriInfo.getRequestUriBuilder(); // get host from header forwarded host if set String forwardedHost = requestContext.getHeaderString(HttpHeaders.X_FORWARDED_HOST); LOG.debug("x-forwarded-host: {}", forwardedHost); URI builtRequestUri = hostUriBuilder.build(); String replacementUri = builtRequestUri.getHost() + builtRequestUri.getPath(); if (forwardedHost != null) { UriBuilder forwardedHostUriBuilder = UriBuilder.fromUri("http://" + forwardedHost.split(",")[0]); replacementUri = forwardedHostUriBuilder.build().getHost() + builtRequestUri.getPath(); } hostUriBuilder.replacePath(replacementUri); LOG.debug("Set new request path to {} (was {})", hostUriBuilder, uriInfo.getAbsolutePath()); requestContext.setRequestUri(hostUriBuilder.build()); }
public void handle(RoutingContext context) { Log.l("Stay Download " + context.request().remoteAddress()); if(AdminManager.isAdmin(context)) { int year = Integer.valueOf(context.request().getParam("year")); int month = Integer.valueOf(context.request().getParam("month")); int week = Integer.valueOf(context.request().getParam("week")); String date = StringFormatter.format("%4d-%02d-%02d", year, month, week).getValue(); String fileName = null; try { fileName = new String("잔류신청.xlsx".getBytes("UTF-8"), "ISO-8859-1"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } context.response() .putHeader(HttpHeaders.CONTENT_DISPOSITION, "filename=" + fileName) .sendFile(residualDownload.readExcel(date)); context.response().close(); }else{ context.response().setStatusCode(400); context.response().end("You are Not Admin"); context.response().close(); } }
@Override public void handle(RoutingContext ctx) { ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Cookie, Origin, X-Requested-With, Content-Type"); ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST, PUT, PATCH, GET, DELETE, OPTIONS, HEAD, CONNECT"); ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://dsm2015.cafe24.com/*"); ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://dsm2015.cafe24.com/"); ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://dsm2015.cafe24.com"); ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); if (secureManager.isBanned(ctx)) { ctx.response().setStatusCode(400); ctx.response().setStatusMessage("You are banned!"); ctx.response().putHeader("Content-Type", "text/html; charset=utf-8"); ctx.response().end("<h1>사이트에서 차단되었습니다.<br> 관리자에게 문의해 주세요 IP:"+ctx.request().remoteAddress().host()+"</h1>"); ctx.response().close(); return; } Log.l(" Method : " ,ctx.request().method()," Absolute URI : " , ctx.request().absoluteURI()," Params size : " , ctx.request().params().size()); ctx.next(); }
/** * 设置客户端缓存过期时间 的Header. */ public static void setExpiresHeader(HttpServletResponse response, long expiresSeconds) { // Http 1.0 header, set a fix expires date. response.setDateHeader(HttpHeaders.EXPIRES, System.currentTimeMillis() + expiresSeconds * 1000); // Http 1.1 header, set a time after now. response.setHeader(HttpHeaders.CACHE_CONTROL, "private, max-age=" + expiresSeconds); }
/** * 根据浏览器 If-None-Match Header, 计算Etag是否已无效. * * 如果Etag有效, checkIfNoneMatch返回false, 设置304 not modify status. * * @param etag 内容的ETag. */ public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response, String etag) { String headerValue = request.getHeader(HttpHeaders.IF_NONE_MATCH); if (headerValue != null) { boolean conditionSatisfied = false; if (!"*".equals(headerValue)) { StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ","); while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) { String currentToken = commaTokenizer.nextToken(); if (currentToken.trim().equals(etag)) { conditionSatisfied = true; } } } else { conditionSatisfied = true; } if (conditionSatisfied) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader(HttpHeaders.ETAG, etag); return false; } } return true; }
private static long getStreamLength(HttpURLConnection connection, Map<String, List<String>> headers) throws IOException { String cl = connection.getHeaderField(HttpHeaders.CONTENT_LENGTH); if (cl == null) { // Try to get the content length by parsing the content range // because HftpFileSystem does not return the content length // if the content is partial. if (connection.getResponseCode() == HttpStatus.SC_PARTIAL_CONTENT) { cl = connection.getHeaderField(HttpHeaders.CONTENT_RANGE); return getLengthFromRange(cl); } else { throw new IOException(HttpHeaders.CONTENT_LENGTH + " is missing: " + headers); } } return Long.parseLong(cl); }
@Override public Response intercept(Chain chain) throws IOException { Request req = chain.request(); try { for (String header : req.headers(HttpHeaders.COOKIE)) { for (Cookie cookie : decodeCookies(header, req.url().host())) { if (cookie.name().equalsIgnoreCase(xsrfCookieName)) { if (log.isDebugEnabled()) { log.debug(String.format("Setting XSRF token header: %s to request.", xsrfHeaderName)); } req = req.newBuilder().addHeader(xsrfHeaderName, cookie.value()).build(); } } } } catch (Exception ex) { log.warn("Error setting " + xsrfHeaderName + " header in request", ex); } return chain.proceed(req); }
@Test public void testAuthenticateWithUnknownIssuer() { Authenticator authenticator = createAuthenticator(Clock.SYSTEM, ISSUER, null); String authToken = TestUtils.generateAuthToken( Optional.<Collection<String>>of(AUDIENCES), Optional.of(EMAIL), Optional.of("https://unknown.issuer.com"), Optional.of(SUBJECT), RSA_JSON_WEB_KEY); when(httpRequest.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer " + authToken); try { authenticator.authenticate(httpRequest, authInfo, SERVICE_NAME); fail(); } catch (UncheckedExecutionException exception) { Throwable rootCause = ExceptionUtils.getRootCause(exception); assertTrue(rootCause instanceof UnauthenticatedException); assertTrue(rootCause.getMessage().contains("the issuer is unknown")); } }
@Test public void shouldReturnValidResponseGivenValidGetSecretMetadataRequest() throws Exception { // set up mock server mockWebServer.enqueue(new MockResponse() .setBody(FileUtil.readFile("getSecretMetadata.json")) .addHeader(HttpHeaders.ETAG, "2")); SecretRequest secretRequest = new SecretRequest(IDENTITY_ID, SECRET_ID); // make a test call GetSecretMetadataResponse response = createDeltaApiClient().getSecretMetadata(secretRequest); // assert the response assertEquals(METADATA, response.getMetadata()); // assert the request we made during the test call RecordedRequest request = mockWebServer.takeRequest(1, TimeUnit.SECONDS); assertEquals(IDENTITY_ID, getAuthIdentity(request.getHeader(AUTHORIZATION))); assertTrue(request.getPath().endsWith("/" + SECRET_ID + "/metadata")); }
@Before public void setup() throws IOException { MockWebServer mockWebServer = new MockWebServer(); mockWebServer.start(); JacksonConverterFactory converterFactory = JacksonConverterFactory.create(new ObjectMapper()); mockDeltaApi = new Retrofit.Builder() .baseUrl(mockWebServer.url(MOCK_HOST).toString()) .addConverterFactory(converterFactory) .build().create(MockDeltaApi.class); CreateIdentityRequest createIdentityRequest = new CreateIdentityRequest(SIGNING_PUBLIC_KEY, ENCRYPTION_PUBLIC_KEY, null, null); Call<CreateIdentityResponse> call = mockDeltaApi.register(REQUEST_DATE, "example.server", IDENTITY_ID, "sampleQueryParamValue", createIdentityRequest); request = call.request() .newBuilder() // fix as okhttp removes content-type header .addHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString()) .build(); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest)request; if ("http".equals(httpRequest.getHeader(HttpHeaders.X_FORWARDED_PROTO))) { StringBuilder location = new StringBuilder(); location.append("https://"); location.append(httpRequest.getServerName()); location.append(httpRequest.getRequestURI()); String queryString = httpRequest.getQueryString(); if (queryString != null) { location.append('?'); location.append(queryString); } HttpServletResponse httpResponse = (HttpServletResponse)response; httpResponse.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); httpResponse.setHeader(HttpHeaders.LOCATION, location.toString()); return; } chain.doFilter(request, response); }
@Test public void testAuditLoggingForPutWithBrokenAuthorization() throws InterruptedException, ExecutionException, TimeoutException { RequestContext requestContext = mock(RequestContext.class); Request request = Request.forUri("/", "PUT") .withHeader(HttpHeaders.AUTHORIZATION, "Bearer broken") .withPayload(ByteString.encodeUtf8("hello")); when(requestContext.request()).thenReturn(request); Response<Object> response = Middlewares.auditLogger().and(Middlewares.exceptionHandler()) .apply(mockInnerHandler(requestContext)) .invoke(requestContext) .toCompletableFuture().get(5, SECONDS); assertThat(response, hasStatus(withCode(Status.BAD_REQUEST))); }
@Test public void appSupportsCORS() { String origin = "http://originfortest.com"; Response response = register.target(address).path("/entries") .request() .header(HttpHeaders.ORIGIN, origin) .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "X-Requested-With") .options(); MultivaluedMap<String, Object> headers = response.getHeaders(); assertThat(headers.get(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN), equalTo(ImmutableList.of(origin))); assertThat(headers.get(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS), is(nullValue())); assertNotNull(headers.get(HttpHeaders.ACCESS_CONTROL_MAX_AGE)); assertThat(headers.get(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS), equalTo(ImmutableList.of("GET,HEAD"))); assertThat(headers.get(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS), equalTo(ImmutableList.of("X-Requested-With,Content-Type,Accept,Origin"))); }
public static String getRemoteServiceUrl(HttpServerRequest httpServerRequest) { try { URI absoluteRequestURI = new URI(httpServerRequest.absoluteURI()); MultiMap headers = httpServerRequest.headers(); String host = getFirstHeader(httpServerRequest, "X-Forwarded-Host"); String contextRoot = getFirstHeader(httpServerRequest, SfsHttpHeaders.X_CONTEXT_ROOT); if (host == null) host = getFirstHeader(httpServerRequest, HttpHeaders.HOST); if (host == null) host = absoluteRequestURI.getHost(); String proto = headers.get(HttpHeaders.X_FORWARDED_PROTO); if (proto == null) proto = absoluteRequestURI.getScheme(); String serviceUrl; if (contextRoot != null) { serviceUrl = String.format("%s://%s/%s", proto, host, contextRoot); } else { serviceUrl = String.format("%s://%s", proto, host); } return serviceUrl; } catch (URISyntaxException e) { throw new RuntimeException(e); } }
@GET public Response get(@HeaderParam(HttpHeaders.IF_NONE_MATCH) String ifNoneMatch, @HeaderParam(HttpHeaders.IF_MODIFIED_SINCE) Date ifModifiedSince) { // Check the ETags to see if the resource has changed... if (ifNoneMatch != null) { for (String eTag : ETAG_SPLITTER.split(ifNoneMatch)) { if ("*".equals(eTag) || ETAG.equals(EntityTag.valueOf(eTag))) { return NOT_MODIFIED; } } } // Check the last modification time if (ifModifiedSince != null && ifModifiedSince.after(LAST_MODIFIED)) { return NOT_MODIFIED; } return Response.ok().lastModified(LAST_MODIFIED).tag(ETAG).type(CONTENT_TYPE).entity(FAVICON).build(); }
/** @return the first {@code Content-Length} header, or {@code -1} if not found */ public long getContentLength() throws NumberFormatException { String contentLengthHeader = httpResponse.getHeaders().getFirstHeaderStringValue(HttpHeaders.CONTENT_LENGTH); if (contentLengthHeader == null) { return -1; } try { return Long.parseLong(contentLengthHeader); } catch (NumberFormatException ex) { return -1; } }
@Override public void handle(RoutingContext ctx) { ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Cookie, Origin, X-Requested-With, Content-Type"); ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST, PUT, PATCH, GET, DELETE, OPTIONS, HEAD, CONNECT"); ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://dsm2015.cafe24.com/*"); ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://dsm2015.cafe24.com/"); ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://dsm2015.cafe24.com"); ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); ctx.next(); }
@Test public void filter_PrefixPathWithXForwaredHeader_Always() throws Exception { // Arrange when(containerRequestContext.getHeaderString(HttpHeaders.X_FORWARDED_HOST)).thenReturn( DBEERPEDIA.NL_HOST); // Act hostPreMatchingRequestFilter.filter(containerRequestContext); // Assert verify(containerRequestContext).setRequestUri(UriBuilder.fromUri( "http://" + DBEERPEDIA.ORG_HOST + "/" + DBEERPEDIA.NL_HOST + "/beer").build()); }
@Test public void filter_PrefixPathWithXForwaredHeader_WithMultipleHosts() throws Exception { // Arrange when(containerRequestContext.getHeaderString(HttpHeaders.X_FORWARDED_HOST)).thenReturn( DBEERPEDIA.NL_HOST + ", " + DBEERPEDIA.ORG_HOST); // Act hostPreMatchingRequestFilter.filter(containerRequestContext); // Assert verify(containerRequestContext).setRequestUri(UriBuilder.fromUri( "http://" + DBEERPEDIA.ORG_HOST + "/" + DBEERPEDIA.NL_HOST + "/beer").build()); }
@Test public void filter_IgnorePort_WhenPortIsGiven() throws Exception { // Arrange when(containerRequestContext.getHeaderString(HttpHeaders.X_FORWARDED_HOST)).thenReturn( DBEERPEDIA.NL_HOST + ":8080"); // Act hostPreMatchingRequestFilter.filter(containerRequestContext); // Assert verify(containerRequestContext).setRequestUri(UriBuilder.fromUri( "http://" + DBEERPEDIA.ORG_HOST + "/" + DBEERPEDIA.NL_HOST + "/beer").build()); }
public void sendRequest(Channel channel, HttpRequest request) throws GeneralSecurityException { addAuthHeaders(request); request.headers().set(HttpHeaders.HOST, conn.getHost()); request.headers().set(HttpHeaders.ACCEPT, "*/*"); request.headers().set(HttpHeaders.USER_AGENT, "Cloudwall/1.0"); request.headers().set(HttpHeaders.CONNECTION, HttpHeaderValues.KEEP_ALIVE); channel.writeAndFlush(request); }
@Override public void handle(RoutingContext ctx) { ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Cookie, Origin, X-Requested-With, Content-Type"); ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST, PUT, PATCH, GET, DELETE, OPTIONS, HEAD, CONNECT"); ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://52.79.134.200/*"); ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://52.79.134.200/"); ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://52.79.134.200"); ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); ctx.next(); }
private static void addCommonResponseHeaders(final HttpServletResponse response) { if (!response.containsHeader(HttpHeaders.X_CONTENT_TYPE_OPTIONS)) { response.addHeader(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"); } }
/** * 设置禁止客户端缓存的Header. */ public static void setNoCacheHeader(HttpServletResponse response) { // Http 1.0 header response.setDateHeader(HttpHeaders.EXPIRES, 1L); response.addHeader(HttpHeaders.PRAGMA, "no-cache"); // Http 1.1 header response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0"); }
/** * 根据浏览器If-Modified-Since Header, 计算文件是否已被修改. * * 如果无修改, checkIfModify返回false ,设置304 not modify status. * * @param lastModified 内容的最后修改时间. */ public static boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response, long lastModified) { long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE); if ((ifModifiedSince != -1) && (lastModified < ifModifiedSince + 1000)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return false; } return true; }
/** * 设置让浏览器弹出下载对话框的Header. * * @param fileName 下载后的文件名. */ public static void setFileDownloadHeader(HttpServletResponse response, String fileName) { try { // 中文文件名支持 String encodedfileName = new String(fileName.getBytes(), "ISO8859-1"); response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\""); } catch (UnsupportedEncodingException e) { e.getMessage(); } }
@Override public void filter(AwsProxyResponse response) { corsConfiguration.getAllowOrigin() .ifPresent(o -> response.addHeaderIfAbsent(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, o)); corsConfiguration.getAllowCredentials() .ifPresent(c -> response.addHeaderIfAbsent(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, c.toString())); }
@Test public void testMRWebAppRedirection() throws Exception { String[] schemePrefix = { WebAppUtils.HTTP_PREFIX, WebAppUtils.HTTPS_PREFIX }; for (String scheme : schemePrefix) { MRApp app = new MRApp(2, 2, true, this.getClass().getName(), true) { @Override protected ClientService createClientService(AppContext context) { return new MRClientService(context); } }; Configuration conf = new Configuration(); conf.set(YarnConfiguration.PROXY_ADDRESS, "9.9.9.9"); conf.set(YarnConfiguration.YARN_HTTP_POLICY_KEY, scheme .equals(WebAppUtils.HTTPS_PREFIX) ? Policy.HTTPS_ONLY.name() : Policy.HTTP_ONLY.name()); webProxyBase = "/proxy/" + app.getAppID(); conf.set("hadoop.http.filter.initializers", TestAMFilterInitializer.class.getName()); Job job = app.submit(conf); String hostPort = NetUtils.getHostPortString(((MRClientService) app.getClientService()) .getWebApp().getListenerAddress()); URL httpUrl = new URL("http://" + hostPort + "/mapreduce"); HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection(); conn.setInstanceFollowRedirects(false); conn.connect(); String expectedURL = scheme + conf.get(YarnConfiguration.PROXY_ADDRESS) + ProxyUriUtils.getPath(app.getAppID(), "/mapreduce"); Assert.assertEquals(expectedURL, conn.getHeaderField(HttpHeaders.LOCATION)); Assert.assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, conn.getResponseCode()); app.waitForState(job, JobState.SUCCEEDED); app.verifyCompleted(); } }
private HttpURLConnection getMockConnection(String length) throws IOException { HttpURLConnection mockConnection = mock(HttpURLConnection.class); doReturn(new ByteArrayInputStream("asdf".getBytes())) .when(mockConnection).getInputStream(); doReturn(length).when(mockConnection) .getHeaderField(HttpHeaders.CONTENT_LENGTH); return mockConnection; }
public static Listener stream(String path, String method, List<Pair> queryParams, ApiClient client, io.kubernetes.client.util.WebSockets.SocketListener listener) throws ApiException, IOException { HashMap<String, String> headers = new HashMap<String, String>(); String allProtocols = String.format("%s,%s,%s,%s", V4_STREAM_PROTOCOL, V3_STREAM_PROTOCOL, V2_STREAM_PROTOCOL, V1_STREAM_PROTOCOL); headers.put(STREAM_PROTOCOL_HEADER, allProtocols); headers.put(HttpHeaders.CONNECTION, HttpHeaders.UPGRADE); headers.put(HttpHeaders.UPGRADE, SPDY_3_1); String[] localVarAuthNames = new String[] { "BearerToken" }; Request request = client.buildRequest(path, method, queryParams, new ArrayList<Pair>(), null, headers, new HashMap<String, Object>(), localVarAuthNames, null); return streamRequest(request, client, listener); }
/** * Tries to determine the RDF format of the given URL. If the format could not be determined, * the default value of {@link RDFFormat#TURTLE} will be returned. * @param url location of an RDF document. * @return the resolved format of the RDF document, or {@code turtle} if the resolving failed. * @throws IOException if an error occured during retrieval of the RDF document. */ private RDFFormat getRdfFormat(URL url) throws IOException { Optional<RDFFormat> format = Rio.getParserFormatForFileName(url.getPath()); if (!format.isPresent()) { URLConnection connection = url.openConnection(); connection.setRequestProperty(HttpHeaders.ACCEPT, CUSTOM_ACCEPT_HEADER); format = Rio.getParserFormatForMIMEType(connection.getContentType()); } return format.orElse(RDFFormat.TURTLE); }
@Test(groups = "fast") public void addTaxCode() throws IOException, ServletException, SQLException { // given byte[] data = "{\"tax_rate\":\"0.15\",\"valid_from_date\":\"2017-01-01T12:00:00Z\"}" .getBytes("UTF-8"); ByteArrayInputStream byis = new ByteArrayInputStream(data); ByteArrayOutputStream byos = givenDefaultServletCall("POST", "/taxCodes/NZ/memory-use/GST", byis, data.length, EasyTaxServlet.APPLICATION_JSON_UTF8); givenPermissions(TEST_USER, TEST_PASSWORD, TEST_PERMISSIONS); // when servlet.service(req, res); // then thenAuthenticatedAs(TEST_USER, TEST_PASSWORD); thenDefaultResponse(201, null); then(res).should().setHeader(HttpHeaders.LOCATION, "/plugins/killbill-easytax/taxCodes/NZ/memory-use/GST"); ArgumentCaptor<EasyTaxTaxCode> taxCodeCaptor = ArgumentCaptor .forClass(EasyTaxTaxCode.class); then(dao).should().saveTaxCode(taxCodeCaptor.capture()); assertEquals(byos.size(), 0, "Response body content"); EasyTaxTaxCode saved = taxCodeCaptor.getValue(); assertEquals(saved.getCreatedDate(), now); assertEquals(saved.getKbTenantId(), tenantId); assertEquals(saved.getTaxZone(), "NZ"); assertEquals(saved.getProductName(), "memory-use"); assertEquals(saved.getTaxCode(), "GST"); assertDateTimeEquals(saved.getValidFromDate(), new DateTime(2017, 1, 1, 12, 0, 0, DateTimeZone.UTC), "Valid from date"); assertNull(saved.getValidToDate(), "Valid to date"); }
@Test public void testPutSnapshotInvalidUser() { byte[] uploadedContent = {1, 2, 3}; assertConnectionTo(createUrl("/test-repository/org/perfectable/test/test-artifact/1.0.1-SNAPSHOT/test-artifact-1.0.1-20161001.101010-1.jar")) .withMethod("PUT") .withHeader(HttpHeaders.AUTHORIZATION, "Basic " + calculateBase64("missing-user:invalid-password")) .withContent(uploadedContent) .returnedStatus(HttpServletResponse.SC_FORBIDDEN) .hasContentText("User missing-user was not authorized"); assertNoFile("test-content/org/perfectable/test/test-artifact/1.0.1-SNAPSHOT/test-artifact-1.0.1-20161001.101010-1.jar"); }
@Override public boolean isHealthy(ServiceEndPoint endPoint) { URI adminUrl = Payload.valueOf(endPoint.getPayload()).getAdminUrl(); return _jerseyClient.resource(adminUrl).path("/healthcheck") .header(HttpHeaders.CONNECTION, "close") .head().getStatus() == 200; }
@Test public void testPutSnapshotValid() { byte[] uploadedContent = {1, 2, 3}; assertConnectionTo(createUrl("/test-repository/org/perfectable/test/test-artifact/1.0.1-SNAPSHOT/test-artifact-1.0.1-20161001.101010-1.jar")) .withMethod("PUT") .withHeader(HttpHeaders.AUTHORIZATION, "Basic " + calculateBase64("test-uploader:test-uploader-password")) .withContent(uploadedContent) .returnedStatus(HttpServletResponse.SC_OK); assertFile("test-content/org/perfectable/test/test-artifact/1.0.1-SNAPSHOT/test-artifact-1.0.1-20161001.101010-1.jar", uploadedContent); }
private Optional<SnapshotItem> fetchLatest(ContentSpecifier spec) throws IOException { AptFacet aptFacet = getRepository().facet(AptFacet.class); ProxyFacet proxyFacet = facet(ProxyFacet.class); HttpClientFacet httpClientFacet = facet(HttpClientFacet.class); HttpClient httpClient = httpClientFacet.getHttpClient(); CacheController cacheController = cacheControllerHolder.getMetadataCacheController(); CacheInfo cacheInfo = cacheController.current(); Content oldVersion = aptFacet.get(spec.path); URI fetchUri = proxyFacet.getRemoteUrl().resolve(spec.path); HttpGet getRequest = buildFetchRequest(oldVersion, fetchUri); HttpResponse response = httpClient.execute(getRequest); StatusLine status = response.getStatusLine(); if (status.getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); Content fetchedContent = new Content(new HttpEntityPayload(response, entity)); AttributesMap contentAttrs = fetchedContent.getAttributes(); contentAttrs.set(Content.CONTENT_LAST_MODIFIED, getDateHeader(response, HttpHeaders.LAST_MODIFIED)); contentAttrs.set(Content.CONTENT_ETAG, getQuotedStringHeader(response, HttpHeaders.ETAG)); contentAttrs.set(CacheInfo.class, cacheInfo); Content storedContent = getAptFacet().put(spec.path, fetchedContent); return Optional.of(new SnapshotItem(spec, storedContent)); } try { if (status.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) { checkState(oldVersion != null, "Received 304 without conditional GET (bad server?) from %s", fetchUri); doIndicateVerified(oldVersion, cacheInfo, spec.path); return Optional.of(new SnapshotItem(spec, oldVersion)); } throwProxyExceptionForStatus(response); } finally { HttpClientUtils.closeQuietly(response); } return Optional.empty(); }