001/**
002 *
003 * Copyright © 2013-2017 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
019import java.net.InetAddress;
020import java.util.Collections;
021import java.util.Iterator;
022import java.util.LinkedHashMap;
023import java.util.List;
024import java.util.Map;
025import java.util.Map.Entry;
026
027import org.jivesoftware.smack.SmackException.ConnectionException;
028import org.jivesoftware.smack.util.StringUtils;
029
030public class HostAddress {
031    private final String fqdn;
032    private final int port;
033    private final Map<InetAddress, Exception> exceptions = new LinkedHashMap<>();
034    private final List<InetAddress> inetAddresses;
035
036    /**
037     * Creates a new HostAddress with the given FQDN.
038     * 
039     * @param fqdn the optional fully qualified domain name (FQDN).
040     * @param port The port to connect on.
041     * @throws IllegalArgumentException If the port is out of valid range (0 - 65535).
042     */
043    public HostAddress(String fqdn, int port, List<InetAddress> inetAddresses) {
044        if (port < 0 || port > 65535)
045            throw new IllegalArgumentException(
046                    "Port must be a 16-bit unsiged integer (i.e. between 0-65535. Port was: " + port);
047        if (StringUtils.isNotEmpty(fqdn) && fqdn.charAt(fqdn.length() - 1) == '.') {
048            this.fqdn = fqdn.substring(0, fqdn.length() - 1);
049        }
050        else {
051            this.fqdn = fqdn;
052        }
053        this.port = port;
054        if (inetAddresses.isEmpty()) {
055            throw new IllegalArgumentException("Must provide at least one InetAddress");
056        }
057        this.inetAddresses = inetAddresses;
058    }
059
060    public HostAddress(int port, InetAddress hostAddress) {
061        this(null, port, Collections.singletonList(hostAddress));
062    }
063
064    /**
065     * Constructs a new failed HostAddress. This constructor is usually used when the DNS resolution of the domain name
066     * failed for some reason.
067     *
068     * @param fqdn the domain name of the host.
069     * @param e the exception causing the failure.
070     */
071    public HostAddress(String fqdn, Exception e) {
072        this.fqdn = fqdn;
073        this.port = 5222;
074        inetAddresses = Collections.emptyList();
075        setException(e);
076    }
077
078    public String getFQDN() {
079        return fqdn;
080    }
081
082    public int getPort() {
083        return port;
084    }
085
086    public void setException(Exception exception) {
087        setException(null, exception);
088    }
089
090    public void setException(InetAddress inetAddress, Exception exception) {
091        Exception old = exceptions.put(inetAddress, exception);
092        assert(old == null);
093    }
094
095    /**
096     * Retrieve the Exception that caused a connection failure to this HostAddress. Every
097     * HostAddress found in {@link ConnectionException} will have an Exception set,
098     * which can be retrieved with this method.
099     * 
100     * @return the Exception causing this HostAddress to fail
101     */
102    public Map<InetAddress, Exception> getExceptions() {
103        return Collections.unmodifiableMap(exceptions);
104    }
105
106    public List<InetAddress> getInetAddresses() {
107        return Collections.unmodifiableList(inetAddresses);
108    }
109
110    @Override
111    public String toString() {
112        return fqdn + ":" + port;
113    }
114
115    @Override
116    public boolean equals(Object o) {
117        if (this == o) {
118            return true;
119        }
120        if (!(o instanceof HostAddress)) {
121            return false;
122        }
123
124        final HostAddress address = (HostAddress) o;
125
126        if (!fqdn.equals(address.fqdn)) {
127            return false;
128        }
129        return port == address.port;
130    }
131
132    @Override
133    public int hashCode() {
134        int result = 1;
135        result = 37 * result + fqdn.hashCode();
136        return result * 37 + port;
137    }
138
139    public String getErrorMessage() {
140        if (exceptions.isEmpty()) {
141            return "No error logged";
142        }
143        StringBuilder sb = new StringBuilder();
144        sb.append('\'').append(toString()).append("' failed because: ");
145        Iterator<Entry<InetAddress, Exception>> iterator = exceptions.entrySet().iterator();
146        while (iterator.hasNext()) {
147            Entry<InetAddress, Exception> entry = iterator.next();
148            InetAddress inetAddress = entry.getKey();
149            if (inetAddress != null) {
150                sb.append(entry.getKey()).append(" exception: ");
151            }
152            sb.append(entry.getValue());
153            if (iterator.hasNext()) {
154                sb.append(", ");
155            }
156        }
157
158        return sb.toString();
159    }
160}