List of usage examples for java.net HttpURLConnection getURL
public URL getURL()
From source file:com.openshift.internal.restclient.http.UrlConnectionHttpClient.java
protected String createErrorMessage(IOException ioe, HttpURLConnection connection) throws IOException { String errorMessage = IOUtils.toString(connection.getErrorStream()); if (!StringUtils.isEmpty(errorMessage)) { return errorMessage; }// ww w.ja v a2 s .co m StringBuilder builder = new StringBuilder("Connection to ").append(connection.getURL()); String reason = connection.getResponseMessage(); if (!StringUtils.isEmpty(reason)) { builder.append(": ").append(reason); } return builder.toString(); }
From source file:com.dao.ShopThread.java
private String getPayKey(HttpURLConnection conn, String type) throws Exception { LogUtil.debugPrintf(""); String keyurl = conn.getURL().toString(); String postParams = getKeyDynamicParams(keyurl, type); HttpURLConnection loginConn = getHttpPostConn(keyurl); loginConn.setRequestProperty("Accept-Encoding", "deflate");// ?? loginConn.setRequestProperty("Referer", keyurl); loginConn.setRequestProperty("Host", "danbao.5173.com"); loginConn.setRequestProperty("Pragma", "no-cache"); loginConn.setRequestProperty("Content-Length", Integer.toString(postParams.length())); LogUtil.debugPrintf("?keyHEADER===" + loginConn.getRequestProperties()); LogUtil.debugPrintf("?keypostParams===" + postParams); DataOutputStream wr = new DataOutputStream(loginConn.getOutputStream()); wr.writeBytes(postParams);/*from w w w . java 2 s .co m*/ wr.flush(); wr.close(); BufferedReader in = new BufferedReader(new InputStreamReader(loginConn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(2000); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); String payurl = response.toString(); LogUtil.debugPrintf("keyHtml:" + payurl); payurl = payurl.substring(payurl.indexOf("action") + "action".length(), payurl.indexOf("></form>")); payurl = payurl.substring(payurl.indexOf("\"") + 1, payurl.lastIndexOf("\"")); Map<String, List<String>> header = loginConn.getHeaderFields(); LogUtil.debugPrintf("?key?HEADER===" + header); List<String> cookie = header.get("Set-Cookie"); if (cookie == null || cookie.size() == 0) { LogUtil.debugPrintf("?keycookie----------->"); } else { LogUtil.debugPrintf("?keycookie----------->"); LogUtil.debugPrintf("cookie====" + cookie); setCookies(cookie); } LogUtil.debugPrintf("?key?----------->"); return payurl; }
From source file:winterwell.jtwitter.URLConnectionHttpClient.java
/** * Throw an exception if the connection failed * /*from ww w . j a v a2 s . c o m*/ * @param connection */ final void processError(HttpURLConnection connection) { try { int code = connection.getResponseCode(); if (code == 200) return; URL url = connection.getURL(); // any explanation? String error = processError2_reason(connection); // which error? if (code == 401) { if (error.contains("Basic authentication is not supported")) throw new TwitterException.UpdateToOAuth(); throw new TwitterException.E401( error + "\n" + url + " (" + (name == null ? "anonymous" : name) + ")"); } if (code == 403) { // separate out the 403 cases processError2_403(url, error); } if (code == 404) { // user deleted? if (error != null && error.contains("deleted")) // Note: This is a 403 exception throw new TwitterException.SuspendedUser(error + "\n" + url); throw new TwitterException.E404(error + "\n" + url); } if (code == 406) // Hm: It might be nice to have info on post variables here throw new TwitterException.E406(error + "\n" + url); if (code == 413) throw new TwitterException.E413(error + "\n" + url); if (code == 416) throw new TwitterException.E416(error + "\n" + url); if (code == 420) throw new TwitterException.TooManyLogins(error + "\n" + url); if (code >= 500 && code < 600) throw new TwitterException.E50X(error + "\n" + url); // Over the rate limit? processError2_rateLimit(connection, code, error); // redirect?? if (code > 299 && code < 400) { String locn = connection.getHeaderField("Location"); throw new TwitterException(code + " " + error + " " + url + " -> " + locn); } // just report it as a vanilla exception throw new TwitterException(code + " " + error + " " + url); } catch (SocketTimeoutException e) { URL url = connection.getURL(); throw new TwitterException.Timeout(timeout + "milli-secs for " + url); } catch (ConnectException e) { // probably also a time out URL url = connection.getURL(); throw new TwitterException.Timeout(url.toString()); } catch (SocketException e) { // treat as a server error - because it probably is // (yes, it could also be an error at your end) throw new TwitterException.E50X(e.toString()); } catch (IOException e) { throw new TwitterException(e); } }
From source file:com.eucalyptus.tokens.oidc.OidcDiscoveryCache.java
protected OidcResource resolve(final HttpURLConnection conn) throws IOException { SslSetup.configureHttpsUrlConnection(conn); try (final InputStream istr = conn.getInputStream()) { final int statusCode = conn.getResponseCode(); if (statusCode == 304) { return new OidcResource(statusCode); } else {// ww w . ja v a 2s.c o m Certificate[] certs = new Certificate[0]; if (conn instanceof HttpsURLConnection) { certs = ((HttpsURLConnection) conn).getServerCertificates(); } final long contentLength = conn.getContentLengthLong(); if (contentLength > MAX_LENGTH) { throw new IOException(conn.getURL() + " content exceeds maximum size, " + MAX_LENGTH); } final byte[] content = ByteStreams.toByteArray(new BoundedInputStream(istr, MAX_LENGTH + 1)); if (content.length > MAX_LENGTH) { throw new IOException(conn.getURL() + " content exceeds maximum size, " + MAX_LENGTH); } return new OidcResource(statusCode, conn.getHeaderField(HttpHeaders.LAST_MODIFIED), conn.getHeaderField(HttpHeaders.ETAG), certs, content); } } }
From source file:eu.eubrazilcc.lvl.oauth2.AuthTest.java
@Test public void test() { System.out.println("AuthTest.test()"); try {//from w w w. j ava2 s . co m final String redirectURI = "https://localhost:8443/redirect"; final String state = generateFastUrlSafeSecret(); final String permissions = allPermissions(); final ResourceOwner resourceOwner = ResourceOwner.builder() .user(User.builder().userid("test_username").password("test_password") .email("username@example.com").firstname("Firstname").lastname("Lastname").role("user") .permissions(asPermissionList(permissions)).build()) .build(); RESOURCE_OWNER_DAO.insert(resourceOwner); // test client registration URI uri = UriBuilder.fromUri(BASE_URI).path(OAuth2Registration.class).build(); System.out.println(" >> Client registration: " + uri.toString()); OAuthClientRequest request = OAuthClientRegistrationRequest .location(uri.toString(), OAuthRegistration.Type.PUSH).setName("Sample Application") .setUrl("http://www.example.com").setDescription("Description of a Sample App") .setIcon("http://www.example.com/app.ico").setRedirectURL(redirectURI).buildJSONMessage(); OAuthRegistrationClient oauthclient = new OAuthRegistrationClient(new URLConnectionClient()); OAuthClientRegistrationResponse response = oauthclient.clientInfo(request); assertThat("Registration response is not null", response, notNullValue()); assertThat("Registration client Id is valid", StringUtils.isNotBlank(response.getClientId())); assertThat("Registration client secret is valid", StringUtils.isNotBlank(response.getClientSecret())); assertThat("Registration expiration is valid", response.getExpiresIn(), notNullValue()); assertThat("Registration issued at is valid", StringUtils.isNotBlank(response.getIssuedAt())); final String clientId = response.getClientId(); final String clientSecret = response.getClientSecret(); /* uncomment the following lines for additional output */ System.out.println(" >> Client Id: " + response.getClientId()); System.out.println(" >> Client secret: " + response.getClientSecret()); System.out.println(" >> Expires in: " + response.getExpiresIn() + " seconds"); System.out.println(" >> Issued at: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(new Date(Long.parseLong(response.getIssuedAt()) * 1000l))); // test client authorization (end user) uri = UriBuilder.fromUri(BASE_URI).path(OAuth2AuthzServer.class).build(); System.out.println(" >> Client (end user) authorization: " + uri.toString()); request = OAuthClientRequest.authorizationLocation(uri.toString()).setClientId(clientId) .setRedirectURI(redirectURI).setResponseType(ResponseType.CODE.toString()).setState(state) .buildQueryMessage(); HttpURLConnection conn = doRequest(request); String queryString = conn.getURL().toURI().getQuery(); Map<String, Object> map = OAuthUtils.decodeForm(queryString); assertThat("End user authorization code is not null", map.get(OAuth.OAUTH_CODE), notNullValue()); assertThat("End user authorization state coincides with original", (String) map.get(OAuth.OAUTH_STATE), equalTo(state)); /* uncomment the following lines for additional output */ for (final Map.Entry<String, Object> entry : map.entrySet()) { System.out.println(" >> " + entry.getKey() + " -> " + entry.getValue()); } // test client authorization (token) uri = UriBuilder.fromUri(BASE_URI).path(OAuth2AuthzServer.class).build(); System.out.println(" >> Client (token) authorization: " + uri.toString()); request = OAuthClientRequest.authorizationLocation(uri.toString()).setClientId(clientId) .setRedirectURI(redirectURI).setResponseType(ResponseType.TOKEN.toString()).setState(state) .buildQueryMessage(); conn = doRequest(request); String fragment = conn.getURL().toURI().getFragment(); map = OAuthUtils.decodeForm(fragment); assertThat("Token authorization expiration is not null", map.get(OAuth.OAUTH_EXPIRES_IN), notNullValue()); assertThat("Token authorization token is not null", map.get(OAuth.OAUTH_ACCESS_TOKEN), notNullValue()); /* uncomment the following lines for additional output */ for (final Map.Entry<String, Object> entry : map.entrySet()) { System.out.println(" >> " + entry.getKey() + " -> " + entry.getValue()); } assertThat("Token authorization state coincides with original", (String) map.get(OAuth.OAUTH_STATE), equalTo(state)); // test access token (user & password) uri = UriBuilder.fromUri(BASE_URI).path(OAuth2Token.class).build(); System.out.println(" >> Access token (user & password): " + uri.toString()); request = OAuthClientRequest.tokenLocation(uri.toString()).setGrantType(GrantType.PASSWORD) .setClientId(clientId).setClientSecret(clientSecret) .setUsername(resourceOwner.getUser().getUserid()) .setPassword(resourceOwner.getUser().getPassword()).buildBodyMessage(); OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); OAuthJSONAccessTokenResponse response2 = oAuthClient.accessToken(request); assertThat("Access token is valid", response2.getAccessToken(), notNullValue()); assertThat("Access token expiration is not null", response2.getExpiresIn(), notNullValue()); assertThat("Access token permission is not null", response2.getScope(), notNullValue()); String accessToken = response2.getAccessToken(); /* uncomment the following lines for additional output */ System.out.println(" >> Access token: " + response2.getAccessToken()); System.out.println(" >> Expires in: " + response2.getExpiresIn() + " seconds"); System.out.println(" >> Scope: " + response2.getScope()); // test access token (email & password), this test uses an additional parameter in the request uri = UriBuilder.fromUri(BASE_URI).path(OAuth2Token.class).build(); System.out.println(" >> Access token (email & password): " + uri.toString()); request = OAuthClientRequest.tokenLocation(uri.toString()).setGrantType(GrantType.PASSWORD) .setClientId(clientId).setClientSecret(clientSecret) .setUsername(resourceOwner.getUser().getEmail()) .setPassword(resourceOwner.getUser().getPassword()).setParameter(OAuth2Token.USE_EMAIL, "true") // additional parameter .buildBodyMessage(); oAuthClient = new OAuthClient(new URLConnectionClient()); response2 = oAuthClient.accessToken(request); assertThat("Access token is valid (using email address)", response2.getAccessToken(), notNullValue()); assertThat("Access token expiration is not null (using email address)", response2.getExpiresIn(), notNullValue()); assertThat("Access token permission is not null (using email address)", response2.getScope(), notNullValue()); accessToken = response2.getAccessToken(); /* uncomment the following lines for additional output */ System.out.println(" >> Access token (using email address): " + response2.getAccessToken()); System.out .println(" >> Expires in (using email address): " + response2.getExpiresIn() + " seconds"); System.out.println(" >> Scope (using email address): " + response2.getScope()); // test token revocation request = OAuthClientRequest.tokenLocation(uri.toString()).setGrantType(GrantType.PASSWORD) .setClientId(clientId).setClientSecret(clientSecret) .setUsername(resourceOwner.getUser().getUserid()) .setPassword(resourceOwner.getUser().getPassword()).buildBodyMessage(); oAuthClient = new OAuthClient(new URLConnectionClient()); response2 = oAuthClient.accessToken(request); final String accessToken2 = response2.getAccessToken(); Path path = OAuth2TokenRevocation.class.getAnnotation(Path.class); System.out.println(" >> Token revocation: " + target.path(path.value()).getUri().toString()); Form form = new Form(); form.param("token", accessToken2); form.param("client_id", clientId); form.param("client_secret", clientSecret); Response response3 = target.path(path.value()).request() .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken2)) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE)); assertThat("Revoke token response is not null", response3, notNullValue()); assertThat("Revoke token response is OK", response3.getStatus(), equalTo(OK.getStatusCode())); assertThat("Revoke token response is not empty", response3.getEntity(), notNullValue()); String payload = response3.readEntity(String.class); assertThat("Revoke token response entity is not null", payload, notNullValue()); assertThat("Revoke token response entity is empty", isBlank(payload)); /* uncomment for additional output */ System.out.println(" >> Revoke token response body (JSON), empty is OK: " + payload); System.out.println(" >> Revoke token response JAX-RS object: " + response3); System.out.println(" >> Revoke token HTTP headers: " + response3.getStringHeaders()); // test identity provider (IdP) create new user path = IdentityProvider.class.getAnnotation(Path.class); final User user = User.builder().userid("username2").password("password2") .email("username2@example.com").firstname("Firstname2").lastname("Lastname2").role("user") .permissions(asPermissionList(userPermissions(toResourceOwnerId("username2")))) .industry("Research").positions(newArrayList("positions")).build(); System.out.println(" >> IdP resource server: " + target.path(path.value()).getUri().toString()); response3 = target.path(path.value()).request() .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)) .post(Entity.entity(user, MediaType.APPLICATION_JSON_TYPE)); assertThat("Create new user response is not null", response3, notNullValue()); assertThat("Create new user response is CREATED", response3.getStatus(), equalTo(CREATED.getStatusCode())); assertThat("Create new user response is not empty", response3.getEntity(), notNullValue()); payload = response3.readEntity(String.class); assertThat("Create new user response entity is not null", payload, notNullValue()); assertThat("Create new user response entity is empty", isBlank(payload)); /* uncomment for additional output */ System.out.println(" >> Create new user response body (JSON), empty is OK: " + payload); System.out.println(" >> Create new user response JAX-RS object: " + response3); System.out.println(" >> Create new user HTTP headers: " + response3.getStringHeaders()); // test identity provider (IdP) get users (JSON encoded) response3 = target.path(path.value()).request(MediaType.APPLICATION_JSON) .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).get(); assertThat("Get users response is not null", response3, notNullValue()); assertThat("Get users response is OK", response3.getStatus(), equalTo(OK.getStatusCode())); assertThat("Get users response is not empty", response3.getEntity(), notNullValue()); payload = response3.readEntity(String.class); assertThat("Get users response entity is not null", payload, notNullValue()); assertThat("Get users response entity is not empty", isNotBlank(payload)); /* uncomment for additional output */ System.out.println(" >> Get users response body (JSON): " + payload); System.out.println(" >> Get users response JAX-RS object: " + response3); System.out.println(" >> Get users HTTP headers: " + response3.getStringHeaders()); // test identity provider (IdP) get users (Java object) final Users users = target.path(path.value()).request(MediaType.APPLICATION_JSON) .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).get(Users.class); assertThat("Get users result is not null", users, notNullValue()); assertThat("Get users list is not null", users.getElements(), notNullValue()); assertThat("Get users list is not empty", !users.getElements().isEmpty()); assertThat("Get users items count coincide with list size", users.getElements().size(), equalTo(users.getTotalCount())); /* uncomment for additional output */ System.out.println(" >> Get users result: " + users.toString()); // test identity provider (IdP) get user by username User user2 = target.path(path.value()).path(toResourceOwnerId(user.getUserid())) .queryParam("plain", true).request(MediaType.APPLICATION_JSON) .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).get(User.class); assertThat("Get user by username result is not null", user2, notNullValue()); assertThat("Get user by username coincides with expected", user2.equalsToUnprotectedIgnoringVolatile(user), equalTo(true)); /* uncomment for additional output */ System.out.println(" >> Get user by username result: " + user2.toString()); // test identity provider (IdP) get user by email address user2 = target.path(path.value()).path(user.getEmail()).queryParam("use_email", true) .queryParam("plain", true).request(MediaType.APPLICATION_JSON) .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).get(User.class); assertThat("Get user by email address result is not null", user2, notNullValue()); assertThat("Get user by email address coincides with expected", user2.equalsToUnprotectedIgnoringVolatile(user), equalTo(true)); /* uncomment for additional output */ System.out.println(" >> Get user by email address result: " + user2.toString()); // test identity provider (IdP) update user user.setPassword("updated_password2"); response3 = target.path(path.value()).path(toResourceOwnerId(user.getUserid())).request() .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)) .put(Entity.entity(user, MediaType.APPLICATION_JSON_TYPE)); assertThat("Update user response is not null", response3, notNullValue()); assertThat("Update user response is OK", response3.getStatus(), equalTo(NO_CONTENT.getStatusCode())); assertThat("Update user response is not empty", response3.getEntity(), notNullValue()); payload = response3.readEntity(String.class); assertThat("Update user response entity is not null", payload, notNullValue()); assertThat("Update user response entity is empty", isBlank(payload)); /* uncomment for additional output */ System.out.println(" >> Update user response body (JSON), empty is OK: " + payload); System.out.println(" >> Update user response JAX-RS object: " + response3); System.out.println(" >> Update user HTTP headers: " + response3.getStringHeaders()); // test identity provider (IdP) get user by username after update user2 = target.path(path.value()).path(toResourceOwnerId(user.getUserid())).queryParam("plain", true) .request(MediaType.APPLICATION_JSON) .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).get(User.class); assertThat("Get user by username after update result is not null", user2, notNullValue()); assertThat("Get user by username after update coincides with expected", user2.equalsIgnoringVolatile(user)); /* uncomment for additional output */ System.out.println(" >> Get user by username after update result: " + user2.toString()); // test identity provider (IdP) get user by username with revoked token try { target.path(path.value()).path(toResourceOwnerId(user.getUserid())) .request(MediaType.APPLICATION_JSON) .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken2)).get(User.class); fail("Should have thrown an NotAuthorizedException because access token is revoked"); } catch (NotAuthorizedException e) { assertThat(e.getMessage(), containsString("HTTP 401 Unauthorized")); } // test identity provider (IdP) delete user response3 = target.path(path.value()).path(toResourceOwnerId(user.getUserid())).request() .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).delete(); assertThat("Delete user response is not null", response3, notNullValue()); assertThat("Delete user response is OK", response3.getStatus(), equalTo(NO_CONTENT.getStatusCode())); assertThat("Delete user response is not empty", response3.getEntity(), notNullValue()); payload = response3.readEntity(String.class); assertThat("Delete user response entity is not null", payload, notNullValue()); assertThat("Delete user response entity is empty", isBlank(payload)); /* uncomment for additional output */ System.out.println(" >> Delete user response body (JSON), empty is OK: " + payload); System.out.println(" >> Delete user response JAX-RS object: " + response3); System.out.println(" >> Delete user HTTP headers: " + response3.getStringHeaders()); // test user registration path = UserRegistration.class.getAnnotation(Path.class); System.out.println( " >> User registration resource server: " + target.path(path.value()).getUri().toString()); response3 = target.path(path.value()).queryParam("skip_activation", true).request() .post(Entity.entity(user, MediaType.APPLICATION_JSON_TYPE)); assertThat("Create pending user response is not null", response3, notNullValue()); assertThat("Create pending user response is CREATED", response3.getStatus(), equalTo(CREATED.getStatusCode())); assertThat("Create pending user response is not empty", response3.getEntity(), notNullValue()); payload = response3.readEntity(String.class); assertThat("Create pending user response entity is not null", payload, notNullValue()); assertThat("Create pending user response entity is empty", isBlank(payload)); /* uncomment for additional output */ System.out.println(" >> Create pending user response body (JSON), empty is OK: " + payload); System.out.println(" >> Create pending user response JAX-RS object: " + response3); System.out.println(" >> Create pending user HTTP headers: " + response3.getStringHeaders()); // test user registration new user activation final PendingUser pendingUser = PENDING_USER_DAO.findByEmail(user.getEmail()); final PendingUser pendingUser2 = PendingUser.builder() .user(User.builder().email(user.getEmail()).build()) .activationCode(pendingUser.getActivationCode()).build(); response3 = target.path(path.value()).path(user.getEmail()).request() .put(Entity.entity(pendingUser2, MediaType.APPLICATION_JSON_TYPE)); assertThat("New user activation response is not null", response3, notNullValue()); assertThat("New user activation response is OK", response3.getStatus(), equalTo(NO_CONTENT.getStatusCode())); assertThat("New user activation response is not empty", response3.getEntity(), notNullValue()); payload = response3.readEntity(String.class); assertThat("New user activation response entity is not null", payload, notNullValue()); assertThat("New user activation response entity is empty", isBlank(payload)); /* uncomment for additional output */ System.out.println(" >> New user activation response body (JSON), empty is OK: " + payload); System.out.println(" >> New user activation response JAX-RS object: " + response3); System.out.println(" >> New user activation HTTP headers: " + response3.getStringHeaders()); // test identity provider (IdP) get user by username after activation path = IdentityProvider.class.getAnnotation(Path.class); System.out.println(" >> IdP resource server: " + target.path(path.value()).getUri().toString()); user2 = target.path(path.value()).path(toResourceOwnerId(user.getUserid())).queryParam("plain", true) .request(MediaType.APPLICATION_JSON) .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).get(User.class); assertThat("Get user by username after validation result is not null", user2, notNullValue()); assertThat("Get user by username after validation permissions are not null", user2.getPermissions(), notNullValue()); assertThat("Get user by username after validation permissions are not empty", !user2.getPermissions().isEmpty()); assertThat("Get user by username after validation coincides with expected", user2.equalsToUnprotectedIgnoringVolatile(user), equalTo(true)); /* uncomment for additional output */ System.out.println(" >> Get user by username after validation result: " + user2.toString()); // test check user availability with form field: username, expected response: user unavailable path = UserRegistration.class.getAnnotation(Path.class); final Path innerPath = UserRegistration.class .getMethod("checkUserAvailability", new Class<?>[] { MultivaluedMap.class }) .getAnnotation(Path.class); System.out.println(" >> Check user availability: " + target.path(path.value()).path(innerPath.value()).getUri().toString()); form = new Form(); form.param("type", "username"); form.param("username", user.getUserid()); response3 = target.path(path.value()).path(innerPath.value()).request(MediaType.APPLICATION_JSON) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED)); assertThat("Check user availability response is not null", response3, notNullValue()); assertThat("Check user availability response is OK", response3.getStatus(), equalTo(OK.getStatusCode())); assertThat("Check user availability response is not empty", response3.getEntity(), notNullValue()); payload = response3.readEntity(String.class); assertThat("Check user availability response entity is not null", payload, notNullValue()); assertThat("Check user availability response entity is not empty", !isBlank(payload)); assertThat("Check user availability coincides with expected", !readValid(payload)); /* uncomment for additional output */ System.out.println(" >> Check user availability response body (JSON): " + payload); System.out.println(" >> Check user availability response JAX-RS object: " + response3); // test check user availability with form field: email, expected response: user available (using plain REST, no Jersey client) uri = target.path(path.value()).path(innerPath.value()).getUri(); System.out.println(" >> Check user availability (plain): " + uri.toString()); final String response4 = Request.Post(uri).addHeader("Accept", "text/javascript") // also supports: application/json .bodyForm(form().add("email", "not_existing_email@example.org").add("type", "email").build()) .execute().returnContent().asString(); assertThat("Check user availability (plain) is not null", response4, notNullValue()); assertThat("Check user availability (plain) is not empty", isNotBlank(response4)); /* uncomment for additional output */ System.out.println("Check user availability (plain): " + response4); final boolean valid = readValid(response4); assertThat("Check user availability (plain) concides with expected", valid, equalTo(true)); /* uncomment for additional output */ System.out.println("Check user availability (plain) returns: " + valid); } catch (Exception e) { e.printStackTrace(System.err); fail("AuthTest.test() failed: " + e.getMessage()); } finally { System.out.println("AuthTest.test() has finished"); } }
From source file:io.mindmaps.engine.loader.DistributedLoader.java
private String executePost(HttpURLConnection connection, String body) { try {//from w w w .ja v a 2 s. co m // create post connection.setRequestMethod(REST.HttpConn.POST_METHOD); connection.addRequestProperty(REST.HttpConn.CONTENT_TYPE, REST.HttpConn.APPLICATION_POST_TYPE); // add body and execute connection.setRequestProperty(REST.HttpConn.CONTENT_LENGTH, Integer.toString(body.length())); connection.getOutputStream().write(body.getBytes(REST.HttpConn.UTF8)); // get response return connection.getResponseMessage(); } catch (HTTPException e) { LOG.error(ErrorMessage.ERROR_IN_DISTRIBUTED_TRANSACTION.getMessage(connection.getURL().toString(), e.getStatusCode(), getResponseMessage(connection), body)); } catch (IOException e) { LOG.error(ErrorMessage.ERROR_COMMUNICATING_TO_HOST.getMessage(connection.getURL().toString())); } return null; }
From source file:org.apache.hadoop.hdfs.TestHftpFileSystem.java
private void testDataNodeRedirect(Path path) throws IOException { // Create the file if (hdfs.exists(path)) { hdfs.delete(path, true);// w w w . j a v a 2 s . c o m } FSDataOutputStream out = hdfs.create(path, (short) 1); out.writeBytes("0123456789"); out.close(); // Get the path's block location so we can determine // if we were redirected to the right DN. BlockLocation[] locations = hdfs.getFileBlockLocations(path, 0, 10); String xferAddr = locations[0].getNames()[0]; // Connect to the NN to get redirected URL u = hftpFs.getNamenodeURL("/data" + ServletUtil.encodePath(path.toUri().getPath()), "ugi=userx,groupy"); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); HttpURLConnection.setFollowRedirects(true); conn.connect(); conn.getInputStream(); boolean checked = false; // Find the datanode that has the block according to locations // and check that the URL was redirected to this DN's info port for (DataNode node : cluster.getDataNodes()) { DatanodeRegistration dnR = DataNodeTestUtils.getDNRegistrationForBP(node, blockPoolId); if (dnR.getXferAddr().equals(xferAddr)) { checked = true; assertEquals(dnR.getInfoPort(), conn.getURL().getPort()); } } assertTrue("The test never checked that location of " + "the block and hftp desitnation are the same", checked); }
From source file:io.mindmaps.loader.DistributedLoader.java
private String executePost(HttpURLConnection connection, String body) { try {/*from www. j a v a 2s . c o m*/ // create post connection.setRequestMethod(RESTUtil.HttpConn.POST_METHOD); connection.addRequestProperty(RESTUtil.HttpConn.CONTENT_TYPE, RESTUtil.HttpConn.APPLICATION_POST_TYPE); // add body and execute connection.setRequestProperty(RESTUtil.HttpConn.CONTENT_LENGTH, Integer.toString(body.length())); connection.getOutputStream().write(body.getBytes(RESTUtil.HttpConn.UTF8)); // get response return connection.getResponseMessage(); } catch (HTTPException e) { LOG.error(ErrorMessage.ERROR_IN_DISTRIBUTED_TRANSACTION.getMessage(connection.getURL().toString(), e.getStatusCode(), getResponseMessage(connection), body)); } catch (IOException e) { LOG.error(ErrorMessage.ERROR_COMMUNICATING_TO_HOST.getMessage(connection.getURL().toString())); } return null; }
From source file:mobac.mapsources.loader.MapPackManager.java
public String downloadMD5SumList() throws IOException, UpdateFailedException { String md5eTag = Settings.getInstance().mapSourcesUpdate.etag; log.debug("Last md5 eTag: " + md5eTag); String updateUrl = System.getProperty("mobac.updateurl"); if (updateUrl == null) throw new RuntimeException("Update url not present"); byte[] data = null; // Proxy p = new Proxy(Type.HTTP, InetSocketAddress.createUnresolved("localhost", 8888)); HttpURLConnection conn = (HttpURLConnection) new URL(updateUrl).openConnection(); conn.setInstanceFollowRedirects(false); if (md5eTag != null) conn.addRequestProperty("If-None-Match", md5eTag); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) { log.debug("No newer md5 file available"); return null; }//from www. jav a 2s. c o m if (responseCode != HttpURLConnection.HTTP_OK) throw new UpdateFailedException( "Invalid HTTP response: " + responseCode + " for update url " + conn.getURL()); // Case HTTP_OK InputStream in = conn.getInputStream(); data = Utilities.getInputBytes(in); in.close(); Settings.getInstance().mapSourcesUpdate.etag = conn.getHeaderField("ETag"); log.debug("New md5 file retrieved"); String md5sumList = new String(data); return md5sumList; }
From source file:osmcd.mapsources.loader.MapPackManager.java
public String downloadMD5SumList() throws IOException, UpdateFailedException { String md5eTag = Settings.getInstance().mapSourcesUpdate.etag; log.debug("Last md5 eTag: " + md5eTag); String updateUrl = System.getProperty("osmcd.updateurl"); if (updateUrl == null) throw new RuntimeException("Update url not present"); byte[] data = null; // Proxy p = new Proxy(Type.HTTP, InetSocketAddress.createUnresolved("localhost", 8888)); HttpURLConnection conn = (HttpURLConnection) new URL(updateUrl).openConnection(); conn.setInstanceFollowRedirects(false); if (md5eTag != null) conn.addRequestProperty("If-None-Match", md5eTag); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) { log.debug("No newer md5 file available"); return null; }/*w w w.ja v a 2 s . c om*/ if (responseCode != HttpURLConnection.HTTP_OK) throw new UpdateFailedException( "Invalid HTTP response: " + responseCode + " for update url " + conn.getURL()); // Case HTTP_OK InputStream in = conn.getInputStream(); data = Utilities.getInputBytes(in); in.close(); Settings.getInstance().mapSourcesUpdate.etag = conn.getHeaderField("ETag"); log.debug("New md5 file retrieved"); String md5sumList = new String(data); return md5sumList; }