org.deviceconnect.android.manager.core.util.DConnectUtil.java Source code

Java tutorial

Introduction

Here is the source code for org.deviceconnect.android.manager.core.util.DConnectUtil.java

Source

/*
 DConnectUtil.java
 Copyright (c) 2014 NTT DOCOMO,INC.
 Released under the MIT license
 http://opensource.org/licenses/mit-license.php
 */
package org.deviceconnect.android.manager.core.util;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.v4.content.res.ResourcesCompat;
import android.util.Log;

import org.deviceconnect.android.activity.PermissionUtility;
import org.deviceconnect.android.manager.core.BuildConfig;
import org.deviceconnect.android.manager.core.DConnectSettings;
import org.deviceconnect.android.manager.core.plugin.DevicePlugin;
import org.deviceconnect.message.DConnectMessage;
import org.deviceconnect.message.intent.message.IntentDConnectMessage;
import org.deviceconnect.profile.DConnectProfileConstants;
import org.deviceconnect.utils.JSONUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Locale;
import java.util.Random;
import java.util.UUID;

/**
 * .
 *
 * @author NTT DOCOMO, INC.
 */
public final class DConnectUtil {
    /**
     * ?.
     */
    private static final int MAX_NUM = 10000;

    /**
     * ??.
     */
    private static final int DIGIT = 4;

    /**
     * 10?.
     */
    private static final int DECIMAL = 10;

    /**
     * Defined the permission.
     */
    public static final String[] PERMISSIONS = new String[] { Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE };

    /**
     * .
     * ????private??????
     */
    private DConnectUtil() {
    }

    /**
     * ??.
     *
     * @return 
     */
    public static String createKeyword() {
        StringBuilder builder = new StringBuilder();
        builder.append("DCONNECT-");
        int rand = Math.abs(new Random().nextInt() % MAX_NUM);
        for (int i = 0; i < DIGIT; i++) {
            int r = rand % DECIMAL;
            builder.append(r);
            rand /= DECIMAL;
        }
        return builder.toString();
    }

    /**
     * Device Connect Manager??????.
     *
     * @return Device Connect Manager????
     */
    public static String createName() {
        StringBuilder builder = new StringBuilder();
        builder.append("Manager-");
        int rand = Math.abs(new Random().nextInt() % MAX_NUM);
        for (int i = 0; i < DIGIT; i++) {
            int r = rand % DECIMAL;
            builder.append(r);
            rand /= DECIMAL;
        }
        return builder.toString();
    }

    /**
     * Device Connect Manager????.
     *
     * @return Device Connect Manager??
     */
    public static String createUuid() {
        return UUID.randomUUID().toString();
    }

    /**
     * HttpDConnect???.
     *
     * @param method ??Http
     * @return DConnect
     */
    public static String convertHttpMethod2DConnectMethod(final String method) {
        if (DConnectMessage.METHOD_GET.equalsIgnoreCase(method)) {
            return IntentDConnectMessage.ACTION_GET;
        } else if (DConnectMessage.METHOD_POST.equalsIgnoreCase(method)) {
            return IntentDConnectMessage.ACTION_POST;
        } else if (DConnectMessage.METHOD_PUT.equalsIgnoreCase(method)) {
            return IntentDConnectMessage.ACTION_PUT;
        } else if (DConnectMessage.METHOD_DELETE.equalsIgnoreCase(method)) {
            return IntentDConnectMessage.ACTION_DELETE;
        }
        return null;
    }

    /**
     * ???dConnect???.
     *
     * @param intent 
     * @return dConnect????true, ???false
     */
    public static boolean checkAction(final Intent intent) {
        return intent != null && checkAction(intent.getAction());
    }

    /**
     * ???dConnect???.
     *
     * @param action 
     * @return dConnect????true, ???false
     */
    public static boolean checkAction(final String action) {
        return action != null && (action.equals(IntentDConnectMessage.ACTION_GET)
                || action.equals(IntentDConnectMessage.ACTION_PUT)
                || action.equals(IntentDConnectMessage.ACTION_POST)
                || action.equals(IntentDConnectMessage.ACTION_DELETE));
    }

    public static boolean checkActionResponse(final Intent intent) {
        return intent != null && checkActionResponse(intent.getAction());
    }

    private static boolean checkActionResponse(final String action) {
        return action != null && IntentDConnectMessage.ACTION_RESPONSE.equals(action);
    }

    public static boolean checkActionEvent(final Intent intent) {
        return intent != null && checkActionEvent(intent.getAction());
    }

    private static boolean checkActionEvent(final String action) {
        return action != null && IntentDConnectMessage.ACTION_EVENT.equals(action);
    }

    /**
     * ??URI??.
     *
     * @param settings DeviceConnect
     * @param uri      ??ContentUri
     * @return URI
     */
    private static String createUri(final DConnectSettings settings, final String uri) {
        StringBuilder builder = new StringBuilder();
        builder.append(settings.isSSL() ? "https://" : "http://");
        builder.append(settings.getHost());
        builder.append(":");
        builder.append(settings.getPort());
        builder.append("/gotapi/files");
        builder.append("?uri=");
        try {
            builder.append(URLEncoder.encode(uri, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Failed to convert a uri.");
        }
        return builder.toString();
    }

    /**
     * JSON?????uri??.
     * <p>
     * <p>
     * ??uri?content://??uri????<br/>
     * ???uri?????
     * </p>
     *
     * @param settings DeviceConnect
     * @param root     ??JSONObject
     * @throws JSONException JSON??????
     */
    private static void convertUri(final DConnectSettings settings, final JSONObject root) throws JSONException {
        @SuppressWarnings("unchecked") // Using legacy API
        Iterator<String> it = root.keys();
        while (it.hasNext()) {
            String key = it.next();
            Object value = root.opt(key);
            if (value instanceof String) {
                if (isUriKey(key) && startWithContent((String) value)) {
                    String u = createUri(settings, (String) value);
                    root.put(key, u);
                }
            } else if (value instanceof JSONObject) {
                convertUri(settings, (JSONObject) value);
            } else if (value instanceof JSONArray) {
                JSONArray array = (JSONArray) value;
                int length = array.length();
                for (int i = 0; i < length; i++) {
                    JSONObject json = array.optJSONObject(i);
                    if (json != null) {
                        convertUri(settings, json);
                    }
                }
            }
        }
    }

    private static final String PARAM_URI_POSTFIX = "Uri";

    /**
     * ??? URI ???????.
     * @param key 
     * @return URI ???<code>true</code>. ????????<code>false</code>
     */
    private static boolean isUriKey(final String key) {
        return DConnectProfileConstants.PARAM_URI.equals(key) || key.endsWith(PARAM_URI_POSTFIX);
    }

    /**
     * ??uri?content://?????.
     *
     * @param uri ??uri
     * @return content://????true????false
     */
    private static boolean startWithContent(final String uri) {
        return uri != null && (uri.startsWith("content://"));
    }

    /**
     * Bundle?JSONObject???.
     *
     * @param settings DeviceConnect
     * @param root     JSONObject??????
     * @param b        ??Bundle
     * @throws JSONException JSON????????
     */
    public static void convertBundleToJSON(final DConnectSettings settings, final JSONObject root, final Bundle b)
            throws JSONException {
        JSONUtils.convertBundleToJSON(root, b);
        convertUri(settings, root);
    }

    /**
     * AndroidManifest.xml?versionName??.
     *
     * @param context Context
     * @return versionName
     */
    public static String getVersionName(final Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_ACTIVITIES);
            return packageInfo.versionName;
        } catch (NameNotFoundException e) {
            return "Unknown";
        }
    }

    /**
     * Gets the ip address.
     *
     * @param context Context of application
     * @return Returns ip address
     */
    public static String getIPAddress(final Context context) {
        Context appContext = context.getApplicationContext();
        WifiManager wifiManager = (WifiManager) appContext.getSystemService(Context.WIFI_SERVICE);
        ConnectivityManager cManager = (ConnectivityManager) appContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo network = cManager.getActiveNetworkInfo();
        String en0Ip = null;
        if (network != null) {
            switch (network.getType()) {
            case ConnectivityManager.TYPE_ETHERNET:
                try {
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                            .hasMoreElements();) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                                .hasMoreElements();) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (inetAddress instanceof Inet4Address
                                    && !inetAddress.getHostAddress().equals("127.0.0.1")) {
                                en0Ip = inetAddress.getHostAddress();
                                break;
                            }
                        }
                    }
                } catch (SocketException e) {
                    Log.e("DConnectUtil", "Get Ethernet IP Error", e);
                }
            }
        }

        if (en0Ip != null) {
            return en0Ip;
        } else {
            int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
            return String.format(Locale.getDefault(), "%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff),
                    (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
        }
    }

    /**
     * Checks whether permission allow by user.
     *
     * @param context context of application
     * @return Returns true if permission allow, otherwise false
     */
    public static boolean isPermission(final Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        } else {
            boolean result = true;
            for (int i = 0; i < PERMISSIONS.length; i++) {
                if (context.checkSelfPermission(PERMISSIONS[i]) != PackageManager.PERMISSION_GRANTED) {
                    result = false;
                }
            }
            return result;
        }
    }

    /**
     * ?????.
     *
     * @param context  
     * @param callback ???
     */
    public static void requestPermission(final Context context, final Handler handler,
            final PermissionUtility.PermissionRequestCallback callback) {
        PermissionUtility.requestPermissions(context, handler, PERMISSIONS, callback);
    }

    /**
     * ??Drawable??.
     *
     * @param drawable ??Drawable
     * @return ??Drawable
     */
    public static Drawable convertToGrayScale(final Drawable drawable) {
        Drawable clone = drawable.getConstantState().newDrawable().mutate();
        ColorMatrix matrix = new ColorMatrix();
        matrix.setSaturation(0.2f);
        ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
        clone.setColorFilter(filter);
        return clone;
    }

    /**
     * .
     */
    private static final int MASK = 0xFF;

    /**
     * ??16????.
     *
     * @param buf ????
     * @return 
     */
    private static String hexToString(final byte[] buf) {
        StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < buf.length; i++) {
            hexString.append(Integer.toHexString(MASK & buf[i]));
        }
        return hexString.toString();
    }

    /**
     * ??MD5????.
     * <p>
     * MD5?????????{@code null}??
     * </p>
     *
     * @param s MD5??
     * @return MD5???
     * @throws UnsupportedEncodingException ??????
     * @throws NoSuchAlgorithmException     MD5????????
     */
    public static String toMD5(final String s) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
        digest.update(s.getBytes("ASCII"));
        return hexToString(digest.digest());
    }

    /**
     * ??Context??Doze?????????.
     * <p>
     * Android M ?? OS ????true????
     * </p>
     *
     * @param context 
     * @return Doze????true????false
     */
    public static boolean isDozeMode(final Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        } else {
            PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            return powerManager.isIgnoringBatteryOptimizations(context.getPackageName());
        }
    }

    /**
     * Doze???.
     * <p>
     * Doze???????????<br>
     * Android M ?? OS ????????????
     * </p>
     *
     * @param context 
     */
    public static void startConfirmIgnoreDozeMode(final Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + context.getPackageName()));
            context.startActivity(intent);
        }
    }

    /**
     * Doze??????.
     * <p>
     * Doze???????????<br>
     * Android M ?? OS ????????????
     * </p>
     *
     * @param context 
     */
    public static void startDozeModeSettingActivity(final Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Intent intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }

    /**
     * ??????.
     *
     * @param context 
     * @param plugin
     * @return ??
     */
    public static Drawable loadPluginIcon(final Context context, final DevicePlugin plugin) {
        return loadPluginIcon(context, plugin.getPackageName(), plugin.getPluginIconId());
    }

    /**
     * ??????.
     *
     * @param context     
     * @param packageName ???
     * @param iconId      ?ID
     * @return ??
     */
    public static Drawable loadPluginIcon(final Context context, final String packageName, final Integer iconId) {
        PackageManager pkgMgr = context.getPackageManager();
        Drawable icon;
        if (iconId != null) {
            icon = ResourcesCompat.getDrawable(context.getResources(), iconId, null);
        } else {
            try {
                ApplicationInfo info = pkgMgr.getApplicationInfo(packageName, 0);
                icon = pkgMgr.getApplicationIcon(info.packageName);
            } catch (PackageManager.NameNotFoundException e) {
                icon = null;
                if (BuildConfig.DEBUG) {
                    Log.d("Manager", "Icon is not found.");
                }
            }
        }
        return icon;
    }

    /**
     * ?Intent???????.
     *
     * @param intent ?Intent
     * @return ??
     */
    public static String convertRequestToString(final Intent intent) {
        StringBuilder sb = new StringBuilder();

        String action = intent.getAction();
        String api = intent.getStringExtra("api");
        String profile = intent.getStringExtra("profile");
        String inter = intent.getStringExtra("interface");
        String attr = intent.getStringExtra("attribute");

        if (IntentDConnectMessage.ACTION_GET.equals(action)) {
            sb.append("GET ");
        } else if (IntentDConnectMessage.ACTION_PUT.equals(action)) {
            sb.append("PUT ");
        } else if (IntentDConnectMessage.ACTION_POST.equals(action)) {
            sb.append("POST ");
        } else if (IntentDConnectMessage.ACTION_DELETE.equals(action)) {
            sb.append("DELETE ");
        }

        if (api != null) {
            sb.append("/");
            sb.append(api);
        }
        if (profile != null) {
            sb.append("/");
            sb.append(profile);
        }
        if (inter != null) {
            sb.append("/");
            sb.append(inter);
        }
        if (attr != null) {
            sb.append("/");
            sb.append(attr);
        }

        return sb.toString();
    }
}