Search in sources :

Example 1 with MqttData

use of org.flyve.mdm.agent.data.database.MqttData in project android-mdm-agent by flyve-mdm.

the class PoliciesAsyncTask method sendStatusbyHttp.

public static void sendStatusbyHttp(Context context, boolean status) {
    try {
        JSONObject jsonPayload = new JSONObject();
        jsonPayload.put("is_online", status);
        JSONObject jsonInput = new JSONObject();
        jsonInput.put("input", jsonPayload);
        String payload = jsonInput.toString();
        Routes routes = new Routes(context);
        MqttData cache = new MqttData(context);
        String url = routes.pluginFlyvemdmAgent(cache.getAgentId());
        pluginHttpResponse(context, url, payload);
    } catch (Exception ex) {
        Helpers.storeLog("fcm", "Error sending status http", ex.getMessage());
    }
}
Also used : MqttData(org.flyve.mdm.agent.data.database.MqttData) JSONObject(org.json.JSONObject) Routes(org.flyve.mdm.agent.core.Routes)

Example 2 with MqttData

use of org.flyve.mdm.agent.data.database.MqttData in project android-mdm-agent by flyve-mdm.

the class ConnectionHTTP method sendHttpResponsePolicies.

public static void sendHttpResponsePolicies(final Context context, final String taskId, final String data, final String sessionToken, final DataCallback callback) {
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                Routes routes = new Routes(context);
                MqttData cache = new MqttData(context);
                String url = routes.PluginFlyvemdmTaskstatusSearch(cache.getAgentId(), taskId);
                // First step get the taskstatus_id
                URL dataURL = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) dataURL.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(timeout);
                conn.setReadTimeout(readtimeout);
                HashMap<String, String> header = new HashMap();
                header.put("Content-Type", "application/json");
                header.put("Session-Token", sessionToken);
                StringBuilder logHeader = new StringBuilder();
                if (header != null) {
                    for (Map.Entry<String, String> entry : header.entrySet()) {
                        logHeader.append("- " + entry.getKey() + " : " + entry.getValue() + "\n");
                        conn.setRequestProperty(entry.getKey(), entry.getValue());
                    }
                } else {
                    logHeader.append("Empty");
                }
                if (conn.getResponseCode() >= 400) {
                    InputStream is = conn.getErrorStream();
                    final String result = inputStreamToString(is);
                    ConnectionHTTP.runOnUI(new Runnable() {

                        public void run() {
                            callback.callback(result);
                        }
                    });
                    return;
                }
                InputStream is = conn.getInputStream();
                final String requestResponse = inputStreamToString(is);
                String taskStatusId = "";
                try {
                    JSONObject objResponse = new JSONObject(requestResponse);
                    JSONArray arrayData = objResponse.getJSONArray("data");
                    taskStatusId = arrayData.getJSONObject(0).getString("2");
                } catch (Exception ex) {
                    FlyveLog.e(ConnectionHTTP.class.getClass().getName() + ", getWebData", ex.getClass() + " : " + ex.getMessage() + " Data : " + data + "Route : " + url);
                    return;
                }
                String response = "\n URL:\n" + url + "\n\n Method:\n" + conn.getRequestMethod() + "\n\n Code:\n" + conn.getResponseCode() + " " + conn.getResponseMessage() + "\n\n Header:\n" + logHeader + "\n\n Data:\n" + data + "\n\n Response:\n" + requestResponse + "\n\n";
                LogDebug(response);
                try {
                    // second step update the status task
                    url = routes.PluginFlyvemdmTaskstatus(taskStatusId);
                    dataURL = new URL(url);
                    conn = (HttpURLConnection) dataURL.openConnection();
                    conn.setRequestMethod("PUT");
                    conn.setConnectTimeout(timeout);
                    conn.setReadTimeout(readtimeout);
                    header = new HashMap();
                    header.put("Content-Type", "application/json");
                    header.put("Session-Token", sessionToken);
                    logHeader = new StringBuilder();
                    if (header != null) {
                        for (Map.Entry<String, String> entry : header.entrySet()) {
                            logHeader.append("- " + entry.getKey() + " : " + entry.getValue() + "\n");
                            conn.setRequestProperty(entry.getKey(), entry.getValue());
                        }
                    } else {
                        logHeader.append("Empty");
                    }
                    // Send post request
                    conn.setDoOutput(true);
                    DataOutputStream os = new DataOutputStream(conn.getOutputStream());
                    os.writeBytes(data);
                    os.flush();
                    os.close();
                    if (conn.getResponseCode() >= 400) {
                        is = conn.getErrorStream();
                        final String result = inputStreamToString(is);
                        ConnectionHTTP.runOnUI(new Runnable() {

                            public void run() {
                                callback.callback(result);
                            }
                        });
                        return;
                    }
                    is = conn.getInputStream();
                    final String requestResponsePut = inputStreamToString(is);
                    response = "\n URL:\n" + url + "\n\n Method:\n" + conn.getRequestMethod() + "\n\n Code:\n" + conn.getResponseCode() + " " + conn.getResponseMessage() + "\n\n Header:\n" + logHeader + "\n\n Data:\n" + data + "\n\n Response:\n" + requestResponse + "\n\n";
                    LogDebug(response);
                    ConnectionHTTP.runOnUI(new Runnable() {

                        public void run() {
                            callback.callback(requestResponsePut);
                        }
                    });
                } catch (final Exception ex) {
                    ConnectionHTTP.runOnUI(new Runnable() {

                        public void run() {
                            callback.callback(ex.getMessage());
                        }
                    });
                }
            } catch (final Exception ex) {
                ConnectionHTTP.runOnUI(new Runnable() {

                    public void run() {
                        callback.callback(EXCEPTION_HTTP + ex.getMessage());
                        FlyveLog.e(ConnectionHTTP.class.getClass().getName() + ", getWebData", ex.getClass() + " : " + ex.getMessage());
                    }
                });
            }
        }
    });
    t.start();
}
Also used : MqttData(org.flyve.mdm.agent.data.database.MqttData) HashMap(java.util.HashMap) InputStream(java.io.InputStream) DataOutputStream(java.io.DataOutputStream) JSONArray(org.json.JSONArray) Routes(org.flyve.mdm.agent.core.Routes) URL(java.net.URL) IOException(java.io.IOException) HttpURLConnection(java.net.HttpURLConnection) JSONObject(org.json.JSONObject)

Example 3 with MqttData

use of org.flyve.mdm.agent.data.database.MqttData in project android-mdm-agent by flyve-mdm.

the class StartEnrollmentActivity method onCreate.

/**
 * Called when the activity is starting
 * It shows the UI to start the enrollment
 * @param savedInstanceState if the activity is being re-initialized, it contains the data it most recently supplied
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start_enrollment);
    sendBroadcast();
    presenter = new DeeplinkPresenter(this);
    // check if broker is on cache open the main activity
    MqttData cache = new MqttData(StartEnrollmentActivity.this);
    if (!cache.getBroker().isEmpty()) {
        openMain();
    }
    TextView txtIntro = findViewById(R.id.txtIntro);
    txtIntro.setText(Html.fromHtml(StartEnrollmentActivity.this.getResources().getString(R.string.walkthrough_step_1)));
    txtIntro.setMovementMethod(LinkMovementMethod.getInstance());
    txtMessage = findViewById(R.id.txtMessage);
    txtTitle = findViewById(R.id.txtTitle);
    pb = findViewById(R.id.progressBar);
    // get the deeplink
    String deeplink = "";
    Intent intent = getIntent();
    Uri data = null;
    // come from QR scan
    Bundle bundle = intent.getExtras();
    if (bundle != null) {
        String str = bundle.getString("data");
        if (str != null) {
            data = Uri.parse(str);
        }
    }
    // come from deeplink
    if (data == null) {
        data = intent.getData();
    }
    try {
        deeplink = data.getQueryParameter("data");
    } catch (Exception ex) {
        presenter.showSnackError(CommonErrorType.DEEPLINK_GETQUERYPARAMETER, ex.getMessage());
    }
    TextView txtVersion = findViewById(R.id.txtVersion);
    txtVersion.setText(MDMAgent.getCompleteVersion());
    presenter.lint(StartEnrollmentActivity.this, deeplink);
    btnEnroll = findViewById(R.id.btnEnroll);
    btnEnroll.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (OptionsEnrollmentActivity.needOptions()) {
                Intent miIntent = new Intent(StartEnrollmentActivity.this, OptionsEnrollmentActivity.class);
                StartEnrollmentActivity.this.startActivity(miIntent);
                StartEnrollmentActivity.this.finish();
            } else {
                Intent miIntent = new Intent(StartEnrollmentActivity.this, PermissionEnrollmentActivity.class);
                StartEnrollmentActivity.this.startActivity(miIntent);
                StartEnrollmentActivity.this.finish();
            }
        }
    });
}
Also used : MqttData(org.flyve.mdm.agent.data.database.MqttData) Bundle(android.os.Bundle) Intent(android.content.Intent) Uri(android.net.Uri) TextView(android.widget.TextView) View(android.view.View) TextView(android.widget.TextView) DeeplinkPresenter(org.flyve.mdm.agent.core.deeplink.DeeplinkPresenter)

Example 4 with MqttData

use of org.flyve.mdm.agent.data.database.MqttData in project android-mdm-agent by flyve-mdm.

the class EnrollmentModel method enroll.

@Override
public void enroll(final Activity activity, final List<UserData.EmailsData> arrEmails, final String firstName, final String lastName, final String phone, final String phone2, final String mobilePhone, final String inventory, final String photo, final String language, final String administrativeNumber) {
    StringBuilder errMsg = new StringBuilder(activity.getResources().getString(R.string.validate_error));
    boolean allow = true;
    Helpers.hideKeyboard(activity);
    if (arrEmails.isEmpty() || arrEmails.get(0).getEmail().equals("")) {
        errMsg.append(activity.getResources().getString(R.string.validate_email_at_least_one));
        allow = false;
    }
    if (firstName.trim().equals("")) {
        errMsg.append(activity.getResources().getString(R.string.validate_first_name));
        allow = false;
    }
    if (lastName.trim().equals("")) {
        errMsg.append(activity.getResources().getString(R.string.validate_last_name));
        allow = false;
    }
    if (inventory.contains("fail")) {
        errMsg.append(activity.getResources().getString(R.string.validate_inventory));
        allow = false;
    }
    // inventory running
    if (inventory.equals("")) {
        errMsg.append(activity.getResources().getString(R.string.inventory_not_exists));
        allow = false;
    }
    if (!allow) {
        presenter.showSnackError(CommonErrorType.ENROLLMENT_FIELD_VALIDATION, activity.getResources().getString(R.string.validate_check_details));
        presenter.showDetailError(CommonErrorType.ENROLLMENT_FIELD_VALIDATION, errMsg.toString());
        return;
    }
    try {
        AndroidCryptoProvider csr = new AndroidCryptoProvider(activity);
        String requestCSR = "";
        if (csr.getlCsr() != null) {
            requestCSR = URLEncoder.encode(csr.getlCsr(), "UTF-8");
        }
        MqttData cache = new MqttData(activity);
        String invitationToken = cache.getInvitationToken();
        JSONObject payload = new JSONObject();
        String mInventory = Helpers.base64encode(inventory.trim());
        // get first email
        payload.put("_email", arrEmails.get(0).getEmail());
        payload.put("_invitation_token", invitationToken);
        payload.put("_serial", Helpers.getDeviceSerial());
        payload.put("_uuid", new Hardware(activity).getUUID());
        payload.put("csr", requestCSR);
        payload.put("firstname", firstName);
        payload.put("lastname", lastName);
        payload.put("phone", phone);
        payload.put("version", BuildConfig.VERSION_NAME);
        payload.put("type", "android");
        payload.put("has_system_permission", Helpers.isSystemApp(activity));
        payload.put("inventory", mInventory);
        // could be mqtt or fcm
        payload.put("notification_type", "mqtt");
        // this is the token get from fcm register
        payload.put("notification_token", "");
        FlyveLog.d(mInventory);
        EnrollmentHelper enroll = new EnrollmentHelper(activity);
        enroll.enrollment(payload, new EnrollmentHelper.EnrollCallBack() {

            @Override
            public void onSuccess(String data) {
                // -------------------------------
                // Store user information
                // -------------------------------
                UserData userData = new UserData(activity);
                userData.setFirstName(firstName);
                userData.setLastName(lastName);
                userData.setEmails(arrEmails);
                userData.setPicture(photo);
                userData.setLanguage(language);
                userData.setAdministrativeNumber(administrativeNumber);
                // -------------------------------
                // Remove Deeplink information
                // -------------------------------
                MqttData cache = new MqttData(activity);
                cache.setInvitationToken("");
                presenter.enrollSuccess();
            }

            @Override
            public void onError(int type, String error) {
                presenter.showSnackError(type, error);
            }
        });
    } catch (Exception ex) {
        presenter.showSnackError(CommonErrorType.ENROLLMENT_REQUEST_EXCEPTION, ex.getMessage());
    }
}
Also used : MqttData(org.flyve.mdm.agent.data.database.MqttData) UserData(org.flyve.mdm.agent.data.localstorage.UserData) AndroidCryptoProvider(org.flyve.mdm.agent.security.AndroidCryptoProvider) JSONObject(org.json.JSONObject) Hardware(org.flyve.inventory.categories.Hardware)

Example 5 with MqttData

use of org.flyve.mdm.agent.data.database.MqttData in project android-mdm-agent by flyve-mdm.

the class MqttModel method connect.

@Override
public void connect(final Context context, final MqttCallback callback) {
    // if the device is connected exit
    if (getMqttClient() != null && getMqttClient().isConnected()) {
        setStatus(context, callback, true);
        return;
    }
    MqttData cache = new MqttData(context);
    final String mBroker = cache.getBroker();
    final String mPort = cache.getPort();
    final String mUser = cache.getMqttUser();
    final String mPassword = cache.getMqttPasswd();
    final String mTopic = cache.getTopic();
    final String mTLS = cache.getTls();
    final StringBuilder connectionInformation = new StringBuilder();
    connectionInformation.append("\n\nBroker: ").append(mBroker).append("\n");
    connectionInformation.append("Port: ").append(mPort).append("\n");
    connectionInformation.append("User: ").append(mUser).append("\n");
    connectionInformation.append("Topic: ").append(mTopic).append("\n");
    connectionInformation.append("TLS: ").append(mTLS).append("\n");
    Log.d("MQTT", connectionInformation.toString());
    Helpers.storeLog("MQTT", "Connection Information", connectionInformation.toString());
    String protocol = "tcp";
    // TLS is active change protocol
    if (mTLS.equals("1")) {
        protocol = "ssl";
    }
    String clientId;
    MqttConnectOptions options;
    if (client == null) {
        try {
            clientId = MqttClient.generateClientId();
            client = new MqttAndroidClient(context, protocol + "://" + mBroker + ":" + mPort, clientId);
        } catch (ExceptionInInitializerError ex) {
            showDetailError(context, CommonErrorType.MQTT_IN_INITIALIZER_ERROR, ex.getMessage());
            reconnect(context, callback);
            return;
        }
        client.setCallback(callback);
    }
    try {
        options = new MqttConnectOptions();
        options.setPassword(mPassword.toCharArray());
        options.setUserName(mUser);
        options.setCleanSession(true);
        options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
        options.setConnectionTimeout(MqttConnectOptions.CONNECTION_TIMEOUT_DEFAULT);
        options.setKeepAliveInterval(MqttConnectOptions.KEEP_ALIVE_INTERVAL_DEFAULT);
        options.setAutomaticReconnect(true);
        // Create a testament to send when MQTT connection is down
        String will = "{ \"online\": false }";
        options.setWill(mTopic + "/Status/Online", will.getBytes(), 0, true);
        // If TLS is active needs ssl connection option
        if (mTLS.equals("1")) {
            try {
                // load ssl certificate from broker and put it in file
                // need to be done in anothger
                new MqttDownloadSSL().execute(mBroker, Integer.valueOf(mPort), context);
                TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                KeyStore caKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                caKeyStore.load(null, null);
                CertificateFactory certificationFactory = CertificateFactory.getInstance("X.509");
                // load certificate file previously loaded from broker
                FileInputStream inputStream;
                inputStream = context.openFileInput("broker_cert");
                X509Certificate ca = (X509Certificate) certificationFactory.generateCertificate(inputStream);
                String alias = ca.getSubjectX500Principal().getName();
                // Set proper alias name
                caKeyStore.setCertificateEntry(alias, ca);
                trustManagerFactory.init(caKeyStore);
                FlyveLog.v("Certificate Owner: %s", ca.getSubjectDN().toString());
                FlyveLog.v("Certificate Issuer: %s", ca.getIssuerDN().toString());
                FlyveLog.v("Certificate Serial Number: %s", ca.getSerialNumber().toString());
                FlyveLog.v("Certificate Algorithm: %s", ca.getSigAlgName());
                FlyveLog.v("Certificate Version: %s", ca.getVersion());
                FlyveLog.v("Certificate OID: %s", ca.getSigAlgOID());
                Enumeration<String> aliasesCA = caKeyStore.aliases();
                for (; aliasesCA.hasMoreElements(); ) {
                    String o = aliasesCA.nextElement();
                    FlyveLog.v("Alias: %s isKeyEntry:%s isCertificateEntry:%s", o, caKeyStore.isKeyEntry(o), caKeyStore.isCertificateEntry(o));
                }
                KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("X509");
                keyManagerFactory.init(null, null);
                // SSL
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
                options.setSocketFactory(sslContext.getSocketFactory());
            } catch (Exception ex) {
                // restart connection
                setStatus(context, callback, false);
                showDetailError(context, CommonErrorType.MQTT_CONNECTION, ex.getMessage());
            }
        }
    } catch (Exception ex) {
        showDetailError(context, CommonErrorType.MQTT_OPTIONS, ex.getMessage());
        return;
    }
    // set all the topics on database to unconnected
    new TopicsData(context).clearTopics();
    try {
        IMqttToken token = client.connect(options);
        token.setActionCallback(new IMqttActionListener() {

            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                Helpers.storeLog("MQTT", "Connection Success", "");
                // Everything ready waiting for message
                policiesController = new MqttController(context, client);
                // We are connected
                setStatus(context, callback, true);
                // set the reconnection counter to 0
                reconnectionCounter = 0;
                // main topic
                String topic = mTopic + "/#";
                policiesController.subscribe(topic);
                // subscribe to manifest
                policiesController.subscribe("FlyvemdmManifest/Status/Version");
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable ex) {
                setStatus(context, callback, false);
                String messageError;
                if (ex.getCause() != null) {
                    messageError = ex.getCause().toString();
                } else {
                    messageError = ex.getMessage();
                }
                showDetailError(context, CommonErrorType.MQTT_ACTION_CALLBACK, messageError);
            }
        });
    } catch (Exception ex) {
        setStatus(context, callback, false);
        showDetailError(context, CommonErrorType.MQTT_CONNECTION, ex.getMessage());
    }
}
Also used : MqttData(org.flyve.mdm.agent.data.database.MqttData) IMqttActionListener(org.eclipse.paho.client.mqttv3.IMqttActionListener) IMqttToken(org.eclipse.paho.client.mqttv3.IMqttToken) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) CertificateFactory(java.security.cert.CertificateFactory) MqttAndroidClient(org.eclipse.paho.android.service.MqttAndroidClient) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) TopicsData(org.flyve.mdm.agent.data.database.TopicsData) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) TrustManagerFactory(javax.net.ssl.TrustManagerFactory)

Aggregations

MqttData (org.flyve.mdm.agent.data.database.MqttData)14 JSONObject (org.json.JSONObject)5 View (android.view.View)4 Routes (org.flyve.mdm.agent.core.Routes)4 Intent (android.content.Intent)3 InventoryTask (org.flyve.inventory.InventoryTask)3 FloatingActionButton (android.support.design.widget.FloatingActionButton)2 TextView (android.widget.TextView)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 HttpURLConnection (java.net.HttpURLConnection)2 URL (java.net.URL)2 HashMap (java.util.HashMap)2 Hardware (org.flyve.inventory.categories.Hardware)2 UserData (org.flyve.mdm.agent.data.localstorage.UserData)2 Context (android.content.Context)1 DialogInterface (android.content.DialogInterface)1 Location (android.location.Location)1 Uri (android.net.Uri)1 Bundle (android.os.Bundle)1