/** * Shortens a URL with bit.ly. * * @param longURL the URL to shorten. * @return the shortened URL. * @throws IllegalArgumentException if the long URI was invalid. * @throws HTTPException if the bit.ly API returns a response code unlike 200 'OK'. * @throws RuntimeException if the http request threw an unknown error. */ public static String shorten(String longURL) { HttpRequest request = new HttpRequest(API_URL); request.addParameter("access_token", Info.BITLY_TOKEN); request.addParameter("longUrl", longURL); request.addParameter("format", "json"); RequestResponse result; try { result = request.sendGETRequest(); } catch (Exception e) { // catch 'anonymous' exceptions throw new RuntimeException("An unknown exception occurred while fetching a bit.ly http request", e); } JSONObject response = new JSONObject(result.getResponse()); // check if uri was valid if (response.getString("status_txt").equals("INVALID_URI")) throw new IllegalArgumentException("'" + longURL + "' is not a valid URL."); // ensure 'OK' status response else if (response.getInt("status_code") == 400) throw new HTTPException(response.getInt("status_code")); // return shortened url return response.getJSONObject("data").getString("url"); }
private void doRoleCommand(String serviceName, String roleName, RoleCommand roleCommand) { URI uri = UriBuilder.fromUri(serverHostname) .path("api") .path(API_VERSION) .path("clusters") .path(clusterName) .path("services") .path(serviceName) .path("roleCommands") .path(roleCommand.toString()) .build(); String body = "{ \"items\": [ \"" + roleName + "\" ] }"; LOG.info("Executing POST against " + uri + " with body " + body + "..."); ClientResponse response = client.resource(uri) .type(MediaType.APPLICATION_JSON) .post(ClientResponse.class, body); int statusCode = response.getStatus(); if (statusCode != Response.Status.OK.getStatusCode()) { throw new HTTPException(statusCode); } }
public void sendPost(URL url, Path content) throws IOException { HttpURLConnection con = null; try { con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "UTF-8"); con.setDoOutput(true); try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(con.getOutputStream())) { Files.copy(content, bufferedOutputStream); } int responseCode = con.getResponseCode(); StringBuilder response = readResponse(con); if (isFailureResponseCode(responseCode)) { throw new HTTPException(responseCode); } } finally { if (con != null) { con.disconnect(); } } }
private void sendResponse(HttpServletResponse response, String payload, boolean json) { try { // Convert to JSON? if (json) { JSONObject jobt = XML.toJSONObject(payload); payload = jobt.toString(3); // 3 is indentation level for nice look } OutputStream out = response.getOutputStream(); out.write(payload.getBytes()); out.flush(); } catch(Exception e) { throw new HTTPException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
/** * * HTTP Get request: * GET url * * If the HTTP status code is not 200, this method throws * {@link HTTPException}. * * @param url Url for GET request. * @return Data sent by the server in response as byte[]. * @throws MalformedURLException * @throws IOException */ public static byte[] getRequest( String url ) throws MalformedURLException, IOException { HttpURLConnection connection = ( HttpURLConnection ) new URL( url ).openConnection(); int response = connection.getResponseCode(); if ( response != 200 ) throw new HTTPException( response ); byte[] bytes; String transferEncoding = connection.getHeaderField( "Transfer-Encoding" ); if ( transferEncoding != null && transferEncoding.compareToIgnoreCase( "chunked" ) == 0 ) { ChunkedByteArrayResponseHandler handler = new ChunkedByteArrayResponseHandler( 1024 ); getRequest( connection, handler ); bytes = handler.getArray(); } else { int contentLength = Integer.parseInt( connection.getHeaderField( "Content-Length" ) ); bytes = new byte[ contentLength ]; getRequest( connection, new ByteArrayResponseHandler( bytes ) ); } connection.disconnect(); return bytes; }
protected MovilizerResponse getReplyFromCloudSync(MovilizerRequest request, Integer connectionTimeoutInMillis, Integer receiveTimeoutInMillis) { MovilizerResponse response; try { setTimeout(connectionTimeoutInMillis, receiveTimeoutInMillis); response = movilizerCloud.movilizer(request); } catch (SOAPFaultException | HTTPException e) { if (logger.isErrorEnabled()) { logger.error(e.getMessage()); } throw new MovilizerWebServiceException(e); } finally { setTimeout(defaultConnectionTimeoutInMillis, defaultReceiveTimeoutInMillis); } if (logger.isInfoEnabled()) { logger.info(String.format(MESSAGES.RESPONSE_RECEIVED, response.getSystemId())); } return response; }
protected void getReplyFromCloud(MovilizerRequest request, Integer connectionTimeoutInMillis, Integer receiveTimeoutInMillis, FutureCallback<MovilizerResponse> asyncHandler) { try { if (logger.isDebugEnabled()) { logger.debug(String.format(MESSAGES.PERFORMING_REQUEST, request.getSystemId())); } setTimeout(connectionTimeoutInMillis, receiveTimeoutInMillis); movilizerCloud.movilizerAsync(request, new AsyncHandlerAdapter<>(asyncHandler)); } catch (SOAPFaultException | HTTPException e) { if (logger.isErrorEnabled()) { logger.error(e.getMessage()); } throw new MovilizerWebServiceException(e); } finally { setTimeout(defaultConnectionTimeoutInMillis, defaultReceiveTimeoutInMillis); } }
protected void setParticipantPassword(Long systemId, String systemPassword, String deviceAddress, String newPassword, PasswordHashTypes type) { MovilizerResponse response; try { MovilizerParticipantConfiguration config = new MovilizerParticipantConfiguration(); config.setDeviceAddress(deviceAddress); config.setPasswordHashType(type.getValue()); config.setPasswordHashValue(digestPassword(newPassword, type)); MovilizerRequest request = prepareUploadRequest(systemId, systemPassword, new MovilizerRequest()); request.getParticipantConfiguration().add(config); response = movilizerCloud.movilizer(request); } catch (SOAPFaultException | HTTPException e) { if (logger.isErrorEnabled()) { logger.error(e.getMessage()); } throw new MovilizerWebServiceException(e); } if (logger.isInfoEnabled()) { logger.info(String.format(MESSAGES.PASSWORD_SUCCESSFULY_CHANGED, deviceAddress, response.getSystemId())); } }
private void doRoleCommand(String serviceName, String roleName, RoleCommand roleCommand) { URI uri = UriBuilder.fromUri(serverHostname) .path("api") .path(API_VERSION) .path("clusters") .path(clusterName) .path("services") .path(serviceName) .path("roleCommands") .path(roleCommand.toString()) .build(); String body = "{ \"items\": [ \"" + roleName + "\" ] }"; LOG.info("Executing POST against " + uri + " with body " + body + "..."); WebTarget webTarget = client.target(uri); Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); Response response = invocationBuilder.post(Entity.json(body)); int statusCode = response.getStatus(); if (statusCode != Response.Status.OK.getStatusCode()) { throw new HTTPException(statusCode); } }
private TestRailResponse httpPost(String path, String payload) throws UnsupportedEncodingException, IOException, HTTPException { TestRailResponse response; do { response = httpPostInt(path, payload); if (response.getStatus() == 429) { try { Thread.sleep(60000); } catch (InterruptedException e) { log(e.toString()); } } } while (response.getStatus() == 429); return response; }
private TestRailResponse httpPostInt(String path, String payload) throws UnsupportedEncodingException, IOException, HTTPException { TestRailResponse result; PostMethod post = new PostMethod(host + "/" + path); HttpClient httpclient = setUpHttpClient(post); try { StringRequestEntity requestEntity = new StringRequestEntity( payload, "application/json", "UTF-8" ); post.setRequestEntity(requestEntity); Integer status = httpclient.executeMethod(post); String body = new String(post.getResponseBody(), post.getResponseCharSet()); result = new TestRailResponse(status, body); } finally { post.releaseConnection(); } return result; }
public static void downloadUrl(String url, File destFile) throws IOException, HTTPException { File tmpFile = new File(destFile.getAbsoluteFile() + ".tmp"); Logger.getLogger(IOUtils.class).debug(String.format("Downloading URL %s to %s", url, tmpFile)); tmpFile.getParentFile().mkdirs(); HttpClient client = new HttpClient(); GetMethod get = new GetMethod(url); get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); int code = client.executeMethod(get); if (code >= 200 && code < 300) { copyToFileAndCloseStreams(get.getResponseBodyAsStream(), tmpFile); tmpFile.renameTo(destFile); } else Logger.getLogger(IOUtils.class).fatal("Got HTTP response code " + code + " when trying to download " + url); }
final void insertFaultMessage(C context, ProtocolException exception) { if(exception instanceof HTTPException) { context.put(MessageContext.HTTP_RESPONSE_CODE,((HTTPException)exception).getStatusCode()); } if (context != null) { // non-soap case context.setPacketMessage(Messages.createEmpty(binding.getSOAPVersion())); } }
@Override protected Packet getResponse(Packet request, Exception e, WSDLPort port, WSBinding binding) { Packet response = super.getResponse(request, e, port, binding); if (e instanceof HTTPException) { if (response.supports(MessageContext.HTTP_RESPONSE_CODE)) { response.put(MessageContext.HTTP_RESPONSE_CODE, ((HTTPException)e).getStatusCode()); } } return response; }
private JsonNode getJsonNodeFromURIGet(URI uri) throws IOException { LOG.info("Executing GET against " + uri + "..."); ClientResponse response = client.resource(uri) .accept(MediaType.APPLICATION_JSON_TYPE) .get(ClientResponse.class); int statusCode = response.getStatus(); if (statusCode != Response.Status.OK.getStatusCode()) { throw new HTTPException(statusCode); } // This API folds information as the value to an "items" attribute. return new ObjectMapper().readTree(response.getEntity(String.class)).get("items"); }
@Override public T onCompleted(Response response) throws Exception { if (expectedStatusCodes.contains(response.getStatusCode())) { if (response.hasResponseBody()) { if (tClass == String.class) { return tClass.cast(response.getResponseBody()); } else { return objectMapper.readValue(response.getResponseBody(), tClass); } } return null; } else { throw new HTTPException(response.getStatusCode()); } }
@Test(expectedExceptions = HTTPException.class) public void testWrongStatusCodeFail() throws Exception { Set<Integer> expected = new HashSet<>(); expected.add(200); when(mockResponse.getStatusCode()).thenReturn(500); DefaultAsyncCompletionHandler<String> handler = new DefaultAsyncCompletionHandler<>(String.class, expected); handler.onCompleted(mockResponse); }
@Test public void test_givenBadResponse_checkHttpSuccess_fails(TestContext context) { Async async = context.async(); when(httpFuture(httpClient.get("/400")).end()) .then(run(HttpFutures::checkHttpSuccess)) .then(runOnFail(err -> { HTTPException httpException = (HTTPException)err; assertThat(context, httpException.getStatusCode(), is(400)); assertThat(context, httpException.toString(), containsString("400")); })) .then(runOnFail(err -> async.complete())) .then(run(() -> context.fail("should never get here"))); }
/** * Convert a throwable to an HTTP status code * @param t the throwable to convert * @return the HTTP status code */ public static int throwableToCode(Throwable t) { if (t instanceof ReplyException) { return ((ReplyException)t).failureCode(); } else if (t instanceof IllegalArgumentException) { return 400; } else if (t instanceof FileNotFoundException) { return 404; } else if (t instanceof HttpException) { return ((HttpException)t).getStatusCode(); } else if (t instanceof HTTPException) { return ((HTTPException)t).getStatusCode(); } return 500; }
public static void getRequest( String url, ResponseHandler handler ) throws MalformedURLException, IOException { HttpURLConnection connection = ( HttpURLConnection ) new URL( url ).openConnection(); int response = connection.getResponseCode(); if ( response != 200 ) throw new HTTPException( response ); getRequest( connection, handler ); connection.disconnect(); }
/** * * HTTP POST request: * POST url * * The connection is returned to allow the caller to handle a potential response. * The caller is responsible for closing the connection. * * @param url Url for request. * @param postData Data to be posted * @param contentType Value of the header field "Content-Type" * @param dataWriter Caller needs to specify how to write data. * @return HTTP Connection for response handling * @throws MalformedURLException * @throws IOException */ public static < T > HttpURLConnection postRequestWithResponse( String url, T postData, String contentType, Writer< T > dataWriter ) throws MalformedURLException, IOException { HttpURLConnection connection = ( HttpURLConnection ) new URL( url ).openConnection(); connection.setDoOutput( true ); connection.setRequestMethod( POST ); connection.setRequestProperty( "Content-Type", contentType ); // Write data. OutputStream stream = connection.getOutputStream(); DataOutputStream writer = new DataOutputStream( stream ); dataWriter.write( writer, postData ); writer.flush(); writer.close(); int response = connection.getResponseCode(); if ( response != 200 ) throw new HTTPException( response ); String contentLength = connection.getHeaderField( "content-length" ); if ( contentLength == null ) return null; return connection; }
/** * Get a LiveThread object from a reddit live ID * * @param id String the Reddit Live thread ID * * @return LiveThread the live thread instance. */ public static LiveThread getLiveThread(String id) throws Exception { String url = "https://www.reddit.com/live/" + id + ".json?limit=10"; URL urlObject = new URL(url); try { HttpURLConnection htmlConnection = (HttpURLConnection) urlObject.openConnection(); htmlConnection.setRequestProperty("User-Agent", USER_AGENT); htmlConnection.setUseCaches(false); htmlConnection.setConnectTimeout(2000); htmlConnection.setReadTimeout(2000); htmlConnection.connect(); if (htmlConnection.getResponseCode() == 200) { BufferedReader in = new BufferedReader(new InputStreamReader(htmlConnection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); Gson gson = new Gson(); String threadPostingsJSON = response.toString(); return gson.fromJson(threadPostingsJSON, LiveThread.class); } else { throw new HTTPException(htmlConnection.getResponseCode()); } } catch (SocketTimeoutException ex) { System.out.println("[ERROR] SocketTimeoutException"); return null; } }
/** * Returns a Subreddit content based upon the ID * * @param id String the subreddit's name * * @return Subreddit the associated subreddit */ public static Subreddit getSubreddit(String id) throws Exception { String url = "https://www.reddit.com/r/" + id + "/new.json?limit=1"; URL urlObject = new URL(url); HttpURLConnection htmlConnection = (HttpURLConnection) urlObject.openConnection(); htmlConnection.setRequestProperty("User-Agent", USER_AGENT); htmlConnection.setUseCaches(false); htmlConnection.setConnectTimeout(2000); htmlConnection.setReadTimeout(2000); htmlConnection.connect(); if (htmlConnection.getResponseCode() == 200) { BufferedReader in = new BufferedReader(new InputStreamReader(htmlConnection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); Gson gson = new Gson(); String threadPostingsJSON = response.toString(); return gson.fromJson(threadPostingsJSON, Subreddit.class); } else { throw new HTTPException(htmlConnection.getResponseCode()); } }
protected MovilizerResponse getReplyFromCloudSync(MovilizerRequest request) { MovilizerResponse response; try { response = movilizerCloud.movilizer(request); } catch (SOAPFaultException | HTTPException e) { if (logger.isErrorEnabled()) { logger.error(e.getMessage()); } throw new MovilizerWebServiceException(e); } if (logger.isInfoEnabled()) { logger.info(String.format(MESSAGES.RESPONSE_RECEIVED, response.getSystemId())); } return response; }
protected void getReplyFromCloud(MovilizerRequest request, FutureCallback<MovilizerResponse> asyncHandler) { try { if (logger.isDebugEnabled()) { logger.debug(String.format(MESSAGES.PERFORMING_REQUEST, request.getSystemId())); } movilizerCloud.movilizerAsync(request, new AsyncHandlerAdapter<>(asyncHandler)); } catch (SOAPFaultException | HTTPException e) { if (logger.isErrorEnabled()) { logger.error(e.getMessage()); } throw new MovilizerWebServiceException(e); } }
private JsonNode getJsonNodeFromURIGet(URI uri) throws IOException { LOG.info("Executing GET against " + uri + "..."); WebTarget webTarget = client.target(uri); Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); Response response = invocationBuilder.get(); int statusCode = response.getStatus(); if (statusCode != Response.Status.OK.getStatusCode()) { throw new HTTPException(statusCode); } // This API folds information as the value to an "items" attribute. return new ObjectMapper().readTree(response.readEntity(String.class)).get("items"); }
public DataSource invoke(DataSource ds) { MessageContext mc = wsContext.getMessageContext(); String method = (String)mc.get(MessageContext.HTTP_REQUEST_METHOD); if (method.equals("GET")) { return get(ds, mc); } HTTPException ex = new HTTPException(404); throw ex; }