Java tutorial
/* Copyright (C) 2013-2014 Ian Teune <ian.teune@gmail.com> * * 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.tinspx.util.net; import com.google.common.base.Strings; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; import java.net.UnknownServiceException; import java.util.Collections; import java.util.List; import java.util.Map; import lombok.Setter; import lombok.experimental.Accessors; /** * * @author Ian */ @Setter @Accessors(fluent = true) public class CofigURLConnection extends URLConnection { IOException connectThrow; IOException outThrow; OutputStream out; IOException inThrow; InputStream in; Headers headers; public CofigURLConnection(URL url) { super(url); } @Override public void connect() throws IOException { if (connectThrow != null) { throw connectThrow; } connected = true; } @Override public OutputStream getOutputStream() throws IOException { if (!getDoOutput()) { throw new IOException("doOutput is false"); } connect(); if (outThrow != null) { throw outThrow; } if (out == null) { throw new UnknownServiceException(); } return out; } @Override public InputStream getInputStream() throws IOException { if (!getDoInput()) { throw new IOException("doInput is false"); } connect(); if (inThrow != null) { throw inThrow; } if (in == null) { throw new UnknownServiceException(); } return in; } @Override public String getHeaderField(int n) { throw new UnsupportedOperationException(); } @Override public String getHeaderFieldKey(int n) { throw new UnsupportedOperationException(); } @Override public Map<String, List<String>> getHeaderFields() { if (headers != null) { return Collections.unmodifiableMap(headers.asMap()); } else { return Collections.emptyMap(); } } @Override public String getHeaderField(String name) { return headers != null ? Strings.emptyToNull(headers.last(name)) : null; } }