Example usage for android.util Base64 NO_WRAP

List of usage examples for android.util Base64 NO_WRAP

Introduction

In this page you can find the example usage for android.util Base64 NO_WRAP.

Prototype

int NO_WRAP

To view the source code for android.util Base64 NO_WRAP.

Click Source Link

Document

Encoder flag bit to omit all line terminators (i.e., the output will be on one long line).

Usage

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private void syncronizeChannels(final boolean replace) {
    new Thread() {
        public void run() {
            boolean somethingSynchonized = false;

            if (replace) {
                ContentValues values = new ContentValues();
                values.put(TvBrowserContentProvider.CHANNEL_KEY_SELECTION, 0);
                values.put(TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER, 0);

                getContentResolver().delete(TvBrowserContentProvider.CONTENT_URI_DATA,
                        TvBrowserContentProvider.KEY_ID + " >= 0 ", null);
                getContentResolver().delete(TvBrowserContentProvider.CONTENT_URI_DATA_VERSION,
                        TvBrowserContentProvider.KEY_ID + " >= 0", null);

                if (getContentResolver().update(TvBrowserContentProvider.CONTENT_URI_CHANNELS, values,
                        TvBrowserContentProvider.CHANNEL_KEY_SELECTION + "=1", null) > 0) {
                    somethingSynchonized = true;
                }//from  w w w .ja  va 2s  .  co m
            }

            URL documentUrl;
            try {
                documentUrl = new URL(
                        "http://android.tvbrowser.org/data/scripts/syncDown.php?type=channelsFromDesktop");
                URLConnection connection = documentUrl.openConnection();

                SharedPreferences pref = getSharedPreferences("transportation", Context.MODE_PRIVATE);

                String car = pref.getString(SettingConstants.USER_NAME, null);
                String bicycle = pref.getString(SettingConstants.USER_PASSWORD, null);

                if (car != null && bicycle != null) {
                    String userpass = car + ":" + bicycle;
                    String basicAuth = "basic " + Base64.encodeToString(userpass.getBytes(), Base64.NO_WRAP);

                    connection.setRequestProperty("Authorization", basicAuth);

                    BufferedReader read = new BufferedReader(
                            new InputStreamReader(new GZIPInputStream(connection.getInputStream()), "UTF-8"));

                    String line = null;

                    int sort = 1;

                    while ((line = read.readLine()) != null) {
                        if (line.trim().length() > 0) {
                            if (line.contains(":")) {
                                String[] parts = line.split(":");

                                String dataService = null;
                                String groupKey = null;
                                String channelId = null;
                                String sortNumber = null;

                                if (parts[0].equals(SettingConstants
                                        .getNumberForDataServiceKey(SettingConstants.EPG_FREE_KEY))) {
                                    dataService = SettingConstants.EPG_FREE_KEY;
                                    groupKey = parts[1];
                                    channelId = parts[2];

                                    if (parts.length > 3) {
                                        sortNumber = parts[3];
                                    }
                                } else if (parts[0].equals(SettingConstants
                                        .getNumberForDataServiceKey(SettingConstants.EPG_DONATE_KEY))) {
                                    dataService = SettingConstants.EPG_DONATE_KEY;
                                    groupKey = SettingConstants.EPG_DONATE_GROUP_KEY;
                                    channelId = parts[1];

                                    if (parts.length > 2) {
                                        sortNumber = parts[2];
                                    }
                                }

                                if (dataService != null) {
                                    String where = " ( " + TvBrowserContentProvider.GROUP_KEY_DATA_SERVICE_ID
                                            + " = '" + dataService + "' ) AND ( "
                                            + TvBrowserContentProvider.GROUP_KEY_GROUP_ID + "='" + groupKey
                                            + "' ) ";

                                    Cursor group = getContentResolver().query(
                                            TvBrowserContentProvider.CONTENT_URI_GROUPS, null, where, null,
                                            null);

                                    if (group.moveToFirst()) {
                                        int groupId = group
                                                .getInt(group.getColumnIndex(TvBrowserContentProvider.KEY_ID));

                                        where = " ( " + TvBrowserContentProvider.GROUP_KEY_GROUP_ID + "="
                                                + groupId + " ) AND ( "
                                                + TvBrowserContentProvider.CHANNEL_KEY_CHANNEL_ID + "='"
                                                + channelId + "' ) ";

                                        ContentValues values = new ContentValues();

                                        if (sortNumber != null) {
                                            try {
                                                sort = Integer.parseInt(sortNumber);
                                            } catch (NumberFormatException e) {
                                            }
                                        }

                                        values.put(TvBrowserContentProvider.CHANNEL_KEY_SELECTION, 1);
                                        values.put(TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER, sort);

                                        int changed = getContentResolver().update(
                                                TvBrowserContentProvider.CONTENT_URI_CHANNELS, values, where,
                                                null);

                                        if (changed > 0) {
                                            somethingSynchonized = true;
                                        }
                                    }

                                    group.close();

                                    sort++;
                                }
                            }
                        }
                    }

                    if (somethingSynchonized) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                SettingConstants.initializeLogoMap(TvBrowser.this, true);
                                updateProgramListChannelBar();
                                Toast.makeText(getApplicationContext(), R.string.synchronize_done,
                                        Toast.LENGTH_LONG).show();
                                checkTermsAccepted();
                            }
                        });
                    } else {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), R.string.synchronize_error,
                                        Toast.LENGTH_LONG).show();
                                showChannelSelectionInternal();
                            }
                        });
                    }
                } else {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            showChannelSelectionInternal();
                        }
                    });
                }
            } catch (Exception e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        showChannelSelectionInternal();
                    }
                });
            }

            selectingChannels = false;
        }
    }.start();

}

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private void synchronizeDontWantToSee(final boolean replace) {
    new Thread() {
        public void run() {
            if (!SettingConstants.UPDATING_FILTER) {
                SettingConstants.UPDATING_FILTER = true;

                Context applicationContext = getApplicationContext();

                NotificationCompat.Builder builder;

                builder = new NotificationCompat.Builder(TvBrowser.this);
                builder.setSmallIcon(R.drawable.ic_stat_notify);
                builder.setOngoing(true);
                builder.setContentTitle(getResources().getText(R.string.action_dont_want_to_see));
                builder.setContentText(getResources().getText(R.string.dont_want_to_see_notification_text));

                int notifyID = 2;

                NotificationManager notification = (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
                notification.notify(notifyID, builder.build());

                updateProgressIcon(true);

                URL documentUrl;/*from ww w  . j a  v  a  2s .  c  om*/

                try {
                    documentUrl = new URL(
                            "http://android.tvbrowser.org/data/scripts/syncDown.php?type=dontWantToSee");
                    URLConnection connection = documentUrl.openConnection();

                    SharedPreferences pref = getSharedPreferences("transportation", Context.MODE_PRIVATE);

                    String car = pref.getString(SettingConstants.USER_NAME, null);
                    String bicycle = pref.getString(SettingConstants.USER_PASSWORD, null);

                    if (car != null && bicycle != null) {
                        String userpass = car + ":" + bicycle;
                        String basicAuth = "basic "
                                + Base64.encodeToString(userpass.getBytes(), Base64.NO_WRAP);

                        connection.setRequestProperty("Authorization", basicAuth);

                        BufferedReader read = new BufferedReader(new InputStreamReader(
                                new GZIPInputStream(connection.getInputStream()), "UTF-8"));

                        String line = null;

                        StringBuilder exclusionBuilder = new StringBuilder();
                        HashSet<String> exclusions = new HashSet<String>();
                        ArrayList<DontWantToSeeExclusion> exclusionList = new ArrayList<DontWantToSeeExclusion>();

                        while ((line = read.readLine()) != null) {
                            if (line.contains(";;") && line.trim().length() > 0) {
                                exclusions.add(line);
                                exclusionList.add(new DontWantToSeeExclusion(line));
                                exclusionBuilder.append(line).append("\n");
                            }
                        }

                        String key = getString(R.string.I_DONT_WANT_TO_SEE_ENTRIES);
                        SharedPreferences pref1 = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this);

                        Set<String> oldValues = pref1.getStringSet(key, null);

                        if (exclusions.size() > 0) {
                            if (!replace && oldValues != null) {
                                for (String old : oldValues) {
                                    if (!exclusions.contains(old)) {
                                        exclusions.add(old);
                                        exclusionList.add(new DontWantToSeeExclusion(old));
                                        exclusionBuilder.append(old).append("\n");
                                    }
                                }
                            }

                            Editor edit = pref1.edit();

                            edit.putStringSet(key, exclusions);
                            edit.commit();

                            DontWantToSeeExclusion[] exclusionArr = exclusionList
                                    .toArray(new DontWantToSeeExclusion[exclusionList.size()]);

                            Cursor c = getContentResolver().query(TvBrowserContentProvider.CONTENT_URI_DATA,
                                    new String[] { TvBrowserContentProvider.KEY_ID,
                                            TvBrowserContentProvider.DATA_KEY_TITLE },
                                    null, null, TvBrowserContentProvider.KEY_ID);
                            c.moveToPosition(-1);

                            builder.setProgress(c.getCount(), 0, true);
                            notification.notify(notifyID, builder.build());

                            ArrayList<ContentProviderOperation> updateValuesList = new ArrayList<ContentProviderOperation>();

                            int keyColumn = c.getColumnIndex(TvBrowserContentProvider.KEY_ID);
                            int titleColumn = c.getColumnIndex(TvBrowserContentProvider.DATA_KEY_TITLE);

                            while (c.moveToNext()) {
                                builder.setProgress(c.getCount(), c.getPosition(), false);
                                notification.notify(notifyID, builder.build());

                                String title = c.getString(titleColumn);

                                boolean filter = UiUtils.filter(getApplicationContext(), title, exclusionArr);
                                long progID = c.getLong(keyColumn);

                                ContentValues values = new ContentValues();
                                values.put(TvBrowserContentProvider.DATA_KEY_DONT_WANT_TO_SEE, filter ? 1 : 0);

                                ContentProviderOperation.Builder opBuilder = ContentProviderOperation
                                        .newUpdate(ContentUris.withAppendedId(
                                                TvBrowserContentProvider.CONTENT_URI_DATA_UPDATE, progID));
                                opBuilder.withValues(values);

                                updateValuesList.add(opBuilder.build());
                            }

                            c.close();

                            if (!updateValuesList.isEmpty()) {
                                try {
                                    getContentResolver().applyBatch(TvBrowserContentProvider.AUTHORITY,
                                            updateValuesList);
                                    UiUtils.sendDontWantToSeeChangedBroadcast(applicationContext, true);
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(getApplicationContext(),
                                                    R.string.dont_want_to_see_sync_success, Toast.LENGTH_LONG)
                                                    .show();
                                        }
                                    });
                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                } catch (OperationApplicationException e) {
                                    e.printStackTrace();
                                }
                            }

                            if (!replace && exclusionBuilder.length() > 0) {
                                startSynchronizeUp(false, exclusionBuilder.toString(),
                                        "http://android.tvbrowser.org/data/scripts/syncUp.php?type=dontWantToSee",
                                        null, null);
                            }
                        } else {
                            if (!replace && oldValues != null && !oldValues.isEmpty()) {
                                for (String old : oldValues) {
                                    exclusionBuilder.append(old).append("\n");
                                }

                                startSynchronizeUp(false, exclusionBuilder.toString(),
                                        "http://android.tvbrowser.org/data/scripts/syncUp.php?type=dontWantToSee",
                                        null, null);
                            }

                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(), R.string.no_dont_want_to_see_sync,
                                            Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    }
                } catch (Throwable t) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), R.string.no_dont_want_to_see_sync,
                                    Toast.LENGTH_LONG).show();
                        }
                    });
                }

                notification.cancel(notifyID);
                updateProgressIcon(false);

                SettingConstants.UPDATING_FILTER = false;
            }
        }
    }.start();
}

From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java

private GBDeviceEvent[] decodeDictToJSONAppMessage(UUID uuid, ByteBuffer buf) throws JSONException {
    buf.order(ByteOrder.LITTLE_ENDIAN);
    byte dictSize = buf.get();
    if (dictSize == 0) {
        LOG.info("dict size is 0, ignoring");
        return null;
    }//from w ww.jav  a 2  s .c om
    JSONArray jsonArray = new JSONArray();
    while (dictSize-- > 0) {
        JSONObject jsonObject = new JSONObject();
        Integer key = buf.getInt();
        byte type = buf.get();
        short length = buf.getShort();
        jsonObject.put("key", key);
        if (type == TYPE_CSTRING) {
            length--;
        }
        jsonObject.put("length", length);
        switch (type) {
        case TYPE_UINT:
            jsonObject.put("type", "uint");
            if (length == 1) {
                jsonObject.put("value", buf.get() & 0xff);
            } else if (length == 2) {
                jsonObject.put("value", buf.getShort() & 0xffff);
            } else {
                jsonObject.put("value", buf.getInt() & 0xffffffffL);
            }
            break;
        case TYPE_INT:
            jsonObject.put("type", "int");
            if (length == 1) {
                jsonObject.put("value", buf.get());
            } else if (length == 2) {
                jsonObject.put("value", buf.getShort());
            } else {
                jsonObject.put("value", buf.getInt());
            }
            break;
        case TYPE_BYTEARRAY:
        case TYPE_CSTRING:
            byte[] bytes = new byte[length];
            buf.get(bytes);
            if (type == TYPE_BYTEARRAY) {
                jsonObject.put("type", "bytes");
                jsonObject.put("value", new String(Base64.encode(bytes, Base64.NO_WRAP)));
            } else {
                jsonObject.put("type", "string");
                jsonObject.put("value", new String(bytes));
                buf.get(); // skip null-termination;
            }
            break;
        default:
            LOG.info("unknown type in appmessage, ignoring");
            return null;
        }
        jsonArray.put(jsonObject);
    }

    GBDeviceEventSendBytes sendBytesAck = null;
    if (mAlwaysACKPebbleKit) {
        // this is a hack we send an ack to the Pebble immediately because somebody said it helps some PebbleKit apps :P
        sendBytesAck = new GBDeviceEventSendBytes();
        sendBytesAck.encodedBytes = encodeApplicationMessageAck(uuid, last_id);
    }
    GBDeviceEventAppMessage appMessage = new GBDeviceEventAppMessage();
    appMessage.appUUID = uuid;
    appMessage.id = last_id & 0xff;
    appMessage.message = jsonArray.toString();
    return new GBDeviceEvent[] { appMessage, sendBytesAck };
}

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private void restorePreferencesInternal() {
    handler.post(new Runnable() {
        @Override//  www  .ja  va2s .co  m
        public void run() {
            mViewPager.setCurrentItem(0, true);

            for (int i = mSectionsPagerAdapter.getCount() - 1; i >= 0; i--) {
                mSectionsPagerAdapter.destroyItem(mViewPager, i,
                        mSectionsPagerAdapter.getRegisteredFragment(i));
                mSectionsPagerAdapter.notifyDataSetChanged();
                actionBar.removeTabAt(i);
            }

            actionBar.addTab(actionBar.newTab().setText(getString(R.string.tab_restoring_name))
                    .setTabListener(new ActionBar.TabListener() {
                        @Override
                        public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
                        }

                        @Override
                        public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
                        }

                        @Override
                        public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
                        }
                    }));

            new Thread("RESTORE PREFERENCES") {
                @Override
                public void run() {
                    updateProgressIcon(true);

                    URL documentUrl;

                    BufferedReader read = null;
                    boolean restored = false;

                    try {
                        documentUrl = new URL(
                                "http://android.tvbrowser.org/data/scripts/syncDown.php?type=preferencesBackup");
                        URLConnection connection = documentUrl.openConnection();

                        SharedPreferences pref = getSharedPreferences("transportation", Context.MODE_PRIVATE);

                        String car = pref.getString(SettingConstants.USER_NAME, null);
                        String bicycle = pref.getString(SettingConstants.USER_PASSWORD, null);

                        if (car != null && bicycle != null) {
                            String userpass = car + ":" + bicycle;
                            String basicAuth = "basic "
                                    + Base64.encodeToString(userpass.getBytes(), Base64.NO_WRAP);

                            connection.setRequestProperty("Authorization", basicAuth);

                            read = new BufferedReader(new InputStreamReader(
                                    new GZIPInputStream(connection.getInputStream()), "UTF-8"));

                            String line = null;
                            Editor edit = PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
                                    .edit();

                            TvBrowserContentProvider.INFORM_FOR_CHANGES = false;

                            final Favorite[] existingFavorites = Favorite
                                    .getAllFavorites(getApplicationContext());

                            while ((line = read.readLine()) != null) {
                                int index = line.indexOf(":");

                                if (index > 0) {
                                    restored = true;
                                    String type = line.substring(0, index);
                                    String[] parts = line.substring(index + 1).split("=");

                                    if (parts != null && parts.length > 1) {
                                        if (type.equals("boolean")) {
                                            boolean boolValue = Boolean.valueOf(parts[1].trim());

                                            if (!getString(R.string.PREF_RATING_DONATION_INFO_SHOWN)
                                                    .equals(parts[0]) || boolValue) {
                                                edit.putBoolean(parts[0], boolValue);
                                            }
                                        } else if (type.equals("int")) {
                                            if (!getString(R.string.OLD_VERSION).equals(parts[0])) {
                                                edit.putInt(parts[0], Integer.valueOf(parts[1].trim()));
                                            }
                                        } else if (type.equals("float")) {
                                            edit.putFloat(parts[0], Float.valueOf(parts[1].trim()));
                                        } else if (type.equals("long")) {
                                            edit.putLong(parts[0], Long.valueOf(parts[1].trim()));
                                        } else if (type.equals("string")) {
                                            edit.putString(parts[0], parts[1].trim());
                                        } else if (type.equals("set")) {
                                            HashSet<String> set = new HashSet<String>();

                                            String[] setParts = parts[1].split("#,#");

                                            if (setParts != null && setParts.length > 0) {
                                                if (parts[0].equals("FAVORITE_LIST")) {
                                                    Favorite.deleteAllFavorites(getApplicationContext());
                                                    int id = 1000;

                                                    for (String setPart : setParts) {
                                                        Favorite favorite = new Favorite(id++, setPart);
                                                        favorite.loadChannelRestrictionIdsFromUniqueChannelRestriction(
                                                                getApplicationContext());
                                                        Favorite.handleFavoriteMarking(getApplicationContext(),
                                                                favorite, Favorite.TYPE_MARK_ADD);
                                                    }
                                                } else {
                                                    for (String setPart : setParts) {
                                                        set.add(setPart);
                                                    }

                                                    edit.putStringSet(parts[0], set);
                                                }
                                            }
                                        } else if (type.equals("favorite")) {
                                            Favorite favorite = new Favorite(Long.parseLong(parts[0]),
                                                    parts[1]);

                                            for (Favorite test : existingFavorites) {
                                                if (test.getFavoriteId() == favorite.getFavoriteId()) {
                                                    Favorite.deleteFavorite(getApplicationContext(), favorite);
                                                    break;
                                                }
                                            }

                                            favorite.loadChannelRestrictionIdsFromUniqueChannelRestriction(
                                                    getApplicationContext());
                                            Favorite.handleFavoriteMarking(getApplicationContext(), favorite,
                                                    Favorite.TYPE_MARK_ADD);
                                        }
                                    }
                                }
                            }

                            TvBrowserContentProvider.INFORM_FOR_CHANGES = true;

                            if (restored) {
                                edit.commit();
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        updateFromPreferences(true);
                                    }
                                });

                                IOUtils.handleDataUpdatePreferences(getApplicationContext());
                            }
                        }
                    } catch (Exception e) {
                        restored = false;
                    } finally {
                        if (read != null) {
                            try {
                                read.close();
                            } catch (IOException e) {
                            }
                        }
                    }

                    if (restored) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(TvBrowser.this,
                                        getString(R.string.backup_preferences_restore_success),
                                        Toast.LENGTH_LONG).show();
                            }
                        });
                    } else {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(TvBrowser.this,
                                        getString(R.string.backup_preferences_restore_failure),
                                        Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    updateProgressIcon(false);
                }
            }.start();
        }
    });
}

From source file:org.mozilla.gecko.BrowserApp.java

private void getFaviconFromCache(final EventCallback callback, final String url) {
    final OnFaviconLoadedListener listener = new OnFaviconLoadedListener() {
        @Override// ww w  .j  a  v  a 2s  .c  o  m
        public void onFaviconLoaded(final String url, final String faviconURL, final Bitmap favicon) {
            ThreadUtils.assertOnUiThread();
            // Convert Bitmap to Base64 data URI in background.
            ThreadUtils.postToBackgroundThread(new Runnable() {
                @Override
                public void run() {
                    ByteArrayOutputStream out = null;
                    Base64OutputStream b64 = null;

                    // Failed to load favicon from local.
                    if (favicon == null) {
                        callback.sendError("Failed to get favicon from cache");
                    } else {
                        try {
                            out = new ByteArrayOutputStream();
                            out.write("data:image/png;base64,".getBytes());
                            b64 = new Base64OutputStream(out, Base64.NO_WRAP);
                            favicon.compress(Bitmap.CompressFormat.PNG, 100, b64);
                            callback.sendSuccess(new String(out.toByteArray()));
                        } catch (IOException e) {
                            Log.w(LOGTAG, "Failed to convert to base64 data URI");
                            callback.sendError("Failed to convert favicon to a base64 data URI");
                        } finally {
                            try {
                                if (out != null) {
                                    out.close();
                                }
                                if (b64 != null) {
                                    b64.close();
                                }
                            } catch (IOException e) {
                                Log.w(LOGTAG, "Failed to close the streams");
                            }
                        }
                    }
                }
            });
        }
    };
    Favicons.getSizedFaviconForPageFromLocal(getContext(), url, listener);
}

From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java

byte[] encodeApplicationMessageFromJSON(UUID uuid, JSONArray jsonArray) {
    ArrayList<Pair<Integer, Object>> pairs = new ArrayList<>();
    for (int i = 0; i < jsonArray.length(); i++) {
        try {//from   w w w  . ja va  2  s.  c  o  m
            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            String type = (String) jsonObject.get("type");
            int key = jsonObject.getInt("key");
            int length = jsonObject.getInt("length");
            switch (type) {
            case "uint":
            case "int":
                if (length == 1) {
                    pairs.add(new Pair<>(key, (Object) (byte) jsonObject.getInt("value")));
                } else if (length == 2) {
                    pairs.add(new Pair<>(key, (Object) (short) jsonObject.getInt("value")));
                } else {
                    if (type.equals("uint")) {
                        pairs.add(new Pair<>(key, (Object) (int) (jsonObject.getInt("value") & 0xffffffffL)));
                    } else {
                        pairs.add(new Pair<>(key, (Object) jsonObject.getInt("value")));
                    }
                }
                break;
            case "string":
                pairs.add(new Pair<>(key, (Object) jsonObject.getString("value")));
                break;
            case "bytes":
                byte[] bytes = Base64.decode(jsonObject.getString("value"), Base64.NO_WRAP);
                pairs.add(new Pair<>(key, (Object) bytes));
                break;
            }
        } catch (JSONException e) {
            return null;
        }
    }

    return encodeApplicationMessagePush(ENDPOINT_APPLICATIONMESSAGE, uuid, pairs);
}

From source file:com.ubiLive.GameCloud.Browser.WebBrowser.java

public String ubiGCPlayerDigestMessage(String message) {
    String resultSignature = "";
    try {//ww  w .j  a  va  2s  .  c o  m
        byte[] sha1Bytes = Utils.SHA1(message);
        //DebugLog.d(TAG, "ubiGCPlayerDigestMessage() sha1Str = " + sha1Str);
        //DebugLog.d(TAG, "ubiGCPlayerDigestMessage() sha1Bytes = " + Arrays.toString(sha1Bytes));

        byte[] rsaEncryptedBytes = Utils.rsaEncrypt(Constants.sModulusStr, Constants.sPublicExponentStr,
                sha1Bytes);
        DebugLog.d(TAG, "ubiGCPlayerDigestMessage() rsaEncryptedBytes = " + Arrays.toString(rsaEncryptedBytes));
        resultSignature = Base64.encodeToString(rsaEncryptedBytes, Base64.NO_WRAP);
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        DebugLog.d(TAG, "excepion = " + e.getMessage());
        return "";
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        DebugLog.d(TAG, "excepion = " + e.getMessage());
        return "";
    }
    return resultSignature;
}

From source file:org.telegram.ui.PassportActivity.java

private void createRequestInterface(Context context) {
    TLRPC.User botUser = null;//from w  w w . j  a v  a2 s .  c  o  m
    if (currentForm != null) {
        for (int a = 0; a < currentForm.users.size(); a++) {
            TLRPC.User user = currentForm.users.get(a);
            if (user.id == currentBotId) {
                botUser = user;
                break;
            }
        }
    }

    FrameLayout frameLayout = (FrameLayout) fragmentView;

    actionBar.setTitle(LocaleController.getString("TelegramPassport", R.string.TelegramPassport));

    actionBar.createMenu().addItem(info_item, R.drawable.profile_info);

    if (botUser != null) {
        FrameLayout avatarContainer = new FrameLayout(context);
        linearLayout2.addView(avatarContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 100));

        BackupImageView avatarImageView = new BackupImageView(context);
        avatarImageView.setRoundRadius(AndroidUtilities.dp(32));
        avatarContainer.addView(avatarImageView, LayoutHelper.createFrame(64, 64, Gravity.CENTER, 0, 8, 0, 0));

        AvatarDrawable avatarDrawable = new AvatarDrawable(botUser);
        TLRPC.FileLocation photo = null;
        if (botUser.photo != null) {
            photo = botUser.photo.photo_small;
        }
        avatarImageView.setImage(photo, "50_50", avatarDrawable, botUser);

        bottomCell = new TextInfoPrivacyCell(context);
        bottomCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_top,
                Theme.key_windowBackgroundGrayShadow));
        bottomCell.setText(AndroidUtilities.replaceTags(LocaleController.formatString("PassportRequest",
                R.string.PassportRequest, UserObject.getFirstName(botUser))));
        bottomCell.getTextView().setGravity(Gravity.CENTER_HORIZONTAL);
        ((FrameLayout.LayoutParams) bottomCell.getTextView()
                .getLayoutParams()).gravity = Gravity.CENTER_HORIZONTAL;
        linearLayout2.addView(bottomCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    }

    headerCell = new HeaderCell(context);
    headerCell.setText(
            LocaleController.getString("PassportRequestedInformation", R.string.PassportRequestedInformation));
    headerCell.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
    linearLayout2.addView(headerCell,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    if (currentForm != null) {
        int size = currentForm.required_types.size();
        ArrayList<TLRPC.TL_secureRequiredType> personalDocuments = new ArrayList<>();
        ArrayList<TLRPC.TL_secureRequiredType> addressDocuments = new ArrayList<>();
        int personalCount = 0;
        int addressCount = 0;
        boolean hasPersonalInfo = false;
        boolean hasAddressInfo = false;
        for (int a = 0; a < size; a++) {
            TLRPC.SecureRequiredType secureRequiredType = currentForm.required_types.get(a);
            if (secureRequiredType instanceof TLRPC.TL_secureRequiredType) {
                TLRPC.TL_secureRequiredType requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType;
                if (isPersonalDocument(requiredType.type)) {
                    personalDocuments.add(requiredType);
                    personalCount++;
                } else if (isAddressDocument(requiredType.type)) {
                    addressDocuments.add(requiredType);
                    addressCount++;
                } else if (requiredType.type instanceof TLRPC.TL_secureValueTypePersonalDetails) {
                    hasPersonalInfo = true;
                } else if (requiredType.type instanceof TLRPC.TL_secureValueTypeAddress) {
                    hasAddressInfo = true;
                }
            } else if (secureRequiredType instanceof TLRPC.TL_secureRequiredTypeOneOf) {
                TLRPC.TL_secureRequiredTypeOneOf requiredTypeOneOf = (TLRPC.TL_secureRequiredTypeOneOf) secureRequiredType;
                if (requiredTypeOneOf.types.isEmpty()) {
                    continue;
                }
                TLRPC.SecureRequiredType innerType = requiredTypeOneOf.types.get(0);
                if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                    continue;
                }
                TLRPC.TL_secureRequiredType requiredType = (TLRPC.TL_secureRequiredType) innerType;

                if (isPersonalDocument(requiredType.type)) {
                    for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) {
                        innerType = requiredTypeOneOf.types.get(b);
                        if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                            continue;
                        }
                        personalDocuments.add((TLRPC.TL_secureRequiredType) innerType);
                    }
                    personalCount++;
                } else if (isAddressDocument(requiredType.type)) {
                    for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) {
                        innerType = requiredTypeOneOf.types.get(b);
                        if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                            continue;
                        }
                        addressDocuments.add((TLRPC.TL_secureRequiredType) innerType);
                    }
                    addressCount++;
                }
            }
        }
        boolean separatePersonal = !hasPersonalInfo || personalCount > 1;
        boolean separateAddress = !hasAddressInfo || addressCount > 1;
        for (int a = 0; a < size; a++) {
            TLRPC.SecureRequiredType secureRequiredType = currentForm.required_types.get(a);
            ArrayList<TLRPC.TL_secureRequiredType> documentTypes;
            TLRPC.TL_secureRequiredType requiredType;
            boolean documentOnly;
            if (secureRequiredType instanceof TLRPC.TL_secureRequiredType) {
                requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType;
                if (requiredType.type instanceof TLRPC.TL_secureValueTypePhone
                        || requiredType.type instanceof TLRPC.TL_secureValueTypeEmail) {
                    documentTypes = null;
                    documentOnly = false;
                } else if (requiredType.type instanceof TLRPC.TL_secureValueTypePersonalDetails) {
                    if (separatePersonal) {
                        documentTypes = null;
                    } else {
                        documentTypes = personalDocuments;
                    }
                    documentOnly = false;
                } else if (requiredType.type instanceof TLRPC.TL_secureValueTypeAddress) {
                    if (separateAddress) {
                        documentTypes = null;
                    } else {
                        documentTypes = addressDocuments;
                    }
                    documentOnly = false;
                } else if (separatePersonal && isPersonalDocument(requiredType.type)) {
                    documentTypes = new ArrayList<>();
                    documentTypes.add(requiredType);
                    requiredType = new TLRPC.TL_secureRequiredType();
                    requiredType.type = new TLRPC.TL_secureValueTypePersonalDetails();
                    documentOnly = true;
                } else if (separateAddress && isAddressDocument(requiredType.type)) {
                    documentTypes = new ArrayList<>();
                    documentTypes.add(requiredType);
                    requiredType = new TLRPC.TL_secureRequiredType();
                    requiredType.type = new TLRPC.TL_secureValueTypeAddress();
                    documentOnly = true;
                } else {
                    continue;
                }
            } else if (secureRequiredType instanceof TLRPC.TL_secureRequiredTypeOneOf) {
                TLRPC.TL_secureRequiredTypeOneOf requiredTypeOneOf = (TLRPC.TL_secureRequiredTypeOneOf) secureRequiredType;
                if (requiredTypeOneOf.types.isEmpty()) {
                    continue;
                }
                TLRPC.SecureRequiredType innerType = requiredTypeOneOf.types.get(0);
                if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                    continue;
                }
                requiredType = (TLRPC.TL_secureRequiredType) innerType;

                if (separatePersonal && isPersonalDocument(requiredType.type)
                        || separateAddress && isAddressDocument(requiredType.type)) {
                    documentTypes = new ArrayList<>();
                    for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) {
                        innerType = requiredTypeOneOf.types.get(b);
                        if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                            continue;
                        }
                        documentTypes.add((TLRPC.TL_secureRequiredType) innerType);
                    }
                    if (isPersonalDocument(requiredType.type)) {
                        requiredType = new TLRPC.TL_secureRequiredType();
                        requiredType.type = new TLRPC.TL_secureValueTypePersonalDetails();
                    } else {
                        requiredType = new TLRPC.TL_secureRequiredType();
                        requiredType.type = new TLRPC.TL_secureValueTypeAddress();
                    }

                    documentOnly = true;
                } else {
                    continue;
                }
            } else {
                continue;
            }
            addField(context, requiredType, documentTypes, documentOnly, a == size - 1);
        }
    }

    if (botUser != null) {
        bottomCell = new TextInfoPrivacyCell(context);
        bottomCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom,
                Theme.key_windowBackgroundGrayShadow));
        bottomCell.setLinkTextColorKey(Theme.key_windowBackgroundWhiteGrayText4);
        if (!TextUtils.isEmpty(currentForm.privacy_policy_url)) {
            String str2 = LocaleController.formatString("PassportPolicy", R.string.PassportPolicy,
                    UserObject.getFirstName(botUser), botUser.username);
            SpannableStringBuilder text = new SpannableStringBuilder(str2);
            int index1 = str2.indexOf('*');
            int index2 = str2.lastIndexOf('*');
            if (index1 != -1 && index2 != -1) {
                bottomCell.getTextView().setMovementMethod(new AndroidUtilities.LinkMovementMethodMy());
                text.replace(index2, index2 + 1, "");
                text.replace(index1, index1 + 1, "");
                text.setSpan(new LinkSpan(), index1, index2 - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            bottomCell.setText(text);
        } else {
            bottomCell.setText(AndroidUtilities.replaceTags(LocaleController.formatString("PassportNoPolicy",
                    R.string.PassportNoPolicy, UserObject.getFirstName(botUser), botUser.username)));
        }
        bottomCell.getTextView().setHighlightColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText4));
        bottomCell.getTextView().setGravity(Gravity.CENTER_HORIZONTAL);
        linearLayout2.addView(bottomCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    }

    bottomLayout = new FrameLayout(context);
    bottomLayout.setBackgroundDrawable(
            Theme.createSelectorWithBackgroundDrawable(Theme.getColor(Theme.key_passport_authorizeBackground),
                    Theme.getColor(Theme.key_passport_authorizeBackgroundSelected)));
    frameLayout.addView(bottomLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM));
    bottomLayout.setOnClickListener(view -> {

        class ValueToSend {
            TLRPC.TL_secureValue value;
            boolean selfie_required;
            boolean translation_required;

            public ValueToSend(TLRPC.TL_secureValue v, boolean s, boolean t) {
                value = v;
                selfie_required = s;
                translation_required = t;
            }
        }

        ArrayList<ValueToSend> valuesToSend = new ArrayList<>();
        for (int a = 0, size = currentForm.required_types.size(); a < size; a++) {

            TLRPC.TL_secureRequiredType requiredType;

            TLRPC.SecureRequiredType secureRequiredType = currentForm.required_types.get(a);
            if (secureRequiredType instanceof TLRPC.TL_secureRequiredType) {
                requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType;
            } else if (secureRequiredType instanceof TLRPC.TL_secureRequiredTypeOneOf) {
                TLRPC.TL_secureRequiredTypeOneOf requiredTypeOneOf = (TLRPC.TL_secureRequiredTypeOneOf) secureRequiredType;
                if (requiredTypeOneOf.types.isEmpty()) {
                    continue;
                }
                secureRequiredType = requiredTypeOneOf.types.get(0);
                if (!(secureRequiredType instanceof TLRPC.TL_secureRequiredType)) {
                    continue;
                }
                requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType;

                for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) {
                    secureRequiredType = requiredTypeOneOf.types.get(b);
                    if (!(secureRequiredType instanceof TLRPC.TL_secureRequiredType)) {
                        continue;
                    }
                    TLRPC.TL_secureRequiredType innerType = (TLRPC.TL_secureRequiredType) secureRequiredType;
                    if (getValueByType(innerType, true) != null) {
                        requiredType = innerType;
                        break;
                    }
                }
            } else {
                continue;
            }

            TLRPC.TL_secureValue value = getValueByType(requiredType, true);
            if (value == null) {
                Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
                if (v != null) {
                    v.vibrate(200);
                }
                AndroidUtilities.shakeView(getViewByType(requiredType), 2, 0);
                return;
            }
            String key = getNameForType(requiredType.type);
            HashMap<String, String> errors = errorsMap.get(key);
            if (errors != null && !errors.isEmpty()) {
                Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
                if (v != null) {
                    v.vibrate(200);
                }
                AndroidUtilities.shakeView(getViewByType(requiredType), 2, 0);
                return;
            }
            valuesToSend.add(
                    new ValueToSend(value, requiredType.selfie_required, requiredType.translation_required));
        }
        showEditDoneProgress(false, true);
        TLRPC.TL_account_acceptAuthorization req = new TLRPC.TL_account_acceptAuthorization();
        req.bot_id = currentBotId;
        req.scope = currentScope;
        req.public_key = currentPublicKey;
        JSONObject jsonObject = new JSONObject();
        for (int a = 0, size = valuesToSend.size(); a < size; a++) {
            ValueToSend valueToSend = valuesToSend.get(a);
            TLRPC.TL_secureValue secureValue = valueToSend.value;

            JSONObject data = new JSONObject();

            if (secureValue.plain_data != null) {
                if (secureValue.plain_data instanceof TLRPC.TL_securePlainEmail) {
                    TLRPC.TL_securePlainEmail securePlainEmail = (TLRPC.TL_securePlainEmail) secureValue.plain_data;
                } else if (secureValue.plain_data instanceof TLRPC.TL_securePlainPhone) {
                    TLRPC.TL_securePlainPhone securePlainPhone = (TLRPC.TL_securePlainPhone) secureValue.plain_data;
                }
            } else {
                try {
                    JSONObject result = new JSONObject();
                    if (secureValue.data != null) {
                        byte[] decryptedSecret = decryptValueSecret(secureValue.data.secret,
                                secureValue.data.data_hash);

                        data.put("data_hash",
                                Base64.encodeToString(secureValue.data.data_hash, Base64.NO_WRAP));
                        data.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));

                        result.put("data", data);
                    }
                    if (!secureValue.files.isEmpty()) {
                        JSONArray files = new JSONArray();
                        for (int b = 0, size2 = secureValue.files.size(); b < size2; b++) {
                            TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.files.get(b);
                            byte[] decryptedSecret = decryptValueSecret(secureFile.secret,
                                    secureFile.file_hash);

                            JSONObject file = new JSONObject();
                            file.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                            file.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                            files.put(file);
                        }
                        result.put("files", files);
                    }
                    if (secureValue.front_side instanceof TLRPC.TL_secureFile) {
                        TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.front_side;
                        byte[] decryptedSecret = decryptValueSecret(secureFile.secret, secureFile.file_hash);

                        JSONObject front = new JSONObject();
                        front.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                        front.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                        result.put("front_side", front);
                    }
                    if (secureValue.reverse_side instanceof TLRPC.TL_secureFile) {
                        TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.reverse_side;
                        byte[] decryptedSecret = decryptValueSecret(secureFile.secret, secureFile.file_hash);

                        JSONObject reverse = new JSONObject();
                        reverse.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                        reverse.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                        result.put("reverse_side", reverse);
                    }
                    if (valueToSend.selfie_required && secureValue.selfie instanceof TLRPC.TL_secureFile) {
                        TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.selfie;
                        byte[] decryptedSecret = decryptValueSecret(secureFile.secret, secureFile.file_hash);

                        JSONObject selfie = new JSONObject();
                        selfie.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                        selfie.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                        result.put("selfie", selfie);
                    }
                    if (valueToSend.translation_required && !secureValue.translation.isEmpty()) {
                        JSONArray translation = new JSONArray();
                        for (int b = 0, size2 = secureValue.translation.size(); b < size2; b++) {
                            TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.translation
                                    .get(b);
                            byte[] decryptedSecret = decryptValueSecret(secureFile.secret,
                                    secureFile.file_hash);

                            JSONObject file = new JSONObject();
                            file.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                            file.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                            translation.put(file);
                        }
                        result.put("translation", translation);
                    }
                    jsonObject.put(getNameForType(secureValue.type), result);
                } catch (Exception ignore) {

                }
            }

            TLRPC.TL_secureValueHash hash = new TLRPC.TL_secureValueHash();
            hash.type = secureValue.type;
            hash.hash = secureValue.hash;
            req.value_hashes.add(hash);
        }
        JSONObject result = new JSONObject();
        try {
            result.put("secure_data", jsonObject);
        } catch (Exception ignore) {

        }
        if (currentPayload != null) {
            try {
                result.put("payload", currentPayload);
            } catch (Exception ignore) {

            }
        }
        if (currentNonce != null) {
            try {
                result.put("nonce", currentNonce);
            } catch (Exception ignore) {

            }
        }
        String json = result.toString();

        EncryptionResult encryptionResult = encryptData(AndroidUtilities.getStringBytes(json));

        req.credentials = new TLRPC.TL_secureCredentialsEncrypted();
        req.credentials.hash = encryptionResult.fileHash;
        req.credentials.data = encryptionResult.encryptedData;
        try {
            String key = currentPublicKey.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----", "")
                    .replace("-----END PUBLIC KEY-----", "");
            KeyFactory kf = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(Base64.decode(key, Base64.DEFAULT));
            RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(keySpecX509);

            Cipher c = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");
            c.init(Cipher.ENCRYPT_MODE, pubKey);
            req.credentials.secret = c.doFinal(encryptionResult.decrypyedFileSecret);
        } catch (Exception e) {
            FileLog.e(e);
        }
        int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req,
                (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                    if (error == null) {
                        ignoreOnFailure = true;
                        callCallback(true);
                        finishFragment();
                    } else {
                        showEditDoneProgress(false, false);
                        if ("APP_VERSION_OUTDATED".equals(error.text)) {
                            AlertsCreator.showUpdateAppAlert(getParentActivity(),
                                    LocaleController.getString("UpdateAppAlert", R.string.UpdateAppAlert),
                                    true);
                        } else {
                            showAlertWithText(LocaleController.getString("AppName", R.string.AppName),
                                    error.text);
                        }
                    }
                }));
        ConnectionsManager.getInstance(currentAccount).bindRequestToGuid(reqId, classGuid);
    });

    acceptTextView = new TextView(context);
    acceptTextView.setCompoundDrawablePadding(AndroidUtilities.dp(8));
    acceptTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.authorize, 0, 0, 0);
    acceptTextView.setTextColor(Theme.getColor(Theme.key_passport_authorizeText));
    acceptTextView.setText(LocaleController.getString("PassportAuthorize", R.string.PassportAuthorize));
    acceptTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    acceptTextView.setGravity(Gravity.CENTER);
    acceptTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    bottomLayout.addView(acceptTextView,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER));

    progressViewButton = new ContextProgressView(context, 0);
    progressViewButton.setVisibility(View.INVISIBLE);
    bottomLayout.addView(progressViewButton,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

    View shadow = new View(context);
    shadow.setBackgroundResource(R.drawable.header_shadow_reverse);
    frameLayout.addView(shadow,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3, Gravity.LEFT | Gravity.BOTTOM, 0, 0, 0, 48));
}

From source file:mobile.tiis.appv2.base.BackboneApplication.java

/**
 * this method takes the date of today and the logged in user id and returns 1 and .....(we get data from server),
 * 2 if there is no entry for the queue(we dont get data from server) and 3 if statusCode not 200
 *
 * @return int that shows result interpretation
 *//*from  w w w.j  ava 2s.com*/
public int getVaccinationQueueByDateAndUser() {
    final StringBuilder webServiceUrl = createWebServiceURL("", GET_VACCINATION_QUEUE_BY_DATE_AND_USER);
    webServiceUrl.append("?date=")
            .append(new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()))
            .append("&userId=").append(getLOGGED_IN_USER_ID());
    Log.e("getVaccQueueByDt&Usr", webServiceUrl.toString());
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(webServiceUrl.toString());
        Utils.writeNetworkLogFileOnSD(
                Utils.returnDeviceIdAndTimestamp(getApplicationContext()) + webServiceUrl.toString());
        httpGet.setHeader("Authorization", "Basic " + Base64
                .encodeToString((LOGGED_IN_USERNAME + ":" + LOGGED_IN_USER_PASS).getBytes(), Base64.NO_WRAP));
        HttpResponse httpResponse = httpClient.execute(httpGet);
        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            Utils.writeNetworkLogFileOnSD(Utils.returnDeviceIdAndTimestamp(getApplicationContext())
                    + " StatusCode " + httpResponse.getStatusLine().getStatusCode() + " ReasonPhrase "
                    + httpResponse.getStatusLine().getReasonPhrase() + " ProtocolVersion "
                    + httpResponse.getStatusLine().getProtocolVersion());
            return 3;
        }
        InputStream inputStream = httpResponse.getEntity().getContent();
        String responseAsString = Utils.getStringFromInputStream(inputStream);
        Utils.writeNetworkLogFileOnSD(
                Utils.returnDeviceIdAndTimestamp(getApplicationContext()) + responseAsString);
        JSONArray jarr = new JSONArray(responseAsString);
        DatabaseHandler db = getDatabaseInstance();
        String childBarcodesNotInDB = "";
        for (int i = 0; i < jarr.length(); i++) {
            JSONObject jobj = jarr.getJSONObject(i);
            if (db.isBarcodeInChildTable(jobj.getString("BarcodeId"))) {
                String dateNow = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ")
                        .format(new Date(Long.parseLong(jobj.getString("Date").substring(6, 19))));

                ContentValues cv = new ContentValues();
                cv.put(SQLHandler.VaccinationQueueColumns.CHILD_ID,
                        db.getChildIdByBarcode(jobj.getString("BarcodeId")));
                cv.put(SQLHandler.VaccinationQueueColumns.DATE, dateNow);
                db.addChildToVaccinationQueue(cv);
            } else {
                if (childBarcodesNotInDB.length() > 0)
                    childBarcodesNotInDB += ",";
                childBarcodesNotInDB += jobj.getString("BarcodeId");
            }
        }

        if (childBarcodesNotInDB.length() > 0) {
            getChildByBarcodeList(childBarcodesNotInDB);
        }
        return 1;
    } catch (JsonGenerationException e) {
        e.printStackTrace();
        return 2;
    } catch (JsonMappingException e) {
        e.printStackTrace();
        return 2;
    } catch (IOException e) {
        e.printStackTrace();
        return 3;
    } catch (JSONException e) {
        e.printStackTrace();
        return 2;
    }
}

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private void setUserName(final String userName, final String password, final boolean syncChannels) {
    if (userName != null && password != null) {
        new Thread() {
            public void run() {
                URL documentUrl;/*from w ww.  j  a  v a2  s. c  o m*/
                try {
                    documentUrl = new URL("http://android.tvbrowser.org/data/scripts/testMyAccount.php");
                    URLConnection connection = documentUrl.openConnection();

                    String userpass = userName + ":" + password;
                    String basicAuth = "basic " + Base64.encodeToString(userpass.getBytes(), Base64.NO_WRAP);

                    connection.setRequestProperty("Authorization", basicAuth);

                    if (((HttpURLConnection) connection).getResponseCode() != 200) {
                        showUserError(userName, password, syncChannels);
                    } else {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                storeUserName(userName, password, syncChannels);
                            }
                        });
                    }

                } catch (Throwable t) {
                    showUserError(userName, password, syncChannels);
                }
            }
        }.start();
    } else if (syncChannels) {
        syncronizeChannels();
    }
}