List of usage examples for com.squareup.okhttp ResponseBody close
@Override public void close() throws IOException
From source file:io.fabric8.docker.client.impl.ContainerOutputHandle.java
License:Apache License
@Override public void onMessage(ResponseBody message) throws IOException { try {//from w ww . j a v a2 s .c o m byte streamID = message.source().readByte(); ByteString byteString = message.source().readByteString(); if (byteString.size() > 0) { switch (streamID) { case 1: if (out != null) { out.write(byteString.toByteArray()); } break; case 2: if (err != null) { err.write(byteString.toByteArray()); } break; case 3: if (err != null) { err.write(byteString.toByteArray()); } break; default: throw new IOException("Unknown stream ID " + streamID); } } } finally { message.close(); } }
From source file:io.fabric8.kubernetes.client.dsl.internal.WatchConnectionManager.java
License:Apache License
private final void runWatch() throws MalformedURLException, ExecutionException, InterruptedException { URL requestUrl = baseOperation.getNamespacedUrl(); HttpUrl.Builder httpUrlBuilder = HttpUrl.get(requestUrl).newBuilder(); String labelQueryParam = baseOperation.getLabelQueryParam(); if (labelQueryParam.length() > 0) { httpUrlBuilder.addQueryParameter("labelSelector", labelQueryParam); }/*from ww w . j a v a 2s . c om*/ String fieldQueryString = baseOperation.getFieldQueryParam(); String name = baseOperation.getName(); if (name != null && name.length() > 0) { if (fieldQueryString.length() > 0) { fieldQueryString += ","; } fieldQueryString += "metadata.name=" + name; } httpUrlBuilder.addQueryParameter("fieldSelector", fieldQueryString); httpUrlBuilder.addQueryParameter("resourceVersion", this.resourceVersion.get()).addQueryParameter("watch", "true"); Request request = new Request.Builder().get().url(httpUrlBuilder.build()) .addHeader("Origin", requestUrl.getProtocol() + "://" + requestUrl.getHost() + ":" + requestUrl.getPort()) .build(); clonedClient.setReadTimeout(0, TimeUnit.MILLISECONDS); webSocketCall = WebSocketCall.create(clonedClient, request); webSocketCall.enqueue(new WebSocketListener() { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public void onOpen(WebSocket webSocket, Response response) { webSocketRef.set(webSocket); currentReconnectAttempt.set(0); } @Override public void onFailure(IOException e, Response response) { e.printStackTrace(); try { if (response != null && response.body() != null) { response.body().close(); } } catch (IOException e1) { e1.printStackTrace(); } if (forceClosed.get()) { executor.shutdownNow(); watcher.onClose(null); return; } onClose(4000, "Connection unexpectedly closed"); } @Override public void onMessage(ResponseBody message) throws IOException { try { WatchEvent event = mapper.readValue(message.byteStream(), WatchEvent.class); T obj = (T) event.getObject(); //Dirty cast - should always be valid though String currentResourceVersion = resourceVersion.get(); String newResourceVersion = ((HasMetadata) obj).getMetadata().getResourceVersion(); if (currentResourceVersion.compareTo(newResourceVersion) < 0) { resourceVersion.compareAndSet(currentResourceVersion, newResourceVersion); } Watcher.Action action = Watcher.Action.valueOf(event.getType()); watcher.eventReceived(action, obj); } catch (IOException e) { logger.error("Could not deserialize watch event: {}", message.source().readUtf8(), e); } catch (ClassCastException e) { logger.error("Received wrong type of object for watch", e); } catch (IllegalArgumentException e) { logger.error("Invalid event type", e); } finally { message.close(); } } @Override public void onPong(Buffer buffer) { } @Override public void onClose(final int code, final String reason) { if (forceClosed.get()) { executor.shutdownNow(); watcher.onClose(null); return; } executor.submit(new Runnable() { @Override public void run() { try { runWatch(); } catch (ExecutionException e) { if (e.getCause() != null && e.getCause().getCause() != null && e.getCause().getCause() instanceof ConnectException) { if (reconnectLimit >= 0 && currentReconnectAttempt.getAndIncrement() >= reconnectLimit) { watcher.onClose( new KubernetesClientException("Connection unexpectedly closed", e)); return; } try { TimeUnit.MILLISECONDS.sleep(reconnectInterval); } catch (InterruptedException e1) { watcher.onClose( new KubernetesClientException("Connection unexpectedly closed", e1)); return; } onClose(code, reason); } } catch (MalformedURLException | InterruptedException e) { throw KubernetesClientException.launderThrowable(e); } } }); } }); }
From source file:io.fabric8.kubernetes.server.mock.WebSocketSession.java
License:Apache License
private String read(ResponseBody message) throws IOException { try {//from ww w.j ava 2 s.c om byte streamID = message.source().readByte(); ByteString byteString = message.source().readByteString(); if (byteString.size() > 0) { switch (streamID) { case 1: case 2: case 3: return byteString.toString(); default: throw new IOException("Unknown stream ID " + streamID); } } } finally { message.close(); } throw new IllegalArgumentException("Not a string message"); }
From source file:io.github.tjg1.library.norilib.clients.Danbooru.java
@Override public SearchResult search(String tags, int pid) throws IOException { // Create HTTP request. final Request request = new Request.Builder().url(createSearchURL(tags, pid, DEFAULT_LIMIT)).build(); // Get HTTP response. final Response response = okHttpClient.newCall(request).execute(); final ResponseBody responseBody = response.body(); final String body = responseBody.string(); responseBody.close(); // Return parsed SearchResult. return parseXMLResponse(body, tags, pid); }
From source file:org.fuse.hawkular.agent.monitor.cmd.FeedCommProcessor.java
License:Apache License
@Override @SuppressWarnings({ "rawtypes", "unchecked" }) public void onMessage(ResponseBody responseBody) throws IOException { BasicMessageWithExtraData<? extends BasicMessage> response; String requestClassName = "?"; try {//from www . j av a 2 s.c om try { BasicMessageWithExtraData<? extends BasicMessage> msgWithData; if (responseBody.contentType().equals(WebSocket.TEXT)) { String nameAndJsonStr = responseBody.string(); msgWithData = new ApiDeserializer().deserialize(nameAndJsonStr); } else if (responseBody.contentType().equals(WebSocket.BINARY)) { InputStream input = responseBody.byteStream(); msgWithData = new ApiDeserializer().deserialize(input); } else { throw new IllegalArgumentException( "Unknown mediatype type, please report this bug: " + responseBody.contentType()); } log.debug("Received message from server"); BasicMessage msg = msgWithData.getBasicMessage(); requestClassName = msg.getClass().getName(); Class<? extends Command<?, ?>> commandClass = VALID_COMMANDS.get(requestClassName); if (commandClass == null) { log.errorInvalidCommandRequestFeed(requestClassName); String errorMessage = "Invalid command request: " + requestClassName; GenericErrorResponse errorMsg = new GenericErrorResponseBuilder().setErrorMessage(errorMessage) .build(); response = new BasicMessageWithExtraData<BasicMessage>(errorMsg, null); } else { Command command = commandClass.newInstance(); CommandContext context = new CommandContext(this, this.config, this.discoveryService); response = command.execute(msgWithData, context); } } finally { // must ensure response is closed; this assumes if it was a stream that the command is finished with it responseBody.close(); } } catch (Throwable t) { log.errorCommandExecutionFailureFeed(requestClassName, t); String errorMessage = "Command failed [" + requestClassName + "]"; GenericErrorResponse errorMsg = new GenericErrorResponseBuilder().setThrowable(t) .setErrorMessage(errorMessage).build(); response = new BasicMessageWithExtraData<BasicMessage>(errorMsg, null); } // send the response back to the server if (response != null) { try { sendSync(response); } catch (Exception e) { log.errorFailedToSendOverFeedComm(response.getClass().getName(), e); } } }
From source file:org.kegbot.api.KegbotApiImpl.java
License:Open Source License
private JsonNode requestJson(Request request) throws KegbotApiException { final Response response; final long startTime = SystemClock.elapsedRealtime(); try {//w w w .j a va 2 s .c om response = mClient.newCall(request).execute(); } catch (IOException e) { Log.w(TAG, String.format("--> %s %s [ERR]", request.method(), request.urlString())); throw new KegbotApiException(e); } final long endTime = SystemClock.elapsedRealtime(); final int responseCode = response.code(); final String logMessage = String.format("--> %s %s [%s] %sms", request.method(), request.urlString(), responseCode, endTime - startTime); if (responseCode >= 200 && responseCode < 300) { Log.d(TAG, logMessage); } else { Log.w(TAG, logMessage); } final ResponseBody body = response.body(); final JsonNode rootNode; try { try { final ObjectMapper mapper = new ObjectMapper(); rootNode = mapper.readValue(body.byteStream(), JsonNode.class); } finally { body.close(); } } catch (JsonParseException e) { throw new KegbotApiMalformedResponseException(e); } catch (JsonMappingException e) { throw new KegbotApiMalformedResponseException(e); } catch (IOException e) { throw new KegbotApiException(e); } boolean success = false; try { // Handle structural errors. if (!rootNode.has("meta")) { throw new KegbotApiMalformedResponseException("Response is missing 'meta' field."); } final JsonNode meta = rootNode.get("meta"); if (!meta.isContainerNode()) { throw new KegbotApiMalformedResponseException("'meta' field is wrong type."); } final String message; if (rootNode.has("error") && rootNode.get("error").has("message")) { message = rootNode.get("error").get("message").getTextValue(); } else { message = null; } // Handle HTTP errors. if (responseCode < 200 || responseCode >= 400) { switch (responseCode) { case 401: throw new NotAuthorizedException(message); case 404: throw new KegbotApi404(message); case 405: throw new MethodNotAllowedException(message); default: if (message != null) { throw new KegbotApiServerError(message); } else { throw new KegbotApiServerError("Server error, response code=" + responseCode); } } } success = true; return rootNode; } finally { if (!success) { Log.d(TAG, "Response JSON was: " + rootNode.toString()); } } }
From source file:retrofit.VoidConverter.java
License:Apache License
@Override public Void convert(ResponseBody value) throws IOException { value.close(); return null; }