001/**
002 *
003 * Copyright 2013-2014 Florian Schmaus
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 */
017package org.jivesoftware.smack.util.dns;
018
019/**
020 * @see <a href="http://tools.ietf.org/html/rfc2782">RFC 2782: A DNS RR for specifying the location of services (DNS
021 * SRV)</a>
022 * @author Florian Schmaus
023 * 
024 */
025public class SRVRecord extends HostAddress implements Comparable<SRVRecord> {
026    
027    private int weight;
028    private int priority;
029    
030    /**
031     * Create a new SRVRecord
032     * 
033     * @param fqdn Fully qualified domain name
034     * @param port The connection port
035     * @param priority Priority of the target host
036     * @param weight Relative weight for records with same priority
037     * @throws IllegalArgumentException fqdn is null or any other field is not in valid range (0-65535).
038     */
039    public SRVRecord(String fqdn, int port, int priority, int weight) {
040        super(fqdn, port);
041        if (weight < 0 || weight > 65535)
042            throw new IllegalArgumentException(
043                    "DNS SRV records weight must be a 16-bit unsiged integer (i.e. between 0-65535. Weight was: "
044                            + weight);
045
046        if (priority < 0 || priority > 65535)
047            throw new IllegalArgumentException(
048                    "DNS SRV records priority must be a 16-bit unsiged integer (i.e. between 0-65535. Priority was: "
049                            + priority);
050
051        this.priority = priority;
052        this.weight = weight;
053
054    }
055    
056    public int getPriority() {
057        return priority;
058    }
059    
060    public int getWeight() {
061        return weight;
062    }
063
064    @Override
065    public int compareTo(SRVRecord other) {
066        // According to RFC2782,
067        // "[a] client MUST attempt to contact the target host with the lowest-numbered priority it can reach".
068        // This means that a SRV record with a higher priority is 'less' then one with a lower.
069        int res = other.priority - this.priority;
070        if (res == 0) {
071            res = this.weight - other.weight;
072        }
073        return res;
074    }
075
076    @Override
077    public String toString() {
078        return super.toString() + " prio:" + priority + ":w:" + weight;
079    }
080}