Example usage for java.net UnknownHostException toString

List of usage examples for java.net UnknownHostException toString

Introduction

In this page you can find the example usage for java.net UnknownHostException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:orca.registry.DatabaseOperations.java

License:asdf

/**
 *  insert version for inserting the actors and their properties
 * @param act_name/*from   ww  w  . j a v a 2 s . c o  m*/
 * @param act_type
 * @param act_guid
 * @param act_desc
 * @param act_soapaxis2url
 * @param act_class
 * @param act_mapper_class
 * @param act_pubkey
 * @param act_cert64
 */
public String insert(String act_name, String act_type, String act_guid, String act_desc,
        String act_soapaxis2url, String act_class, String act_mapper_class, String act_pubkey,
        String act_cert64) {

    if ((act_name == null) || (act_type == null) || (act_guid == null) || (act_soapaxis2url == null)
            || (act_class == null) || (act_mapper_class == null) || (act_pubkey == null)
            || (act_cert64 == null))
        return "STATUS: ERROR; invalid insert parameters";

    if (act_desc == null) {
        act_desc = "No description";
    }

    log.debug(
            "Inside DatabaseOperations: insert() - inserting actors and their properties for guid " + act_guid);
    String status = STATUS_SUCCESS;
    Connection conn = null;

    // check for name duplicate
    if (checkNameDuplicate(act_name, act_guid)) {
        log.error("This registration is invalid, actor " + act_name + "/" + act_guid
                + " will not be allowed to register");
        return "STATUS: ERROR; duplicate actor name detected";
    }

    try {
        // Query the Actors table to find out if act_guid already present
        // If act_guid already present, check if the ip address of the client 
        // matches the IP address returned by InetAddress.getByName(act_soapaxis2url - the extracted portion of soapaxis2url)
        // If it matches, execute an 'Update' command for that row, OR, delete that row and insert this new row
        // Set new timestamp for that row

        String clientIP = RegistryServlet.getClientIpAddress();
        //System.out.println("clientIP = " + clientIP);
        log.debug("DatabaseOperations: insert() -  clientIP = " + clientIP);

        if (clientIP == null) {
            //System.out.println("Can't get IP address of client; Insert failed");
            log.error("DatabaseOperations: insert() -  Can't get IP address of client; Insert failed");
            return "STATUS: ERROR; Can't get IP address of client; Insert failed";
        }

        String[] splitSoapUrl = act_soapaxis2url.split("//");
        String noHttp = splitSoapUrl[1];
        String[] splitNoHttp = noHttp.split(":");
        String ipSoapUrl = splitNoHttp[0];

        //System.out.println("ip in SoapUrl = " + ipSoapUrl);
        log.debug("DatabaseOperations: insert() -  ip in SoapUrl = " + ipSoapUrl);

        String humanReadableIP = null;
        String numericIP = null;
        try {
            InetAddress address = InetAddress.getByName(ipSoapUrl);
            //System.out.println("humanreadable IP/numeric IP = " + address.toString());
            //log.debug("humanreadable IP/numeric IP = " + address.toString());
            String[] splitResultGetByName = address.toString().split("/");
            humanReadableIP = splitResultGetByName[0];
            numericIP = splitResultGetByName[1];
        } catch (UnknownHostException ex) {
            log.error("Error converting IP address: " + ex.toString());
            return "STATUS: ERROR; Exception encountered";
        }

        boolean insertEntry = false;
        String act_production_deployment = FALSE_STRING;
        if (clientIP.equalsIgnoreCase(numericIP)) {
            insertEntry = true;
            act_production_deployment = TRUE_STRING;

            if (ipSoapUrl.equalsIgnoreCase("localhost") || ipSoapUrl.equalsIgnoreCase("127.0.0.1")) {
                // Special check: if the soapaxis url is localhost (implying test deployment) set production deployment as false

                // REMINDER: set to FALSE_STRING before deploying otherwise localhost actors will be considered valid
                act_production_deployment = FALSE_STRING;
            }
        } else {
            log.error(
                    "Can't verify the identity of the client; client IP doesn't match with IP in SOAP-Axis URL of the Actor; It is also not a test deployment. INSERT Failed !!!");
            return "STATUS: ERROR; Can't verify the identity of the client; client IP doesn't match with IP in SOAP-Axis URL of the Actor;";
        }

        boolean actorExists = checkExistingGuid(act_guid);

        //System.out.println("Trying to get a new instance");
        log.debug("Inside DatabaseOperations: insert() - Trying to get a new instance");
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        //System.out.println("Trying to get a database connection");
        log.debug("Inside DatabaseOperations: insert() - Trying to get a database connection");
        conn = DriverManager.getConnection(url, userName, password);
        //System.out.println ("Database connection established");
        log.debug("Inside DatabaseOperations: insert() - Database connection established");

        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String act_last_update = sdf.format(cal.getTime());

        if (insertEntry) { // valid client trying to insert new entry or trying to update an existing entry

            if (!actorExists) { // New actor
                PreparedStatement pStat = conn.prepareStatement(
                        "INSERT into `Actors` ( `act_name` , `act_guid` , `act_type`, `act_desc`, `act_soapaxis2url`, `act_class`, `act_mapper_class`, `act_pubkey`, `act_cert64`, `act_production_deployment`, `act_last_update`, `act_verified`) values "
                                + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                pStat.setString(1, act_name);
                pStat.setString(2, act_guid);
                pStat.setString(3, act_type);
                pStat.setString(4, act_desc);
                pStat.setString(5, act_soapaxis2url);
                pStat.setString(6, act_class);
                pStat.setString(7, act_mapper_class);
                pStat.setString(8, act_pubkey);
                pStat.setString(9, act_cert64);
                pStat.setString(10, act_production_deployment);
                pStat.setString(11, act_last_update);
                pStat.setString(12, FALSE_STRING);
                pStat.execute();
                pStat.close();
            } else { // Existing actor
                     // get ALL known entries
                Map<String, String> res = queryMapForGuid(act_guid, false);

                // update if necessary: only location  and description can be updated
                boolean needUpdate = false;
                if (!res.get(ActorLocation).equals(act_soapaxis2url))
                    needUpdate = true;

                if (res.get(ActorDesc) == null) {
                    if (act_desc != null)
                        needUpdate = true;
                } else if (!res.get(ActorDesc).equals(act_desc))
                    needUpdate = true;

                if (needUpdate) {
                    log.debug("Updating description or location for actor " + act_guid);
                    PreparedStatement pStat = conn.prepareStatement(
                            "UPDATE Actors SET act_soapaxis2url = ?, act_desc = ?, act_last_update = ? WHERE act_guid = ?");
                    pStat.setString(1, act_soapaxis2url);
                    pStat.setString(2, act_desc);
                    pStat.setString(3, act_last_update);
                    pStat.setString(4, act_guid);
                    pStat.execute();
                    pStat.close();
                } else {
                    // if any other mismatch - return error
                    if (!res.get(ActorName).equals(act_name) || !res.get(ActorClazz).equals(act_class)
                            || !res.get(ActorMapperclass).equals(act_mapper_class)
                            || !res.get(ActorPubkey).equals(act_pubkey)
                            || !res.get(ActorCert64).equals(act_cert64)) {
                        status = "STATUS: ERROR; Mimatch to previous registration for this guid. Please change the guid and generate new certificate;";
                        log.error("Error inserting information for actor " + act_name + ":" + act_guid
                                + " due to mismatch to previous registration");
                    } else {
                        // otherwise simply insert heartbeat for this guid
                        insertHeartbeat(act_guid);
                    }
                }
            }
        }
    } catch (Exception e) {
        //System.err.println ("Error inserting into Actors table");
        log.error("DatabaseOperations: insert() - Error inserting into Actors table: " + e.toString());
        status = "STATUS: ERROR; Exception encountered during insert";
    } finally {
        if (conn != null) {
            try {
                conn.close();
                //System.out.println ("Database connection terminated");
                log.debug("Database connection terminated");
            } catch (Exception e) { /* ignore close errors */
            }
        }
    }
    return status;
}

From source file:eu.faircode.adblocker.ServiceSinkhole.java

private void prepareUidIPFilters(String dname) {
    if (dname == null)
        mapUidIPFilters.clear();//from  w  ww.ja  v  a  2  s.co  m

    Cursor cursor = DatabaseHelper.getInstance(ServiceSinkhole.this).getAccessDns(dname);
    int colUid = cursor.getColumnIndex("uid");
    int colVersion = cursor.getColumnIndex("version");
    int colProtocol = cursor.getColumnIndex("protocol");
    int colDAddr = cursor.getColumnIndex("daddr");
    int colResource = cursor.getColumnIndex("resource");
    int colDPort = cursor.getColumnIndex("dport");
    int colBlock = cursor.getColumnIndex("block");
    while (cursor.moveToNext()) {
        int uid = cursor.getInt(colUid);
        int version = cursor.getInt(colVersion);
        int protocol = cursor.getInt(colProtocol);
        String daddr = cursor.getString(colDAddr);
        String dresource = cursor.getString(colResource);
        int dport = cursor.getInt(colDPort);
        boolean block = (cursor.getInt(colBlock) > 0);

        // long is 64 bits
        // 0..15 uid
        // 16..31 dport
        // 32..39 protocol
        // 40..43 version
        if (!(protocol == 6 /* TCP */ || protocol == 17 /* UDP */))
            dport = 0;
        long key = (version << 40) | (protocol << 32) | (dport << 16) | uid;

        synchronized (mapUidIPFilters) {
            if (!mapUidIPFilters.containsKey(key))
                mapUidIPFilters.put(key, new HashMap());

            try {
                if (dname != null)
                    Log.i(TAG, "Set filter uid=" + uid + " " + daddr + " " + dresource + "/" + dport + "="
                            + block);
                if (dresource == null) {
                    if (Util.isNumericAddress(daddr))
                        mapUidIPFilters.get(key).put(InetAddress.getByName(daddr), block);
                } else {
                    if (Util.isNumericAddress(dresource))
                        mapUidIPFilters.get(key).put(InetAddress.getByName(dresource), block);
                    else
                        Log.w(TAG, "Address not numeric " + daddr);
                }
            } catch (UnknownHostException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }
        }
    }
    cursor.close();
}

From source file:eu.faircode.adblocker.ServiceSinkhole.java

private Allowed isAddressAllowed(Packet packet) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    packet.allowed = false;/*from   www .  j  a va 2s.co  m*/
    if (prefs.getBoolean("filter", false)) {
        // https://android.googlesource.com/platform/system/core/+/master/include/private/android_filesystem_config.h
        if (packet.uid < 2000 && !last_connected && isSupported(packet.protocol)) {
            // Allow system applications in disconnected state
            packet.allowed = true;
            Log.w(TAG, "Allowing disconnected system " + packet);

        } else if (packet.uid < 2000 && !mapUidKnown.containsKey(packet.uid) && isSupported(packet.protocol)) {
            // Allow unknown system traffic
            packet.allowed = true;
            Log.w(TAG, "Allowing unknown system " + packet);

        } else {
            boolean filtered = false;
            // Only TCP (6) and UDP (17) have port numbers
            int dport = (packet.protocol == 6 || packet.protocol == 17 ? packet.dport : 0);
            long key = (packet.version << 40) | (packet.protocol << 32) | (dport << 16) | packet.uid;

            synchronized (mapUidIPFilters) {
                if (mapUidIPFilters.containsKey(key))
                    try {
                        InetAddress iaddr = InetAddress.getByName(packet.daddr);
                        Map<InetAddress, Boolean> map = mapUidIPFilters.get(key);
                        if (map != null && map.containsKey(iaddr)) {
                            filtered = true;
                            packet.allowed = !map.get(iaddr);
                            Log.i(TAG, "Filtering " + packet);
                        }
                    } catch (UnknownHostException ex) {
                        Log.w(TAG, "Allowed " + ex.toString() + "\n" + Log.getStackTraceString(ex));
                    }

                if (!filtered)
                    packet.allowed = (mapUidAllowed.containsKey(packet.uid) && mapUidAllowed.get(packet.uid));
            }
        }
    }

    Allowed allowed = null;
    if (packet.allowed) {
        if (mapForward.containsKey(packet.dport)) {
            Forward fwd = mapForward.get(packet.dport);
            if (fwd.ruid == packet.uid) {
                allowed = new Allowed();
            } else {
                allowed = new Allowed(fwd.raddr, fwd.rport);
                packet.data = "> " + fwd.raddr + "/" + fwd.rport;
            }
        } else
            allowed = new Allowed();
    }

    if (prefs.getBoolean("log", false) || prefs.getBoolean("log_app", false))
        logPacket(packet);

    return allowed;
}

From source file:org.apache.zeppelin.socket.NotebookServer.java

public boolean checkOrigin(HttpServletRequest request, String origin) {
    try {/* w w w  .  j  a v a 2  s .com*/
        return SecurityUtils.isValidOrigin(origin, ZeppelinConfiguration.create());
    } catch (UnknownHostException e) {
        LOG.error(e.toString(), e);
    } catch (URISyntaxException e) {
        LOG.error(e.toString(), e);
    }
    return false;
}

From source file:com.zhengde163.netguard.ServiceSinkhole.java

private Allowed isAddressAllowed(Packet packet) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    packet.allowed = false;//from   www.  jav  a  2 s  .  co  m
    if (prefs.getBoolean("filter", false)) {
        // https://android.googlesource.com/platform/system/core/+/master/include/private/android_filesystem_config.h
        if (packet.uid < 2000 && !last_connected && isSupported(packet.protocol)) {
            // Allow system applications in disconnected state
            packet.allowed = true;
            Log.w(TAG, "Allowing disconnected system " + packet);

        } else if (packet.uid < 2000 && !mapUidKnown.containsKey(packet.uid) && isSupported(packet.protocol)) {
            // Allow unknown system traffic
            packet.allowed = true;
            Log.w(TAG, "Allowing unknown system " + packet);

        } else {
            boolean filtered = false;
            // Only TCP (6) and UDP (17) have port numbers
            int dport = (packet.protocol == 6 || packet.protocol == 17 ? packet.dport : 0);
            long key = (packet.version << 40) | (packet.protocol << 32) | (dport << 16) | packet.uid;

            synchronized (mapUidIPFilters) {
                if (mapUidIPFilters.containsKey(key))
                    try {
                        InetAddress iaddr = InetAddress.getByName(packet.daddr);
                        Map<InetAddress, Boolean> map = mapUidIPFilters.get(key);
                        if (map != null && map.containsKey(iaddr)) {
                            filtered = true;
                            packet.allowed = !map.get(iaddr);
                            Log.i(TAG, "Filtering " + packet);
                        }
                    } catch (UnknownHostException ex) {
                        Log.w(TAG, "Allowed " + ex.toString() + "\n" + Log.getStackTraceString(ex));
                    }

                if (!filtered)
                    packet.allowed = (mapUidAllowed.containsKey(packet.uid) && mapUidAllowed.get(packet.uid));
            }
        }
    }

    Allowed allowed = null;
    if (packet.allowed) {
        if (mapForward.containsKey(packet.dport)) {
            Forward fwd = mapForward.get(packet.dport);
            if (fwd.ruid == packet.uid) {
                allowed = new Allowed();
            } else {
                allowed = new Allowed(fwd.raddr, fwd.rport);
                packet.data = "> " + fwd.raddr + "/" + fwd.rport;
            }
        } else
            allowed = new Allowed();
    }

    if (prefs.getBoolean("log", false) || prefs.getBoolean("log_app", false))
        logPacket(packet);

    return allowed;
}

From source file:android_network.hetnet.vpn_service.ServiceSinkhole.java

private void prepareUidIPFilters(String dname) {
    lock.writeLock().lock();/*from   w  w w.j  a  va 2 s .  c om*/

    if (dname == null) {
        mapUidIPFilters.clear();

    }

    Cursor cursor = DatabaseHelper.getInstance(ServiceSinkhole.this).getAccessDns(dname);
    int colUid = cursor.getColumnIndex("uid");
    int colVersion = cursor.getColumnIndex("version");
    int colProtocol = cursor.getColumnIndex("protocol");
    int colDAddr = cursor.getColumnIndex("daddr");
    int colResource = cursor.getColumnIndex("resource");
    int colDPort = cursor.getColumnIndex("dport");
    int colBlock = cursor.getColumnIndex("block");
    int colTime = cursor.getColumnIndex("time");
    int colTTL = cursor.getColumnIndex("ttl");
    while (cursor.moveToNext()) {
        int uid = cursor.getInt(colUid);
        int version = cursor.getInt(colVersion);
        int protocol = cursor.getInt(colProtocol);
        String daddr = cursor.getString(colDAddr);
        String dresource = cursor.getString(colResource);
        int dport = cursor.getInt(colDPort);
        boolean block = (cursor.getInt(colBlock) > 0);
        long time = cursor.getLong(colTime);
        long ttl = cursor.getLong(colTTL);

        // long is 64 bits
        // 0..15 uid
        // 16..31 dport
        // 32..39 protocol
        // 40..43 version
        if (!(protocol == 6 /* TCP */ || protocol == 17 /* UDP */))
            dport = 0;
        long key = (version << 40) | (protocol << 32) | (dport << 16) | uid;

        synchronized (mapUidIPFilters) {
            if (!mapUidIPFilters.containsKey(key))
                mapUidIPFilters.put(key, new HashMap());

            try {
                if (dname != null)
                    Log.i(TAG, "Set filter uid=" + uid + " " + daddr + " " + dresource + "/" + dport + "="
                            + block);
                String name = (dresource == null ? daddr : dresource);
                if (Util.isNumericAddress(name)) {
                    InetAddress iname = InetAddress.getByName(name);
                    boolean exists = mapUidIPFilters.get(key).containsKey(iname);
                    if (!exists || !mapUidIPFilters.get(key).get(iname).isBlocked()) {
                        IPRule rule = new IPRule(block, time + ttl);
                        mapUidIPFilters.get(key).put(iname, rule);
                        if (exists)
                            Log.w(TAG, "Address conflict uid=" + uid + " " + daddr + " " + dresource + "/"
                                    + dport);
                    } else if (exists) {
                        mapUidIPFilters.get(key).get(iname).updateExpires(time + ttl);
                        Log.w(TAG, "Address updated uid=" + uid + " " + daddr + " " + dresource + "/" + dport);
                    }
                } else
                    Log.w(TAG, "Address not numeric " + name);
            } catch (UnknownHostException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }
        }
    }
    cursor.close();

    lock.writeLock().unlock();
}

From source file:android_network.hetnet.vpn_service.ServiceSinkhole.java

private Allowed isAddressAllowed(Packet packet) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    lock.readLock().lock();//from w ww  .  j  ava  2 s.c  om

    packet.allowed = false;
    if (prefs.getBoolean("filter", false)) {
        // https://android.googlesource.com/platform/system/core/+/master/include/private/android_filesystem_config.h
        if (packet.uid < 2000 && !last_connected && isSupported(packet.protocol)) {
            // Allow system applications in disconnected state
            packet.allowed = true;
            Log.w(TAG, "Allowing disconnected system " + packet);

        } else if (packet.uid < 2000 && !mapUidKnown.containsKey(packet.uid) && isSupported(packet.protocol)) {
            // Allow unknown system traffic
            packet.allowed = true;
            Log.w(TAG, "Allowing unknown system " + packet);

        } else {
            boolean filtered = false;
            // Only TCP (6) and UDP (17) have port numbers
            int dport = (packet.protocol == 6 || packet.protocol == 17 ? packet.dport : 0);
            long key = (packet.version << 40) | (packet.protocol << 32) | (dport << 16) | packet.uid;

            if (mapUidIPFilters.containsKey(key))
                try {
                    InetAddress iaddr = InetAddress.getByName(packet.daddr);
                    Map<InetAddress, IPRule> map = mapUidIPFilters.get(key);
                    if (map != null && map.containsKey(iaddr)) {
                        IPRule rule = map.get(iaddr);
                        if (rule.isExpired())
                            Log.i(TAG, "DNS expired " + packet);
                        else {
                            filtered = true;
                            packet.allowed = !rule.isBlocked();
                            Log.i(TAG, "Filtering " + packet);
                        }
                    }
                } catch (UnknownHostException ex) {
                    Log.w(TAG, "Allowed " + ex.toString() + "\n" + Log.getStackTraceString(ex));
                }

            if (!filtered)
                packet.allowed = (mapUidAllowed.containsKey(packet.uid) && mapUidAllowed.get(packet.uid));
        }
    }

    Allowed allowed = null;
    if (packet.allowed) {
        if (mapForward.containsKey(packet.dport)) {
            Forward fwd = mapForward.get(packet.dport);
            if (fwd.ruid == packet.uid) {
                allowed = new Allowed();
            } else {
                allowed = new Allowed(fwd.raddr, fwd.rport);
                packet.data = "> " + fwd.raddr + "/" + fwd.rport;
            }
        } else
            allowed = new Allowed();
    }

    lock.readLock().unlock();

    if (prefs.getBoolean("log", false) || prefs.getBoolean("log_app", false))
        logPacket(packet);

    return allowed;
}

From source file:eu.faircode.netguard.ServiceSinkhole.java

private void prepareUidIPFilters(String dname) {
    SharedPreferences lockdown = getSharedPreferences("lockdown", Context.MODE_PRIVATE);

    lock.writeLock().lock();/*from   w ww  . j a  v  a 2 s  . c o  m*/

    if (dname == null) {
        mapUidIPFilters.clear();
        if (!IAB.isPurchased(ActivityPro.SKU_FILTER, ServiceSinkhole.this)) {
            lock.writeLock().unlock();
            return;
        }
    }

    Cursor cursor = DatabaseHelper.getInstance(ServiceSinkhole.this).getAccessDns(dname);
    int colUid = cursor.getColumnIndex("uid");
    int colVersion = cursor.getColumnIndex("version");
    int colProtocol = cursor.getColumnIndex("protocol");
    int colDAddr = cursor.getColumnIndex("daddr");
    int colResource = cursor.getColumnIndex("resource");
    int colDPort = cursor.getColumnIndex("dport");
    int colBlock = cursor.getColumnIndex("block");
    int colTime = cursor.getColumnIndex("time");
    int colTTL = cursor.getColumnIndex("ttl");
    while (cursor.moveToNext()) {
        int uid = cursor.getInt(colUid);
        int version = cursor.getInt(colVersion);
        int protocol = cursor.getInt(colProtocol);
        String daddr = cursor.getString(colDAddr);
        String dresource = cursor.getString(colResource);
        int dport = cursor.getInt(colDPort);
        boolean block = (cursor.getInt(colBlock) > 0);
        long time = cursor.getLong(colTime);
        long ttl = cursor.getLong(colTTL);

        if (isLockedDown(last_metered)) {
            String[] pkg = getPackageManager().getPackagesForUid(uid);
            if (pkg != null && pkg.length > 0) {
                if (!lockdown.getBoolean(pkg[0], false))
                    continue;
            }
        }

        // long is 64 bits
        // 0..15 uid
        // 16..31 dport
        // 32..39 protocol
        // 40..43 version
        if (!(protocol == 6 /* TCP */ || protocol == 17 /* UDP */))
            dport = 0;
        long key = (version << 40) | (protocol << 32) | (dport << 16) | uid;

        synchronized (mapUidIPFilters) {
            if (!mapUidIPFilters.containsKey(key))
                mapUidIPFilters.put(key, new HashMap());

            try {
                if (dname != null)
                    Log.i(TAG, "Set filter uid=" + uid + " " + daddr + " " + dresource + "/" + dport + "="
                            + block);
                String name = (dresource == null ? daddr : dresource);
                if (Util.isNumericAddress(name)) {
                    InetAddress iname = InetAddress.getByName(name);
                    boolean exists = mapUidIPFilters.get(key).containsKey(iname);
                    if (!exists || !mapUidIPFilters.get(key).get(iname).isBlocked()) {
                        IPRule rule = new IPRule(block, time + ttl);
                        mapUidIPFilters.get(key).put(iname, rule);
                        if (exists)
                            Log.w(TAG, "Address conflict uid=" + uid + " " + daddr + " " + dresource + "/"
                                    + dport);
                    } else if (exists) {
                        mapUidIPFilters.get(key).get(iname).updateExpires(time + ttl);
                        Log.w(TAG, "Address updated uid=" + uid + " " + daddr + " " + dresource + "/" + dport);
                    }
                } else
                    Log.w(TAG, "Address not numeric " + name);
            } catch (UnknownHostException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }
        }
    }
    cursor.close();

    lock.writeLock().unlock();
}

From source file:eu.faircode.netguard.ServiceSinkhole.java

private Allowed isAddressAllowed(Packet packet) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    lock.readLock().lock();//from   w w  w .  j  a  v  a 2 s  .com

    packet.allowed = false;
    if (prefs.getBoolean("filter", false)) {
        // https://android.googlesource.com/platform/system/core/+/master/include/private/android_filesystem_config.h
        if (packet.uid < 2000 && !last_connected && isSupported(packet.protocol)) {
            // Allow system applications in disconnected state
            packet.allowed = true;
            Log.w(TAG, "Allowing disconnected system " + packet);

        } else if (packet.uid < 2000 && !mapUidKnown.containsKey(packet.uid) && isSupported(packet.protocol)) {
            // Allow unknown system traffic
            packet.allowed = true;
            Log.w(TAG, "Allowing unknown system " + packet);

        } else {
            boolean filtered = false;
            // Only TCP (6) and UDP (17) have port numbers
            int dport = (packet.protocol == 6 || packet.protocol == 17 ? packet.dport : 0);
            long key = (packet.version << 40) | (packet.protocol << 32) | (dport << 16) | packet.uid;

            if (mapUidIPFilters.containsKey(key))
                try {
                    InetAddress iaddr = InetAddress.getByName(packet.daddr);
                    Map<InetAddress, IPRule> map = mapUidIPFilters.get(key);
                    if (map != null && map.containsKey(iaddr)) {
                        IPRule rule = map.get(iaddr);
                        if (rule.isExpired())
                            Log.i(TAG, "DNS expired " + packet);
                        else {
                            filtered = true;
                            packet.allowed = !rule.isBlocked();
                            Log.i(TAG, "Filtering " + packet);
                        }
                    }
                } catch (UnknownHostException ex) {
                    Log.w(TAG, "Allowed " + ex.toString() + "\n" + Log.getStackTraceString(ex));
                }

            if (!filtered)
                packet.allowed = (mapUidAllowed.containsKey(packet.uid) && mapUidAllowed.get(packet.uid));
        }
    }

    Allowed allowed = null;
    if (packet.allowed) {
        if (mapForward.containsKey(packet.dport)) {
            Forward fwd = mapForward.get(packet.dport);
            if (fwd.ruid == packet.uid) {
                allowed = new Allowed();
            } else {
                allowed = new Allowed(fwd.raddr, fwd.rport);
                packet.data = "> " + fwd.raddr + "/" + fwd.rport;
            }
        } else
            allowed = new Allowed();
    }

    lock.readLock().unlock();

    if (prefs.getBoolean("log", false) || prefs.getBoolean("log_app", false))
        if (packet.protocol != 6 /* TCP */ || !"".equals(packet.flags))
            logPacket(packet);

    return allowed;
}

From source file:com.streamsets.pipeline.stage.destination.cassandra.CassandraTarget.java

@Override
protected List<ConfigIssue> init() {
    List<ConfigIssue> issues = super.init();
    errorRecordHandler = new DefaultErrorRecordHandler(getContext());

    Target.Context context = getContext();
    if (addresses.isEmpty()) {
        issues.add(context.createConfigIssue(Groups.CASSANDRA.name(), "contactNodes", Errors.CASSANDRA_00));
    }/*from   w w  w.  j a  v a  2  s. co m*/

    for (String address : addresses) {
        if (address.isEmpty()) {
            issues.add(context.createConfigIssue(Groups.CASSANDRA.name(), "contactNodes", Errors.CASSANDRA_01));
        }
    }

    contactPoints = new ArrayList<>(addresses.size());
    for (String address : addresses) {
        if (null == address) {
            LOG.warn("A null value was passed in as a contact point.");
            // This isn't valid but InetAddress won't complain so we skip this entry.
            continue;
        }

        try {
            contactPoints.add(InetAddress.getByName(address));
        } catch (UnknownHostException e) {
            issues.add(context.createConfigIssue(Groups.CASSANDRA.name(), "contactNodes", Errors.CASSANDRA_04,
                    address));
        }
    }

    if (contactPoints.size() < 1) {
        issues.add(context.createConfigIssue(Groups.CASSANDRA.name(), "contactNodes", Errors.CASSANDRA_00));
    }

    if (!qualifiedTableName.contains(".")) {
        issues.add(
                context.createConfigIssue(Groups.CASSANDRA.name(), "qualifiedTableName", Errors.CASSANDRA_02));
    } else {
        if (checkCassandraReachable(issues)) {
            List<String> invalidColumns = checkColumnMappings();
            if (invalidColumns.size() != 0) {
                issues.add(context.createConfigIssue(Groups.CASSANDRA.name(), "columnNames",
                        Errors.CASSANDRA_08, Joiner.on(", ").join(invalidColumns)));
            }
        }
    }

    if (issues.isEmpty()) {
        cluster = Cluster.builder().addContactPoints(contactPoints).withCompression(compression).withPort(port)
                // If authentication is disabled on the C* cluster, this method has no effect.
                .withCredentials(username, password).build();

        try {
            session = cluster.connect();

            statementCache = CacheBuilder.newBuilder()
                    // No expiration as prepared statements are good for the entire session.
                    .build(new CacheLoader<SortedSet<String>, PreparedStatement>() {
                        @Override
                        public PreparedStatement load(SortedSet<String> columns) {
                            // The INSERT query we're going to perform (parameterized).
                            SortedSet<String> statementColumns = new TreeSet<>();
                            for (String fieldPath : columnMappings.keySet()) {
                                final String fieldName = fieldPath.replaceAll("/", "");
                                if (columns.contains(fieldName)) {
                                    statementColumns.add(fieldName);
                                }
                            }
                            final String query = String.format("INSERT INTO %s (%s) VALUES (%s);",
                                    qualifiedTableName, Joiner.on(", ").join(statementColumns),
                                    Joiner.on(", ").join(Collections.nCopies(statementColumns.size(), "?")));
                            LOG.trace("Prepared Query: {}", query);
                            return session.prepare(query);
                        }
                    });
        } catch (NoHostAvailableException | AuthenticationException | IllegalStateException e) {
            issues.add(context.createConfigIssue(null, null, Errors.CASSANDRA_03, e.toString()));
        }
    }
    return issues;
}