001/*-------------------------------------------------------------------------+ 002| | 003| Copyright (c) 2005-2017 The ConQAT Project | 004| | 005| Licensed under the Apache License, Version 2.0 (the "License"); | 006| you may not use this file except in compliance with the License. | 007| You may obtain a copy of the License at | 008| | 009| http://www.apache.org/licenses/LICENSE-2.0 | 010| | 011| Unless required by applicable law or agreed to in writing, software | 012| distributed under the License is distributed on an "AS IS" BASIS, | 013| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | 014| See the License for the specific language governing permissions and | 015| limitations under the License. | 016| | 017+-------------------------------------------------------------------------*/ 018package org.conqat.lib.commons.net; 019 020import java.io.File; 021import java.io.IOException; 022import java.net.HttpURLConnection; 023import java.net.URI; 024import java.net.URISyntaxException; 025import java.net.URL; 026 027/** 028 * Utils for URL handling. 029 */ 030public class UrlUtils { 031 /** "file://" protocol prefix in URLs */ 032 public static final String FILE_PROTOCOL = "file://"; 033 034 /** 035 * Converts the given url to a {@link URI}. Has special handling for "file://" 036 * paths since {@link URI#URI(String)} does not handle windows paths correctly. 037 */ 038 public static URI convertUriFromUrl(String url) throws URISyntaxException { 039 if (url.startsWith(FILE_PROTOCOL)) { 040 return new File(url.substring(FILE_PROTOCOL.length())).toURI(); 041 } 042 return new URI(url); 043 } 044 045 /** 046 * Checks whether an http connection to the given URL is possible or throws an 047 * {@link java.io.IOException}. 048 */ 049 public static void checkHttpConnection(String url) throws IOException { 050 HttpURLConnection connection = null; 051 try { 052 URL testUrl = new URL(url); 053 connection = (HttpURLConnection) testUrl.openConnection(); 054 connection.connect(); 055 } finally { 056 if (connection != null) { 057 connection.disconnect(); 058 } 059 } 060 } 061}