Java tutorial
/* * The MIT License * * Copyright 2014 CloudBees. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.cloudbees.mtslaves.client; import com.cloudbees.api.cr.Credential; import net.sf.json.JSONObject; import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.NullOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * @author Kohsuke Kawaguchi */ public abstract class RemoteReference { /** * URL of this resource. */ public final URL url; /** * Represents the authorization for talking to this remote object. */ protected final Credential token; protected RemoteReference(URL url, Credential token) { try { if (!url.toString().endsWith("/")) url = new URL(url.toExternalForm() + '/'); // normalize } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid URL:" + url, e); } this.url = url; this.token = token; } protected <T extends BaseJsonObject> T getResource(String path, Class<T> type) throws IOException { HttpURLConnection con = open(path); try { JSONObject json = JSONObject.fromObject(IOUtils.toString(con.getInputStream(), "UTF-8")); T resource = (T) json.toBean(type); resource.json = json; return resource; } catch (IOException e) { throw wrappedException(con, e); } } /** * Wrap the exception with one which includes the error message from the server. * @param con the connection throwing the error * @param e the original exception * @return the wrapped exception * @throws IOException is unexpected */ protected IOException wrappedException(HttpURLConnection con, IOException e) throws IOException { InputStream es = con.getErrorStream(); String payload = es != null ? IOUtils.toString(es) : "(no data)"; return new IOException(e.getMessage() + " Error response: " + payload, e); } protected HttpURLConnection open(String relUrl) throws IOException { URL u = getEntityUrl(relUrl); HttpURLConnection con = (HttpURLConnection) u.openConnection(); con.addRequestProperty("Accept", "application/json"); this.token.authorizeRequest(con); con.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MS); con.setReadTimeout(DEFAULT_READ_TIMEOUT_MS); return con; } protected URL getEntityUrl(String restOfUrl) throws MalformedURLException { URL u = url; if (url.toString().endsWith("/")) u = new URL(u, restOfUrl); else u = new URL(u.toExternalForm() + '/' + restOfUrl); return u; } protected HttpURLConnection postJson(HttpURLConnection con, JSONObject json) throws IOException { try { token.authorizeRequest(con); con.setDoOutput(true); con.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); con.connect(); // send JSON OutputStreamWriter w = new OutputStreamWriter(con.getOutputStream(), "UTF-8"); json.write(w); w.close(); return con; } catch (IOException e) { throw (IOException) new IOException("Failed to POST to " + url).initCause(e); } } protected void verifyResponseStatus(HttpURLConnection con) throws IOException { if (con.getResponseCode() / 100 != 2) { String msg = "Failed to call " + con.getURL() + " : " + con.getResponseCode() + ' ' + con.getResponseMessage(); InputStream es = con.getErrorStream(); String ct = con.getContentType(); if (ct != null) { HttpHeader contentType = HttpHeader.parse(ct); if (contentType.value.equals("application/json")) { // if the error is JSON, parse it if (es != null) { JSONObject error = JSONObject .fromObject(IOUtils.toString(es, contentType.getSubHeader("charset", "UTF-8"))); throw new ServerException(msg, error, con.getResponseCode(), con.getResponseMessage(), con.getURL()); } } } if (es != null) msg += "\n" + IOUtils.toString(es); throw new IOException(msg); } } protected void drain(HttpURLConnection con) throws IOException { if (con.getResponseCode() >= 500) { String error = IOUtils.toString(con.getErrorStream()); con.getErrorStream().close(); throw new IOException("Error received:" + con.getResponseCode() + "\n" + error); } else { IOUtils.copy(con.getInputStream(), new NullOutputStream()); con.getInputStream().close(); } } /** * How long to wait for a connection. */ public static final int DEFAULT_CONNECT_TIMEOUT_MS = 30 * 1000; /** * How long to wait for responses, in general. */ public static final int DEFAULT_READ_TIMEOUT_MS = 60 * 1000; }