001/* 002 * oauth2-oidc-sdk 003 * 004 * Copyright 2012-2016, Connect2id Ltd and contributors. 005 * 006 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use 007 * this file except in compliance with the License. You may obtain a copy of the 008 * License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software distributed 013 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 014 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 015 * specific language governing permissions and limitations under the License. 016 */ 017 018package com.nimbusds.oauth2.sdk.util; 019 020 021import java.net.URI; 022import java.net.URISyntaxException; 023 024 025/** 026 * URI operations. 027 */ 028public final class URIUtils { 029 030 031 /** 032 * Gets the base part (schema, host, port and path) of the specified 033 * URI. 034 * 035 * @param uri The URI. May be {@code null}. 036 * 037 * @return The base part of the URI, {@code null} if the original URI 038 * is {@code null} or doesn't specify a protocol. 039 */ 040 public static URI getBaseURI(final URI uri) { 041 042 if (uri == null) 043 return null; 044 045 try { 046 return new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), null, null); 047 048 } catch (URISyntaxException e) { 049 050 return null; 051 } 052 } 053 054 055 /** 056 * Strips the query string from the specified URI. 057 * 058 * @param uri The URI. May be {@code null}.' 059 * 060 * @return The URI with stripped query string, {@code null} if the 061 * original URI is {@code null} or doesn't specify a protocol. 062 */ 063 public static URI stripQueryString(final URI uri) { 064 065 if (uri == null) 066 return null; 067 068 try { 069 return new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), null, uri.getFragment()); 070 071 } catch (URISyntaxException e) { 072 return null; 073 } 074 } 075 076 077 /** 078 * Removes the trailing slash ("/") from the specified URI, if present. 079 * 080 * @param uri The URI. May be {@code null}. 081 * 082 * @return The URI with no trailing slash, {@code null} if the original 083 * URI is {@code null}. 084 */ 085 public static URI removeTrailingSlash(final URI uri) { 086 087 if (uri == null) 088 return null; 089 090 String uriString = uri.toString(); 091 092 if (uriString.charAt(uriString.length() - 1 ) == '/') { 093 return URI.create(uriString.substring(0, uriString.length() - 1)); 094 } 095 096 return uri; 097 } 098 099 100 /** 101 * Prevents public instantiation. 102 */ 103 private URIUtils() {} 104}