org.dmfs.rfc3986.uris.StringUri Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of rfc3986-uri Show documentation
Show all versions of rfc3986-uri Show documentation
RFC 3986 compliant URI implementation.
/*
* Copyright 2017 dmfs GmbH
*
* 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.
*/
package org.dmfs.rfc3986.uris;
import org.dmfs.rfc3986.Authority;
import org.dmfs.rfc3986.Fragment;
import org.dmfs.rfc3986.Path;
import org.dmfs.rfc3986.Query;
import org.dmfs.rfc3986.Scheme;
import org.dmfs.rfc3986.Uri;
import org.dmfs.rfc3986.authorities.StringAuthority;
import org.dmfs.rfc3986.encoding.Precoded;
import org.dmfs.rfc3986.fragments.PrecodedFragment;
import org.dmfs.rfc3986.paths.StringPath;
import org.dmfs.rfc3986.queries.PrecodedQuery;
import org.dmfs.rfc3986.schemes.StringScheme;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A {@link Uri} based on a {@link String}.
*
* @author Marten Gajda
*/
public final class StringUri implements Uri
{
private final static Pattern URI_PATTERN = Pattern.compile("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?");
private final String mUri;
private String mScheme;
private String mAuthority;
private String mPath;
private String mQuery;
private String mFragment;
public StringUri(String uri)
{
mUri = uri;
}
@Override
public Scheme scheme()
{
parse();
return new StringScheme(mScheme);
}
@Override
public Authority authority()
{
parse();
return new StringAuthority(mAuthority);
}
@Override
public Path path()
{
parse();
return new StringPath(mPath);
}
@Override
public Query query()
{
parse();
return new PrecodedQuery(mQuery == null ? null : new Precoded(mQuery));
}
@Override
public Fragment fragment()
{
parse();
return new PrecodedFragment(mFragment == null ? null : new Precoded(mFragment));
}
@Override
public boolean isHierarchical()
{
parse();
return mScheme == null || mAuthority != null || mPath.startsWith("/");
}
@Override
public boolean isAbsolute()
{
parse();
return mScheme != null;
}
private void parse()
{
if (mPath == null) // mPath should never be null after parsing
{
Matcher matcher = URI_PATTERN.matcher(mUri);
if (!matcher.matches())
{
throw new IllegalArgumentException(String.format("Illegal URI '%s'", mUri));
}
mScheme = matcher.group(2);
mAuthority = matcher.group(4);
mPath = matcher.group(5);
mQuery = matcher.group(7);
mFragment = matcher.group(9);
}
}
@Override
public String toString()
{
return mUri;
}
}