All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.dmfs.rfc3986.authorities.StringAuthority Maven / Gradle / Ivy

There is a newer version: 0.8.1
Show newest version
/*
 * 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.authorities;

import org.dmfs.rfc3986.Authority;
import org.dmfs.rfc3986.UriEncoded;
import org.dmfs.rfc3986.encoding.Precoded;


/**
 * @author Marten Gajda
 */
public final class StringAuthority implements Authority
{
    private final String mAuthority;
    private int mAtIndex = -2;
    private int mColonIndex = -2;


    public StringAuthority(String authority)
    {
        mAuthority = authority;
    }


    @Override
    public UriEncoded userinfo()
    {
        int atIndex = atIndex();
        return atIndex < 0 ? null : new Precoded(mAuthority.subSequence(0, atIndex));
    }


    @Override
    public UriEncoded host()
    {
        return new Precoded(mAuthority.substring(atIndex() + 1, colonIndex()));
    }


    public int port()
    {
        int colonIdx = colonIndex();
        return colonIdx < 0 || colonIdx >= mAuthority.length() - 1 ? -1 : Integer.parseInt(mAuthority.substring(colonIdx + 1));
    }


    public int length()
    {
        return mAuthority.length();
    }


    public char charAt(int index)
    {
        return mAuthority.charAt(index);
    }


    public CharSequence subSequence(int beginIndex, int endIndex)
    {
        return mAuthority.subSequence(beginIndex, endIndex);
    }


    private int atIndex()
    {
        if (mAtIndex == -2)
        {
            mAtIndex = mAuthority.indexOf('@');
        }
        return mAtIndex;
    }


    private int colonIndex()
    {
        if (mColonIndex == -2)
        {
            mColonIndex = mAuthority.lastIndexOf(':');
            if (mColonIndex < 0)
            {
                mColonIndex = mAuthority.length();
            }
        }
        return mColonIndex;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy