NetUtil.java 4.4 KB
Newer Older
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 

MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/*
 * NetUtil.java
 */

package org.maxkey.crypto.cert;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
34
import java.nio.file.Files;
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Networking utilities.
 * 
 * @author Ville Skyttä
 */
public final class NetUtil
{
	/** Logger */
	private static final Logger _logger = LoggerFactory.getLogger(NetUtil.class);

M
MaxKey 已提交
49
	//  make this configurable
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
50 51
	private static final int CONNECT_TIMEOUT = 10000;

M
MaxKey 已提交
52
	//  make this configurable
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
	private static final int READ_TIMEOUT = 20000;

	/**
	 * Private to prevent construction.
	 */
	private NetUtil()
	{
		// Nothing to do
	}

	/**
	 * Open an input stream to a GET(-like) operation on an URL.
	 * 
	 * @param url The URL
	 * @return Input stream to the URL connection
	 * @throws IOException If an I/O error occurs
	 */
	public static InputStream openGetStream(URL url)
	    throws IOException
	{
		URLConnection conn = url.openConnection();

		conn.setConnectTimeout(CONNECT_TIMEOUT);
		conn.setReadTimeout(READ_TIMEOUT);

M
MaxKey 已提交
78
		//  User-Agent?
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

		return conn.getInputStream();
	}

	/**
	 * Open an input stream to a POST(-like) operation on an URL.
	 * 
	 * @param url The URL
	 * @param content Content to POST
	 * @param contentType Content type
	 * @return Input stream to the URL connection
	 * @throws IOException If an I/O error occurs
	 */
	public static InputStream openPostStream(URL url, byte[] content, String contentType)
	    throws IOException
	{
		URLConnection conn = url.openConnection();
		conn.setDoOutput(true);

		conn.setConnectTimeout(CONNECT_TIMEOUT);
		conn.setReadTimeout(READ_TIMEOUT);

M
MaxKey 已提交
101
		//  User-Agent?
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143

		if (contentType != null)
		{
			conn.setRequestProperty("Content-Type", contentType);
		}

		conn.setRequestProperty("Content-Length", String.valueOf(content.length));

		OutputStream out = conn.getOutputStream();
		try
		{
			out.write(content);
		}
		finally
		{
			out.close();
		}

		return conn.getInputStream();
	}

	/**
	 * Download the given URL to a temporary local file. The temporary file is marked for deletion at exit.
	 * 
	 * @param url
	 * @return URL pointing to the temporary file, <code>url</code> itself if it's a file: one.
	 * @throws IOException
	 */
	public static URL download(URL url)
	    throws IOException
	{
		if ("file".equals(url.getProtocol()))
		{
			return url;
		}

		InputStream in = openGetStream(url);
		File tempFile = null;
		OutputStream out = null;

		try
		{
144
			tempFile = Files.createTempFile("portecle",null).toFile();
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
			out = new BufferedOutputStream(new FileOutputStream(tempFile));
			byte[] buf = new byte[2048];
			int n;
			while ((n = in.read(buf)) != -1)
			{
				out.write(buf, 0, n);
			}
			out.flush();
			out.close();
		}
		catch (IOException e)
		{
			try
			{
				if (out != null)
				{
					out.close();
				}
			}
			finally
			{
				if (tempFile != null && !tempFile.delete())
				{
					_logger.info("Could not delete temporary file " + tempFile);
				}
			}
			throw e;
		}
		finally
		{
			in.close();
		}

		tempFile.deleteOnExit();

		return tempFile.toURI().toURL();
	}

	/**
	 * Creates a URL pointing to a URL, URI or a File object.
	 * 
	 * @param obj Object to create a URI to
	 * @return URL
	 * @throws ClassCastException if obj is not a supported object
	 * @throws MalformedURLException if converting obj to a URL fails
	 */
	public static URL toURL(Object obj)
	    throws MalformedURLException
	{
		if (obj instanceof File)
		{
			return ((File) obj).toURI().toURL();
		}
		else if (obj instanceof URI)
		{
			return ((URI) obj).toURL();
		}
		else
		{
			return (URL) obj;
		}
	}
}