summaryrefslogtreecommitdiffstats
blob: 24deb4dde5654b6bd989a8cfe3a6c2db3fe09251 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*  Copyright (c) 2016, Isode Limited, London, England.
 *  All rights reserved.
 *
 *  Acquisition and use of this software and related materials for any
 *  purpose requires a written license agreement from Isode Limited,
 *  or a written license from an organisation licensed by Isode Limited
 *  to grant such a license.
 *
 */
package com.isode.stroke.network;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.isode.stroke.eventloop.Event.Callback;
import com.isode.stroke.eventloop.EventLoop;

public class PlatformDomainNameAddressQuery extends DomainNameAddressQuery {

    private final String host_;
    private final EventLoop eventLoop_;
    
    public PlatformDomainNameAddressQuery(String host,EventLoop eventLoop) {
        host_ = host;
        eventLoop_ = eventLoop;
    }
    
    private class QueryRunnable implements Runnable {

        private final List<HostAddress> results_ = 
                Collections.synchronizedList(new ArrayList<HostAddress>());

        @Override
        public void run() {
            try {
                InetAddress[] inetAddresses = InetAddress.getAllByName(host_);
                for (InetAddress address : inetAddresses) {
                    HostAddress result = new HostAddress(address);
                    results_.add(result);
                }
            } catch (UnknownHostException e) {
                emitError();
            }
            emitResults();
        }

        private void emitError() {
            eventLoop_.postEvent(new Callback() {
                
                @Override
                public void run() {
                    onResult.emit(new ArrayList<HostAddress>(),new DomainNameResolveError());
                }
                
            });
        }

        private void emitResults() {
            eventLoop_.postEvent(new Callback() {
                
                @Override
                public void run() {
                    // For thread safety emit a copy of the results
                    List<HostAddress> resultCopy = new ArrayList<HostAddress>();
                    synchronized (results_) {
                        resultCopy.addAll(results_);
                    }
                    onResult.emit(results_,null);
                }
                
            });
        }
        
    }

    @Override
    public void run() {
        Thread queryThread = new Thread(new QueryRunnable());
        queryThread.setDaemon(true);
        queryThread.run();
    }

}