Example usage for android.util Log getStackTraceString

List of usage examples for android.util Log getStackTraceString

Introduction

In this page you can find the example usage for android.util Log getStackTraceString.

Prototype

public static String getStackTraceString(Throwable tr) 

Source Link

Document

Handy function to get a loggable stack trace from a Throwable

Usage

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

private void prepareUidIPFilters(String dname) {
    lock.writeLock().lock();//w w  w. j av  a 2  s.  co m

    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:eu.faircode.netguard.ServiceSinkhole.java

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

    lock.writeLock().lock();/*from w ww.  j av  a  2  s  . co  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:com.zhengde163.netguard.ServiceSinkhole.java

private Allowed isAddressAllowed(Packet packet) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    packet.allowed = false;/*from ww  w .  jav  a 2 s  . c  om*/
    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:eu.faircode.netguard.ServiceSinkhole.java

private void stopVPN(ParcelFileDescriptor pfd) {
    Log.i(TAG, "Stopping");
    try {/*from  www  . jav a2s  .  co  m*/
        pfd.close();
    } catch (IOException ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }
}

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  w  w . j a  v  a2 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:com.karura.framework.plugins.utils.ContactAccessorSdk5.java

/**
 * Creates a new contact and stores it in the database
 * /*w  w  w.j ava 2s .  c o m*/
 * @param id
 *            the raw contact id which is required for linking items to the contact
 * @param contact
 *            the contact to be saved
 * @param account
 *            the account to be saved under
 */
private String modifyContact(String id, JSONObject contact, String accountType, String accountName) {
    // Get the RAW_CONTACT_ID which is needed to insert new values in an
    // already existing contact.
    // But not needed to update existing values.
    int rawId = Integer.valueOf(getJsonString(contact, "rawId"));

    // Create a list of attributes to add to the contact database
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    // Add contact type
    ops.add(ContentProviderOperation.newUpdate(ContactsContract.RawContacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType)
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName).build());

    // Modify name
    JSONObject name;
    try {
        String displayName = getJsonString(contact, "displayName");
        name = contact.getJSONObject("name");
        if (displayName != null || name != null) {
            ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(
                            ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                    + "=?",
                            new String[] { id,
                                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE });

            if (displayName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName);
            }

            String familyName = getJsonString(name, "familyName");
            if (familyName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, familyName);
            }
            String middleName = getJsonString(name, "middleName");
            if (middleName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME, middleName);
            }
            String givenName = getJsonString(name, "givenName");
            if (givenName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, givenName);
            }
            String honorificPrefix = getJsonString(name, "honorificPrefix");
            if (honorificPrefix != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.PREFIX, honorificPrefix);
            }
            String honorificSuffix = getJsonString(name, "honorificSuffix");
            if (honorificSuffix != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.SUFFIX, honorificSuffix);
            }

            ops.add(builder.build());
        }
    } catch (JSONException e1) {
        Log.d(LOG_TAG, "Could not get name");
    }

    // Modify phone numbers
    JSONArray phones = null;
    try {
        phones = contact.getJSONArray("phoneNumbers");
        if (phones != null) {
            // Delete all the phones
            if (phones.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a phone
            else {
                for (int i = 0; i < phones.length(); i++) {
                    JSONObject phone = (JSONObject) phones.get(i);
                    String phoneId = getJsonString(phone, "id");
                    // This is a new phone so do a DB insert
                    if (phoneId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                getJsonString(phone, "value"));
                        contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE,
                                getPhoneType(getJsonString(phone, "type")));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing phone so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Phone._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { phoneId,
                                                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                        getJsonString(phone, "value"))
                                .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                                        getPhoneType(getJsonString(phone, "type")))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get phone numbers");
    }

    // Modify emails
    JSONArray emails = null;
    try {
        emails = contact.getJSONArray("emails");
        if (emails != null) {
            // Delete all the emails
            if (emails.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a email
            else {
                for (int i = 0; i < emails.length(); i++) {
                    JSONObject email = (JSONObject) emails.get(i);
                    String emailId = getJsonString(email, "id");
                    // This is a new email so do a DB insert
                    if (emailId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Email.DATA,
                                getJsonString(email, "value"));
                        contentValues.put(ContactsContract.CommonDataKinds.Email.TYPE,
                                getContactType(getJsonString(email, "type")));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing email so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Email._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { emailId,
                                                ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.Email.DATA,
                                        getJsonString(email, "value"))
                                .withValue(ContactsContract.CommonDataKinds.Email.TYPE,
                                        getContactType(getJsonString(email, "type")))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get emails");
    }

    // Modify addresses
    JSONArray addresses = null;
    try {
        addresses = contact.getJSONArray("addresses");
        if (addresses != null) {
            // Delete all the addresses
            if (addresses.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
                        .withSelection(
                                ContactsContract.Data.RAW_CONTACT_ID + "=? AND "
                                        + ContactsContract.Data.MIMETYPE + "=?",
                                new String[] { "" + rawId,
                                        ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a address
            else {
                for (int i = 0; i < addresses.length(); i++) {
                    JSONObject address = (JSONObject) addresses.get(i);
                    String addressId = getJsonString(address, "id");
                    // This is a new address so do a DB insert
                    if (addressId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.TYPE,
                                getAddressType(getJsonString(address, "type")));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS,
                                getJsonString(address, "formatted"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
                                getJsonString(address, "streetAddress"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
                                getJsonString(address, "locality"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
                                getJsonString(address, "region"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
                                getJsonString(address, "postalCode"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
                                getJsonString(address, "country"));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing address so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.StructuredPostal._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { addressId,
                                                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE,
                                        getAddressType(getJsonString(address, "type")))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS,
                                        getJsonString(address, "formatted"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
                                        getJsonString(address, "streetAddress"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
                                        getJsonString(address, "locality"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
                                        getJsonString(address, "region"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
                                        getJsonString(address, "postalCode"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
                                        getJsonString(address, "country"))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get addresses");
    }

    // Modify organizations
    JSONArray organizations = null;
    try {
        organizations = contact.getJSONArray("organizations");
        if (organizations != null) {
            // Delete all the organizations
            if (organizations.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
                        .withSelection(
                                ContactsContract.Data.RAW_CONTACT_ID + "=? AND "
                                        + ContactsContract.Data.MIMETYPE + "=?",
                                new String[] { "" + rawId,
                                        ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a organization
            else {
                for (int i = 0; i < organizations.length(); i++) {
                    JSONObject org = (JSONObject) organizations.get(i);
                    String orgId = getJsonString(org, "id");
                    // This is a new organization so do a DB insert
                    if (orgId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Organization.TYPE,
                                getOrgType(getJsonString(org, "type")));
                        contentValues.put(ContactsContract.CommonDataKinds.Organization.DEPARTMENT,
                                getJsonString(org, "department"));
                        contentValues.put(ContactsContract.CommonDataKinds.Organization.COMPANY,
                                getJsonString(org, "name"));
                        contentValues.put(ContactsContract.CommonDataKinds.Organization.TITLE,
                                getJsonString(org, "title"));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing organization so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Organization._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { orgId,
                                                ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.Organization.TYPE,
                                        getOrgType(getJsonString(org, "type")))
                                .withValue(ContactsContract.CommonDataKinds.Organization.DEPARTMENT,
                                        getJsonString(org, "department"))
                                .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY,
                                        getJsonString(org, "name"))
                                .withValue(ContactsContract.CommonDataKinds.Organization.TITLE,
                                        getJsonString(org, "title"))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get organizations");
    }

    // Modify IMs
    JSONArray ims = null;
    try {
        ims = contact.getJSONArray("ims");
        if (ims != null) {
            // Delete all the ims
            if (ims.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a im
            else {
                for (int i = 0; i < ims.length(); i++) {
                    JSONObject im = (JSONObject) ims.get(i);
                    String imId = getJsonString(im, "id");
                    // This is a new IM so do a DB insert
                    if (imId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"));
                        contentValues.put(ContactsContract.CommonDataKinds.Im.TYPE,
                                getImType(getJsonString(im, "type")));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing IM so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Im._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { imId,
                                                ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"))
                                .withValue(ContactsContract.CommonDataKinds.Im.TYPE,
                                        getContactType(getJsonString(im, "type")))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get emails");
    }

    // Modify note
    String note = getJsonString(contact, "note");
    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
            .withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
                    new String[] { id, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE })
            .withValue(ContactsContract.CommonDataKinds.Note.NOTE, note).build());

    // Modify nickname
    String nickname = getJsonString(contact, "nickname");
    if (nickname != null) {
        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(
                        ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
                        new String[] { id, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE })
                .withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname).build());
    }

    // Modify urls
    JSONArray websites = null;
    try {
        websites = contact.getJSONArray("urls");
        if (websites != null) {
            // Delete all the websites
            if (websites.length() == 0) {
                Log.d(LOG_TAG, "This means we should be deleting all the phone numbers.");
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a website
            else {
                for (int i = 0; i < websites.length(); i++) {
                    JSONObject website = (JSONObject) websites.get(i);
                    String websiteId = getJsonString(website, "id");
                    // This is a new website so do a DB insert
                    if (websiteId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Website.DATA,
                                getJsonString(website, "value"));
                        contentValues.put(ContactsContract.CommonDataKinds.Website.TYPE,
                                getContactType(getJsonString(website, "type")));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing website so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Website._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { websiteId,
                                                ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.Website.DATA,
                                        getJsonString(website, "value"))
                                .withValue(ContactsContract.CommonDataKinds.Website.TYPE,
                                        getContactType(getJsonString(website, "type")))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get websites");
    }

    // Modify birthday
    String birthday = getJsonString(contact, "birthday");
    if (birthday != null) {
        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(
                        ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=? AND " + ContactsContract.CommonDataKinds.Event.TYPE + "=?",
                        new String[] { id, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE,
                                new String("" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY) })
                .withValue(ContactsContract.CommonDataKinds.Event.TYPE,
                        ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY)
                .withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthday).build());
    }

    // Modify photos
    JSONArray photos = null;
    try {
        photos = contact.getJSONArray("photos");
        if (photos != null) {
            // Delete all the photos
            if (photos.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a photo
            else {
                for (int i = 0; i < photos.length(); i++) {
                    JSONObject photo = (JSONObject) photos.get(i);
                    String photoId = getJsonString(photo, "id");
                    byte[] bytes = getPhotoBytes(getJsonString(photo, "value"));
                    // This is a new photo so do a DB insert
                    if (photoId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
                        contentValues.put(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes);

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing photo so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Photo._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { photoId,
                                                ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
                                .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes).build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get photos");
    }

    boolean retVal = true;

    // Modify contact
    try {
        getContext().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (RemoteException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        Log.e(LOG_TAG, Log.getStackTraceString(e), e);
        retVal = false;
    } catch (OperationApplicationException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        Log.e(LOG_TAG, Log.getStackTraceString(e), e);
        retVal = false;
    }

    // if the save was a success return the contact ID
    if (retVal) {
        return id;
    } else {
        return null;
    }
}

From source file:com.parttime.IM.ChatActivity.java

public void getGroupApliantResult(final String id) {
    try {/*  w  ww. jav a 2  s .c  om*/
        new GroupSettingRequest().getUserList(id, queue, new DefaultCallback() {
            @Override
            public void success(Object obj) {
                super.success(obj);
                if (obj instanceof GroupSettingRequest.AppliantResult) {
                    GroupSettingRequest.AppliantResult result = (GroupSettingRequest.AppliantResult) obj;
                    List<GroupSettingRequest.UserVO> userList = result.userList;
                    adapter.refresh();
                }
            }
        });
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }

}

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

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

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

    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:eu.faircode.adblocker.ServiceSinkhole.java

@Override
public void onDestroy() {
    Log.i(TAG, "Destroy");

    commandLooper.quit();//from   w w  w. j  a  va 2  s . c  o m
    logLooper.quit();
    statsLooper.quit();

    unregisterReceiver(interactiveStateReceiver);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        unregisterReceiver(powerSaveReceiver);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
        unregisterReceiver(userReceiver);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        unregisterReceiver(idleStateReceiver);
    unregisterReceiver(connectivityChangedReceiver);
    unregisterReceiver(packageAddedReceiver);

    if (phone_state) {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (tm != null) {
            tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
            phone_state = false;
        }
    }

    if (subscriptionsChangedListener != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        SubscriptionManager sm = SubscriptionManager.from(this);
        sm.removeOnSubscriptionsChangedListener(
                (SubscriptionManager.OnSubscriptionsChangedListener) subscriptionsChangedListener);
        subscriptionsChangedListener = null;
    }

    try {
        if (vpn != null) {
            stopNative(vpn, true, true);
            stopVPN(vpn);
            vpn = null;
            unprepare();
        }
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }

    jni_done();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.unregisterOnSharedPreferenceChangeListener(this);

    super.onDestroy();
}

From source file:org.apache.cordova.ContactAccessorSdk5.java

/**
 * Creates a new contact and stores it in the database
 *
 * @param id the raw contact id which is required for linking items to the contact
 * @param contact the contact to be saved
 * @param account the account to be saved under
 *//*  w w  w . j av  a2s . c om*/
private String modifyContact(String id, JSONObject contact, String accountType, String accountName) {
    // Get the RAW_CONTACT_ID which is needed to insert new values in an already existing contact.
    // But not needed to update existing values.
    int rawId = (new Integer(getJsonString(contact, "rawId"))).intValue();

    // Create a list of attributes to add to the contact database
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    //Add contact type
    ops.add(ContentProviderOperation.newUpdate(ContactsContract.RawContacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType)
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName).build());

    // Modify name
    JSONObject name;
    try {
        String displayName = getJsonString(contact, "displayName");
        name = contact.getJSONObject("name");
        if (displayName != null || name != null) {
            ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(
                            ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                    + "=?",
                            new String[] { id,
                                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE });

            if (displayName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName);
            }

            String familyName = getJsonString(name, "familyName");
            if (familyName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, familyName);
            }
            String middleName = getJsonString(name, "middleName");
            if (middleName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME, middleName);
            }
            String givenName = getJsonString(name, "givenName");
            if (givenName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, givenName);
            }
            String honorificPrefix = getJsonString(name, "honorificPrefix");
            if (honorificPrefix != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.PREFIX, honorificPrefix);
            }
            String honorificSuffix = getJsonString(name, "honorificSuffix");
            if (honorificSuffix != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.SUFFIX, honorificSuffix);
            }

            ops.add(builder.build());
        }
    } catch (JSONException e1) {
        Log.d(LOG_TAG, "Could not get name");
    }

    // Modify phone numbers
    JSONArray phones = null;
    try {
        phones = contact.getJSONArray("phoneNumbers");
        if (phones != null) {
            // Delete all the phones
            if (phones.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a phone
            else {
                for (int i = 0; i < phones.length(); i++) {
                    JSONObject phone = (JSONObject) phones.get(i);
                    String phoneId = getJsonString(phone, "id");
                    // This is a new phone so do a DB insert
                    if (phoneId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                getJsonString(phone, "value"));
                        contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE,
                                getPhoneType(getJsonString(phone, "type")));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing phone so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Phone._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { phoneId,
                                                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                        getJsonString(phone, "value"))
                                .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                                        getPhoneType(getJsonString(phone, "type")))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get phone numbers");
    }

    // Modify emails
    JSONArray emails = null;
    try {
        emails = contact.getJSONArray("emails");
        if (emails != null) {
            // Delete all the emails
            if (emails.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a email
            else {
                for (int i = 0; i < emails.length(); i++) {
                    JSONObject email = (JSONObject) emails.get(i);
                    String emailId = getJsonString(email, "id");
                    // This is a new email so do a DB insert
                    if (emailId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Email.DATA,
                                getJsonString(email, "value"));
                        contentValues.put(ContactsContract.CommonDataKinds.Email.TYPE,
                                getContactType(getJsonString(email, "type")));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing email so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Email._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { emailId,
                                                ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.Email.DATA,
                                        getJsonString(email, "value"))
                                .withValue(ContactsContract.CommonDataKinds.Email.TYPE,
                                        getContactType(getJsonString(email, "type")))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get emails");
    }

    // Modify addresses
    JSONArray addresses = null;
    try {
        addresses = contact.getJSONArray("addresses");
        if (addresses != null) {
            // Delete all the addresses
            if (addresses.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
                        .withSelection(
                                ContactsContract.Data.RAW_CONTACT_ID + "=? AND "
                                        + ContactsContract.Data.MIMETYPE + "=?",
                                new String[] { "" + rawId,
                                        ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a address
            else {
                for (int i = 0; i < addresses.length(); i++) {
                    JSONObject address = (JSONObject) addresses.get(i);
                    String addressId = getJsonString(address, "id");
                    // This is a new address so do a DB insert
                    if (addressId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.TYPE,
                                getAddressType(getJsonString(address, "type")));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS,
                                getJsonString(address, "formatted"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
                                getJsonString(address, "streetAddress"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
                                getJsonString(address, "locality"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
                                getJsonString(address, "region"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
                                getJsonString(address, "postalCode"));
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
                                getJsonString(address, "country"));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing address so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.StructuredPostal._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { addressId,
                                                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE,
                                        getAddressType(getJsonString(address, "type")))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS,
                                        getJsonString(address, "formatted"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
                                        getJsonString(address, "streetAddress"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
                                        getJsonString(address, "locality"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
                                        getJsonString(address, "region"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
                                        getJsonString(address, "postalCode"))
                                .withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
                                        getJsonString(address, "country"))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get addresses");
    }

    // Modify organizations
    JSONArray organizations = null;
    try {
        organizations = contact.getJSONArray("organizations");
        if (organizations != null) {
            // Delete all the organizations
            if (organizations.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
                        .withSelection(
                                ContactsContract.Data.RAW_CONTACT_ID + "=? AND "
                                        + ContactsContract.Data.MIMETYPE + "=?",
                                new String[] { "" + rawId,
                                        ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a organization
            else {
                for (int i = 0; i < organizations.length(); i++) {
                    JSONObject org = (JSONObject) organizations.get(i);
                    String orgId = getJsonString(org, "id");
                    // This is a new organization so do a DB insert
                    if (orgId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Organization.TYPE,
                                getOrgType(getJsonString(org, "type")));
                        contentValues.put(ContactsContract.CommonDataKinds.Organization.DEPARTMENT,
                                getJsonString(org, "department"));
                        contentValues.put(ContactsContract.CommonDataKinds.Organization.COMPANY,
                                getJsonString(org, "name"));
                        contentValues.put(ContactsContract.CommonDataKinds.Organization.TITLE,
                                getJsonString(org, "title"));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing organization so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Organization._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { orgId,
                                                ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.Organization.TYPE,
                                        getOrgType(getJsonString(org, "type")))
                                .withValue(ContactsContract.CommonDataKinds.Organization.DEPARTMENT,
                                        getJsonString(org, "department"))
                                .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY,
                                        getJsonString(org, "name"))
                                .withValue(ContactsContract.CommonDataKinds.Organization.TITLE,
                                        getJsonString(org, "title"))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get organizations");
    }

    // Modify IMs
    JSONArray ims = null;
    try {
        ims = contact.getJSONArray("ims");
        if (ims != null) {
            // Delete all the ims
            if (ims.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a im
            else {
                for (int i = 0; i < ims.length(); i++) {
                    JSONObject im = (JSONObject) ims.get(i);
                    String imId = getJsonString(im, "id");
                    // This is a new IM so do a DB insert
                    if (imId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"));
                        contentValues.put(ContactsContract.CommonDataKinds.Im.TYPE,
                                getImType(getJsonString(im, "type")));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing IM so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Im._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { imId,
                                                ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"))
                                .withValue(ContactsContract.CommonDataKinds.Im.TYPE,
                                        getContactType(getJsonString(im, "type")))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get emails");
    }

    // Modify note
    String note = getJsonString(contact, "note");
    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
            .withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
                    new String[] { id, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE })
            .withValue(ContactsContract.CommonDataKinds.Note.NOTE, note).build());

    // Modify nickname
    String nickname = getJsonString(contact, "nickname");
    if (nickname != null) {
        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(
                        ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
                        new String[] { id, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE })
                .withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname).build());
    }

    // Modify urls
    JSONArray websites = null;
    try {
        websites = contact.getJSONArray("urls");
        if (websites != null) {
            // Delete all the websites
            if (websites.length() == 0) {
                Log.d(LOG_TAG, "This means we should be deleting all the phone numbers.");
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a website
            else {
                for (int i = 0; i < websites.length(); i++) {
                    JSONObject website = (JSONObject) websites.get(i);
                    String websiteId = getJsonString(website, "id");
                    // This is a new website so do a DB insert
                    if (websiteId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.CommonDataKinds.Website.DATA,
                                getJsonString(website, "value"));
                        contentValues.put(ContactsContract.CommonDataKinds.Website.TYPE,
                                getContactType(getJsonString(website, "type")));

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing website so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Website._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { websiteId,
                                                ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.CommonDataKinds.Website.DATA,
                                        getJsonString(website, "value"))
                                .withValue(ContactsContract.CommonDataKinds.Website.TYPE,
                                        getContactType(getJsonString(website, "type")))
                                .build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get websites");
    }

    // Modify birthday
    String birthday = getJsonString(contact, "birthday");
    if (birthday != null) {
        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(
                        ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=? AND " + ContactsContract.CommonDataKinds.Event.TYPE + "=?",
                        new String[] { id, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE,
                                new String("" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY) })
                .withValue(ContactsContract.CommonDataKinds.Event.TYPE,
                        ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY)
                .withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthday).build());
    }

    // Modify photos
    JSONArray photos = null;
    try {
        photos = contact.getJSONArray("photos");
        if (photos != null) {
            // Delete all the photos
            if (photos.length() == 0) {
                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(
                        ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=?",
                        new String[] { "" + rawId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE })
                        .build());
            }
            // Modify or add a photo
            else {
                for (int i = 0; i < photos.length(); i++) {
                    JSONObject photo = (JSONObject) photos.get(i);
                    String photoId = getJsonString(photo, "id");
                    byte[] bytes = getPhotoBytes(getJsonString(photo, "value"));
                    // This is a new photo so do a DB insert
                    if (photoId == null) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                        contentValues.put(ContactsContract.Data.MIMETYPE,
                                ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
                        contentValues.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
                        contentValues.put(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes);

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValues(contentValues).build());
                    }
                    // This is an existing photo so do a DB update
                    else {
                        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                                .withSelection(
                                        ContactsContract.CommonDataKinds.Photo._ID + "=? AND "
                                                + ContactsContract.Data.MIMETYPE + "=?",
                                        new String[] { photoId,
                                                ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE })
                                .withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
                                .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes).build());
                    }
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get photos");
    }

    boolean retVal = true;

    //Modify contact
    try {
        mApp.getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (RemoteException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        Log.e(LOG_TAG, Log.getStackTraceString(e), e);
        retVal = false;
    } catch (OperationApplicationException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        Log.e(LOG_TAG, Log.getStackTraceString(e), e);
        retVal = false;
    }

    // if the save was a success return the contact ID
    if (retVal) {
        return id;
    } else {
        return null;
    }
}