001/** 002 * 003 * Copyright 2013-2016 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.dnsjava; 018 019import java.net.InetAddress; 020import java.util.ArrayList; 021import java.util.List; 022 023import org.jivesoftware.smack.ConnectionConfiguration.DnssecMode; 024import org.jivesoftware.smack.initializer.SmackInitializer; 025import org.jivesoftware.smack.util.DNSUtil; 026import org.jivesoftware.smack.util.dns.DNSResolver; 027import org.jivesoftware.smack.util.dns.HostAddress; 028import org.jivesoftware.smack.util.dns.SRVRecord; 029import org.xbill.DNS.Lookup; 030import org.xbill.DNS.Record; 031import org.xbill.DNS.TextParseException; 032import org.xbill.DNS.Type; 033 034/** 035 * This implementation uses the <a href="http://www.dnsjava.org/">dnsjava</a> implementation for resolving DNS addresses. 036 * 037 */ 038public class DNSJavaResolver extends DNSResolver implements SmackInitializer { 039 040 private static DNSJavaResolver instance = new DNSJavaResolver(); 041 042 public static DNSResolver getInstance() { 043 return instance; 044 } 045 046 public DNSJavaResolver() { 047 super(false); 048 } 049 050 @Override 051 protected List<SRVRecord> lookupSRVRecords0(String name, List<HostAddress> failedAddresses, DnssecMode dnssecMode) { 052 List<SRVRecord> res = new ArrayList<SRVRecord>(); 053 054 Lookup lookup; 055 try { 056 lookup = new Lookup(name, Type.SRV); 057 } 058 catch (TextParseException e) { 059 throw new IllegalStateException(e); 060 } 061 062 Record[] recs = lookup.run(); 063 if (recs == null) 064 return res; 065 066 for (Record record : recs) { 067 org.xbill.DNS.SRVRecord srvRecord = (org.xbill.DNS.SRVRecord) record; 068 if (srvRecord != null && srvRecord.getTarget() != null) { 069 String host = srvRecord.getTarget().toString(); 070 int port = srvRecord.getPort(); 071 int priority = srvRecord.getPriority(); 072 int weight = srvRecord.getWeight(); 073 074 List<InetAddress> hostAddresses = lookupHostAddress0(host, failedAddresses, dnssecMode); 075 if (hostAddresses == null) { 076 continue; 077 } 078 079 SRVRecord r = new SRVRecord(host, port, priority, weight, hostAddresses); 080 res.add(r); 081 } 082 } 083 084 return res; 085 } 086 087 public static void setup() { 088 DNSUtil.setDNSResolver(getInstance()); 089 } 090 091 @Override 092 public List<Exception> initialize() { 093 setup(); 094 return null; 095 } 096 097}