javatips.net counter

Java Examples for android.util.Pair

The following java examples will help you to understand the usage of android.util.Pair. These source code samples are taken from different open source projects.

Example 1
Project: ohmagePhone-master  File: FilterControl.java View source code
/**
	 * Constructs the parts of the control that provide actual functionality. Declarative styling is handled by initStyles().
	 * @param context the context of whoever's creating this control, usually passed into the class constructor
	 */
protected void initControl(Context context) {
    LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
    this.setLayoutParams(params);
    this.setOrientation(HORIZONTAL);
    this.setBackgroundResource(R.color.lightergray);
    // load up the elements of the actionbar from controls_filter.xml
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.inflate(R.layout.controls_filter, this, true);
    // and init an empty list so we don't crash and burn when we try to read before populating
    mItemList = new ArrayList<Pair<String, String>>();
    mSelectionIndex = 0;
    mPrevBtn = (Button) findViewById(R.id.controls_filter_prev);
    mCurrentBtn = (Button) findViewById(R.id.controls_filter_current);
    mNextBtn = (Button) findViewById(R.id.controls_filter_next);
    FilterClickHandler handler = new FilterClickHandler();
    mPrevBtn.setOnClickListener(handler);
    mCurrentBtn.setOnClickListener(handler);
    mNextBtn.setOnClickListener(handler);
    mCurrentBtn.setSelected(true);
}
Example 2
Project: property-db-master  File: AppWidgetServiceImpl.java View source code
// Binds to a specific RemoteViewsService
public void bindRemoteViewsService(int appWidgetId, Intent intent, IBinder connection) {
    synchronized (mAppWidgetIds) {
        ensureStateLoadedLocked();
        AppWidgetId id = lookupAppWidgetIdLocked(appWidgetId);
        if (id == null) {
            throw new IllegalArgumentException("bad appWidgetId");
        }
        final ComponentName componentName = intent.getComponent();
        try {
            final ServiceInfo si = AppGlobals.getPackageManager().getServiceInfo(componentName, PackageManager.GET_PERMISSIONS, mUserId);
            if (!android.Manifest.permission.BIND_REMOTEVIEWS.equals(si.permission)) {
                throw new SecurityException("Selected service does not require " + android.Manifest.permission.BIND_REMOTEVIEWS + ": " + componentName);
            }
        } catch (RemoteException e) {
            throw new IllegalArgumentException("Unknown component " + componentName);
        }
        // If there is already a connection made for this service intent, then disconnect from
        // that first. (This does not allow multiple connections to the same service under
        // the same key)
        ServiceConnectionProxy conn = null;
        FilterComparison fc = new FilterComparison(intent);
        Pair<Integer, FilterComparison> key = Pair.create(appWidgetId, fc);
        if (mBoundRemoteViewsServices.containsKey(key)) {
            conn = (ServiceConnectionProxy) mBoundRemoteViewsServices.get(key);
            conn.disconnect();
            mContext.unbindService(conn);
            mBoundRemoteViewsServices.remove(key);
        }
        int userId = UserHandle.getUserId(id.provider.uid);
        // Bind to the RemoteViewsService (which will trigger a callback to the
        // RemoteViewsAdapter.onServiceConnected())
        final long token = Binder.clearCallingIdentity();
        try {
            conn = new ServiceConnectionProxy(key, connection);
            mContext.bindService(intent, conn, Context.BIND_AUTO_CREATE, userId);
            mBoundRemoteViewsServices.put(key, conn);
        } finally {
            Binder.restoreCallingIdentity(token);
        }
        // Add it to the mapping of RemoteViewsService to appWidgetIds so that we can determine
        // when we can call back to the RemoteViewsService later to destroy associated
        // factories.
        incrementAppWidgetServiceRefCount(appWidgetId, fc);
    }
}
Example 3
Project: TextSecureSMP-master  File: MmsDatabase.java View source code
private Pair<Long, Long> insertMessageInbox(MasterSecret masterSecret, IncomingMediaMessage retrieved, String contentLocation, long threadId, long mailbox) throws MmsException {
    PduHeaders headers = retrieved.getPduHeaders();
    ContentValues contentValues = getContentValuesFromHeader(headers);
    boolean unread = org.thoughtcrime.SMP.util.Util.isDefaultSmsProvider(context) || ((mailbox & Types.SECURE_MESSAGE_BIT) != 0);
    if (threadId == -1 || retrieved.isGroupMessage()) {
        try {
            threadId = getThreadIdFor(retrieved);
        } catch (RecipientFormattingException e) {
            Log.w("MmsDatabase", e);
            if (threadId == -1)
                throw new MmsException(e);
        }
    }
    contentValues.put(MESSAGE_BOX, mailbox);
    contentValues.put(THREAD_ID, threadId);
    contentValues.put(CONTENT_LOCATION, contentLocation);
    contentValues.put(STATUS, Status.DOWNLOAD_INITIALIZED);
    contentValues.put(DATE_RECEIVED, System.currentTimeMillis() / 1000);
    contentValues.put(READ, unread ? 0 : 1);
    if (!contentValues.containsKey(DATE_SENT)) {
        contentValues.put(DATE_SENT, contentValues.getAsLong(DATE_RECEIVED));
    }
    long messageId = insertMediaMessage(masterSecret, retrieved.getPduHeaders(), retrieved.getBody(), contentValues);
    if (unread) {
        DatabaseFactory.getThreadDatabase(context).setUnread(threadId);
    }
    DatabaseFactory.getThreadDatabase(context).update(threadId);
    notifyConversationListeners(threadId);
    jobManager.add(new TrimThreadJob(context, threadId));
    return new Pair<>(messageId, threadId);
}
Example 4
Project: iview-android-tv-master  File: AuthApi.java View source code
private void buildAuth(String stream) {
    if (stream == null) {
        stream = updateEpisodeDetails(id);
    }
    if (stream != null) {
        Pair<String, String> auth = getAuthToken();
        if (auth != null) {
            Uri.Builder builder = Uri.parse(stream).buildUpon();
            builder.authority(auth.first).appendQueryParameter("hdnea", auth.second);
            Uri url = builder.build();
            Log.d(TAG, "Stream URL:" + url);
            ContentManager.cache().putStreamUrl(id, url);
            ContentManager.getInstance().broadcastChange(ContentManager.CONTENT_AUTH_DONE, id);
        } else {
            Log.w(TAG, "Unable to build stream URL for:" + id);
        }
    } else {
        Log.w(TAG, "Unable to find stream URL for:" + id);
    }
}
Example 5
Project: xface-android-master  File: XStartAppView.java View source code
@Override
public void onReceived(Context context, XEvent evt) {
    if (evt.getType() == XEventType.XAPP_MESSAGE) {
        @SuppressWarnings("unchecked") Pair<XAppWebView, String> data = (Pair<XAppWebView, String>) evt.getData();
        handleXAppMessage(data.first, data.second);
    } else if (evt.getType() == XEventType.CLOSE_APP) {
        int viewId = (Integer) evt.getData();
        handleCloseApplication(viewId);
    } else if (evt.getType() == XEventType.CLEAR_MEMORY_CACHE) {
        mSystemCtx.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                mOwnerApp.clearCache(false);
            }
        });
    } else {
        super.onReceived(context, evt);
    }
}
Example 6
Project: codereview.chromium-master  File: SideBySideDiffAdapter.java View source code
@Override
protected void rebuildWithComments(HashMap<Pair<Integer, Boolean>, List<Comment>> lineToComments) {
    for (Object object : mergedDiffLines) {
        linesWithComments.add(object);
        if (object instanceof SkippingLine) {
            continue;
        }
        Content content = (Content) object;
        Iterator<Comment> leftIterator = iteratorFor(lineToComments, content.leftLineNumber, true);
        Iterator<Comment> rightIterator = iteratorFor(lineToComments, content.rightLineNumber, false);
        while (leftIterator.hasNext() || rightIterator.hasNext()) {
            Comment leftComment = leftIterator.hasNext() ? leftIterator.next() : null;
            Comment rightComment = rightIterator.hasNext() ? rightIterator.next() : null;
            CommentPair commentPair = new CommentPair();
            commentPair.left = leftComment;
            commentPair.right = rightComment;
            linesWithComments.add(commentPair);
        }
    }
}
Example 7
Project: MD-BiliBili-master  File: VideoView.java View source code
/**
     * Set the display options
     *
     * @param layout      <ul>
     *                    <li>[email protected] #VIDEO_LAYOUT_ORIGIN}
     *                    <li>[email protected] #VIDEO_LAYOUT_SCALE}
     *                    <li>[email protected] #VIDEO_LAYOUT_STRETCH}
     *                    <li>[email protected] #VIDEO_LAYOUT_ZOOM}
     *                    </ul>
     * @param aspectRatio video aspect ratio, will audo detect if 0.
     */
public void setVideoLayout(int layout) {
    LayoutParams lp = getLayoutParams();
    Pair<Integer, Integer> res = ScreenResolution.getResolution(mContext);
    int windowWidth = res.first.intValue(), windowHeight = res.second.intValue();
    float windowRatio = windowWidth / (float) windowHeight;
    int sarNum = mVideoSarNum;
    int sarDen = mVideoSarDen;
    if (mVideoHeight > 0 && mVideoWidth > 0) {
        float videoRatio = ((float) (mVideoWidth)) / mVideoHeight;
        if (sarNum > 0 && sarDen > 0)
            videoRatio = videoRatio * sarNum / sarDen;
        mSurfaceHeight = mVideoHeight;
        mSurfaceWidth = mVideoWidth;
        if (VIDEO_LAYOUT_ORIGIN == layout && mSurfaceWidth < windowWidth && mSurfaceHeight < windowHeight) {
            lp.width = (int) (mSurfaceHeight * videoRatio);
            lp.height = mSurfaceHeight;
        } else if (layout == VIDEO_LAYOUT_ZOOM) {
            lp.width = windowRatio > videoRatio ? windowWidth : (int) (videoRatio * windowHeight);
            lp.height = windowRatio < videoRatio ? windowHeight : (int) (windowWidth / videoRatio);
        } else {
            boolean full = layout == VIDEO_LAYOUT_STRETCH;
            lp.width = (full || windowRatio < videoRatio) ? windowWidth : (int) (videoRatio * windowHeight);
            lp.height = (full || windowRatio > videoRatio) ? windowHeight : (int) (windowWidth / videoRatio);
        }
        setLayoutParams(lp);
        getHolder().setFixedSize(mSurfaceWidth, mSurfaceHeight);
        DebugLog.dfmt(TAG, "VIDEO: %dx%dx%f[SAR:%d:%d], Surface: %dx%d, LP: %dx%d, Window: %dx%dx%f", mVideoWidth, mVideoHeight, videoRatio, mVideoSarNum, mVideoSarDen, mSurfaceWidth, mSurfaceHeight, lp.width, lp.height, windowWidth, windowHeight, windowRatio);
    }
    mVideoLayout = layout;
}
Example 8
Project: Pure-File-Manager-master  File: MediaStoreUtils.java View source code
public static void copyFiles(@NonNull final Context context, @NonNull final List<Pair<GenericFile, GenericFile>> files) {
    final int size = files.size();
    final String[] paths = new String[size];
    for (int i = 0; i < size; i++) {
        final Pair<GenericFile, GenericFile> pair = files.get(i);
        final String newPath = PFMFileUtils.fullPath(pair.second);
        paths[i] = newPath;
    }
    MediaScannerConnection.scanFile(context, paths, null, null);
}
Example 9
Project: financius-public-master  File: SmoothPathMaker.java View source code
private void addCurveToPath(Path outPath, List<PointF> curve) {
    List<Pair<PointF, PointF>> bezierControlPoints = Collections.emptyList();
    if (curve.size() > 1) {
        bezierControlPoints = getBezierControlPoints(curve);
    }
    for (int i = 0, size = curve.size(); i < size; i++) {
        final PointF point = curve.get(i);
        if (i == 0) {
            outPath.moveTo(point.x, point.y);
        } else {
            final Pair<PointF, PointF> bezierControlPointPair = bezierControlPoints.get(i - 1);
            outPath.cubicTo(bezierControlPointPair.first.x, bezierControlPointPair.first.y, bezierControlPointPair.second.x, bezierControlPointPair.second.y, point.x, point.y);
        }
    }
}
Example 10
Project: android-sdk-sources-for-api-level-23-master  File: NotificationStackScrollLayout.java View source code
/**
     * Remove a removed child view from the heads up animations if it was just added there
     *
     * @return whether any child was removed from the list to animate
     */
private boolean removeRemovedChildFromHeadsUpChangeAnimations(View child) {
    boolean hasAddEvent = false;
    for (Pair<ExpandableNotificationRow, Boolean> eventPair : mHeadsUpChangeAnimations) {
        ExpandableNotificationRow row = eventPair.first;
        boolean isHeadsUp = eventPair.second;
        if (child == row) {
            mTmpList.add(eventPair);
            hasAddEvent |= isHeadsUp;
        }
    }
    if (hasAddEvent) {
        // This child was just added lets remove all events.
        mHeadsUpChangeAnimations.removeAll(mTmpList);
    }
    mTmpList.clear();
    return hasAddEvent;
}
Example 11
Project: platform_packages_providers_downloadprovider-master  File: ThreadingTest.java View source code
public void testFilenameRace() throws Exception {
    final List<Pair<Download, String>> downloads = Lists.newArrayList();
    final HashSet<String> expectedBodies = Sets.newHashSet();
    // Request dozen files at once with same name
    for (int i = 0; i < 32; i++) {
        final String body = "DOWNLOAD " + i + " CONTENTS";
        enqueueResponse(new MockResponse().setResponseCode(HTTP_OK).setBody(body).setHeader("Content-type", "text/plain").setSocketPolicy(SocketPolicy.DISCONNECT_AT_END));
        final Download d = enqueueRequest(getRequest());
        downloads.add(Pair.create(d, body));
        expectedBodies.add(body);
        startDownload(d.mId);
    }
    final long startMillis = mSystemFacade.currentTimeMillis();
    for (Pair<Download, String> d : downloads) {
        d.first.waitForStatus(DownloadManager.STATUS_SUCCESSFUL, startMillis);
    }
    // Ensure that contents are clean and filenames unique
    final Set<String> seenFiles = Sets.newHashSet();
    final HashSet<String> actualBodies = Sets.newHashSet();
    for (Pair<Download, String> d : downloads) {
        final String file = d.first.getStringField(DownloadManager.COLUMN_LOCAL_FILENAME);
        if (!seenFiles.add(file)) {
            fail("Another download already claimed " + file);
        }
        final String expected = d.second;
        final String actual = d.first.getContents();
        actualBodies.add(actual);
    }
    assertEquals(expectedBodies, actualBodies);
}
Example 12
Project: MHacksAndroid-Public-master  File: NativeAppCallContentProvider.java View source code
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
    Pair<UUID, String> callIdAndAttachmentName = parseCallIdAndAttachmentName(uri);
    if (callIdAndAttachmentName == null) {
        throw new FileNotFoundException();
    }
    try {
        File file = dataSource.openAttachment(callIdAndAttachmentName.first, callIdAndAttachmentName.second);
        return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
    } catch (FileNotFoundException exception) {
        Log.e(TAG, "Got unexpected exception:" + exception);
        throw exception;
    }
}
Example 13
Project: CReader-master  File: BookDao.java View source code
public boolean set_book_needupdate(BookBasicBean b) {
    if (null == b) {
        return false;
    }
    if (db == null) {
        this.open();
    }
    db = dbHelper.getWritableDatabase();
    Pair<String, String> user_force = new Pair<String, String>(b.getBook_name(), b.getAuthor_name());
    if (cheak_user_force(user_force)) {
        return true;
    }
    if (db == null) {
        this.open();
    }
    db = dbHelper.getWritableDatabase();
    String sql;
    sql = "UPDATE book_table SET need_post = 1 WHERE book_name = '" + b.getBook_name() + "' and author_name = '" + b.getAuthor_name() + "'";
    db.execSQL(sql);
    db.close();
    return true;
}
Example 14
Project: android-15-master  File: ActivityManagerService.java View source code
@Override
public int compare(Pair<ProcessRecord, Integer> object1, Pair<ProcessRecord, Integer> object2) {
    if (object1.first.setAdj != object2.first.setAdj) {
        return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
    }
    if (object1.second.intValue() != object2.second.intValue()) {
        return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
    }
    return 0;
}
Example 15
Project: GeoSMS-Release-master  File: SmsManagerService.java View source code
/**
     * @param notifications list of notification entries
     * @param isReceivedType if true means that notifications is for received sms.
     *                       if false - notification is for failed sms.
     */
private void sendNotification(List<Pair<Long, Long>> notifications, boolean isReceivedType) {
    if (notifications.size() <= 0)
        return;
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext());
    Uri uri = Uri.parse("content://sms/");
    ContentResolver cv = getContentResolver();
    if (notifications.size() > 1) {
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        for (Pair<Long, Long> notif : notifications) {
            Cursor c = cv.query(uri, null, "_id=?", new String[] { "" + notif.first }, null);
            if (c == null)
                continue;
            if (!c.moveToFirst()) {
                c.close();
                Log.i(TAG, "returns null");
                continue;
            }
            String address = c.getString(c.getColumnIndex("address"));
            String text = c.getString(c.getColumnIndex("body"));
            Contact contact = new Contact(getBaseContext(), address);
            inboxStyle.addLine(Html.fromHtml(String.format("%s : %s", "<b>" + contact.getDisplayName() + "</b>", text)));
        }
        Bitmap photo = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_sms_received);
        String formatContentText = isReceivedType ? getString(R.string.unread_sms_content_format) : getString(R.string.failed_sms_content_format);
        mBuilder.setStyle(inboxStyle).setLargeIcon(photo).setSmallIcon(isReceivedType ? R.mipmap.ic_sms_received : R.mipmap.ic_sms_failed).setContentTitle(isReceivedType ? getText(R.string.geosms_unread_sms) : getText(R.string.geosms_failed_sms)).setContentText(String.format(formatContentText, notifications.size())).setDefaults(Notification.DEFAULT_ALL).setAutoCancel(true).setGroup(GROUP).setColor(Color.argb(100, 20, 80, 200)).setGroupSummary(true);
        Intent resultIntent = new Intent(this, ConversationsListActivity.class);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(ConversationsListActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        Intent dismissedPI = new Intent(Constants.Actions.RECEIVED_NOTIFICATION_DISMISSED, null, this, SmsReceiver.class);
        dismissedPI.putExtra(IS_SUMMARY, true);
        //dismissedPI.putExtra(Constants.NOTIFICATION_ARRAY, notifications.toArray());
        dismissedPI.putExtra(Constants.NOTIFICATION_TYPE, isReceivedType ? 0 : 1);
        int uniqueInt = new Random().nextInt();
        mBuilder.setDeleteIntent(PendingIntent.getBroadcast(this, uniqueInt, dismissedPI, PendingIntent.FLAG_CANCEL_CURRENT));
        notificationManager.notify(isReceivedType ? RECEIVED_TAG : FAILED_TAG, SUMMARY, mBuilder.build());
    } else {
        Cursor c = cv.query(uri, null, "_id=?", new String[] { "" + notifications.get(0).first }, null);
        if (c == null)
            return;
        if (!c.moveToFirst()) {
            c.close();
            return;
        }
        String address = c.getString(c.getColumnIndex("address"));
        String text = c.getString(c.getColumnIndex("body"));
        Contact contact = new Contact(getBaseContext(), address);
        contact.resolveContactImage(getApplicationContext(), 100);
        Bitmap photo = contact.getPhoto();
        mBuilder.setLargeIcon(photo).setSmallIcon(isReceivedType ? R.mipmap.ic_sms_received : R.mipmap.ic_sms_failed).setContentTitle(isReceivedType ? contact.getDisplayName() : getString(R.string.sms_sending_faild)).setDefaults(Notification.DEFAULT_ALL).setContentText(text).setStyle(new NotificationCompat.BigTextStyle().bigText(text)).setAutoCancel(true).setGroup(GROUP);
        // now build callback
        Intent resultIntent = new Intent(this, ConversationActivity.class);
        ArrayList<Contact> data = new ArrayList<>(1);
        data.add(contact);
        resultIntent.putExtra(Constants.CONTACT_DATA, data);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(ConversationActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        int uniqueInt = new Random().nextInt();
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(uniqueInt, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        Intent dismissedPI = new Intent(Constants.Actions.RECEIVED_NOTIFICATION_DISMISSED, null, this, SmsReceiver.class);
        long threadId = notifications.get(0).second;
        dismissedPI.putExtra(IS_SUMMARY, true);
        dismissedPI.putExtra(Constants.NOTIFICATION_TYPE, isReceivedType ? 0 : 1);
        dismissedPI.putExtra(Constants.THREAD_ID, threadId);
        Log.i(TAG, "thread_id " + threadId);
        uniqueInt = new Random().nextInt();
        mBuilder.setDeleteIntent(PendingIntent.getBroadcast(this, uniqueInt, dismissedPI, PendingIntent.FLAG_CANCEL_CURRENT));
        notificationManager.notify(isReceivedType ? RECEIVED_TAG : FAILED_TAG, (int) threadId, mBuilder.build());
    }
}
Example 16
Project: openxface-android-master  File: XRuntime.java View source code
@SuppressWarnings("unchecked")
@Override
public void onReceived(Context context, XEvent evt) {
    if (evt.getType() == XEventType.CLOSE_APP) {
        int viewId = (Integer) evt.getData();
        mStartApp.getEventHandler().onCloseApplication(viewId);
    } else if (evt.getType() == XEventType.CLOSE_ENGINE) {
        mSystemContext.getActivity().finish();
    } else if (evt.getType() == XEventType.XAPP_MESSAGE) {
        Pair<XAppWebView, String> data = (Pair<XAppWebView, String>) evt.getData();
        mStartApp.getEventHandler().onXAppMessageReceived(data.first, data.second);
    }
}
Example 17
Project: Appsii-master  File: YahooWeatherApiClient.java View source code
@VisibleForTesting
static LocationInfo parseLocationInfo(LocationInfo li, InputStream in) throws XmlPullParserException, IOException, CantGetWeatherException {
    CircularArray<Pair<String, String>> alternateWoeids = new CircularArray<>();
    String primaryWoeid = null;
    XmlPullParser xpp = sXmlPullParserFactory.newPullParser();
    xpp.setInput(new InputStreamReader(in));
    boolean inWoe = false;
    boolean inTown = false;
    boolean inCountry = false;
    boolean inTimezone = false;
    int eventType = xpp.getEventType();
    while (eventType != XmlPullParser.END_DOCUMENT) {
        String tagName = xpp.getName();
        if (eventType == XmlPullParser.START_TAG && "woeid".equals(tagName)) {
            inWoe = true;
        } else if (eventType == XmlPullParser.TEXT && inWoe) {
            primaryWoeid = xpp.getText();
        } else if (eventType == XmlPullParser.START_TAG && tagName.startsWith("timezone")) {
            inTimezone = true;
        } else if (eventType == XmlPullParser.TEXT && inTimezone) {
            li.timezone = xpp.getText();
        } else if (eventType == XmlPullParser.START_TAG && (tagName.startsWith("locality") || tagName.startsWith("admin") || tagName.startsWith("country"))) {
            for (int i = xpp.getAttributeCount() - 1; i >= 0; i--) {
                String attrName = xpp.getAttributeName(i);
                if ("type".equals(attrName) && "Town".equals(xpp.getAttributeValue(i))) {
                    inTown = true;
                } else if ("type".equals(attrName) && "Country".equals(xpp.getAttributeValue(i))) {
                    inCountry = true;
                } else if ("woeid".equals(attrName)) {
                    String woeid = xpp.getAttributeValue(i);
                    if (!TextUtils.isEmpty(woeid)) {
                        alternateWoeids.addLast(new Pair<>(tagName, woeid));
                    }
                }
            }
        } else if (eventType == XmlPullParser.TEXT && inTown) {
            li.town = xpp.getText();
        } else if (eventType == XmlPullParser.TEXT && inCountry) {
            li.country = xpp.getText();
        }
        if (eventType == XmlPullParser.END_TAG) {
            inWoe = false;
            inTown = false;
            inCountry = false;
            inTimezone = false;
        }
        eventType = xpp.next();
    }
    // Add the primary woeid if it was found.
    if (!TextUtils.isEmpty(primaryWoeid)) {
        li.woeids.addLast(primaryWoeid);
    }
    // Sort by descending tag name to order by decreasing precision
    // (locality3, locality2, locality1, admin3, admin2, admin1, etc.)
    ArrayUtils.sort(alternateWoeids, new Comparator<Pair<String, String>>() {

        @Override
        public int compare(Pair<String, String> pair1, Pair<String, String> pair2) {
            return pair1.first.compareTo(pair2.first);
        }
    });
    int N = alternateWoeids.size();
    for (int i = 0; i < N; i++) {
        Pair<String, String> pair = alternateWoeids.get(i);
        li.woeids.addLast(pair.second);
    }
    if (li.woeids.size() > 0) {
        return li;
    }
    throw new CantGetWeatherException(true, R.string.no_weather_data, "No WOEIDs found nearby.");
}
Example 18
Project: TestingStuff-master  File: VideoWallDemoActivity.java View source code
private void flipNext() {
    if (!nextThumbnailLoaded || state.equals(State.VIDEO_LOADING)) {
        return;
    }
    if (state.equals(State.VIDEO_ENDED)) {
        flippingCol = videoCol;
        flippingRow = videoRow;
        state = State.VIDEO_BEING_FLIPPED_OUT;
    } else {
        Pair<Integer, Integer> nextTarget = imageWallView.getNextLoadTarget();
        flippingCol = nextTarget.first;
        flippingRow = nextTarget.second;
    }
    flippingView.setX(imageWallView.getXPosition(flippingCol, flippingRow));
    flippingView.setY(imageWallView.getYPosition(flippingCol, flippingRow));
    flippingView.setFlipInDrawable(thumbnailView.getDrawable());
    flippingView.setFlipOutDrawable(imageWallView.getImageDrawable(flippingCol, flippingRow));
    imageWallView.setImageDrawable(flippingCol, flippingRow, thumbnailView.getDrawable());
    imageWallView.hideImage(flippingCol, flippingRow);
    flippingView.setVisibility(View.VISIBLE);
    flippingView.flip();
}
Example 19
Project: Yhb-2.0-master  File: FreeFlowContainer.java View source code
/**
	 * Will move viewport to viewPortX and viewPortY values
	 * 
	 * @param isInFlingMode
	 *            Setting this
	 */
protected void moveViewport(boolean isInFlingMode) {
    mScrollableWidth = mLayout.getContentWidth() - getWidth();
    if (mScrollableWidth < 0) {
        mScrollableWidth = 0;
    }
    mScrollableHeight = mLayout.getContentHeight() - getHeight();
    if (mScrollableHeight < 0) {
        mScrollableHeight = 0;
    }
    if (isInFlingMode) {
        if (viewPortX < 0 || viewPortX > mScrollableWidth || viewPortY < 0 || viewPortY > mScrollableHeight) {
            mTouchMode = TOUCH_MODE_OVERFLING;
        }
    } else {
        if (viewPortX < -overflingDistance) {
            viewPortX = -overflingDistance;
        } else if (viewPortX > mScrollableWidth + overflingDistance) {
            viewPortX = (mScrollableWidth + overflingDistance);
        }
        if (viewPortY < (int) (-overflingDistance)) {
            viewPortY = (int) -overflingDistance;
        } else if (viewPortY > mScrollableHeight + overflingDistance) {
            viewPortY = (int) (mScrollableHeight + overflingDistance);
        }
        if (mEdgeEffectsEnabled) {
            if (viewPortX <= 0) {
                mLeftEdge.onPull(viewPortX / (-overflingDistance));
            } else if (viewPortX >= mScrollableWidth) {
                mRightEdge.onPull((viewPortX - mScrollableWidth) / (-overflingDistance));
            }
            if (viewPortY <= 0) {
                mTopEdge.onPull(viewPortY / (-overflingDistance));
            } else if (viewPortY >= mScrollableHeight) {
                mBottomEdge.onPull((viewPortY - mScrollableHeight) / (-overflingDistance));
            }
        }
    }
    LinkedHashMap<Object, FreeFlowItem> oldFrames = new LinkedHashMap<Object, FreeFlowItem>();
    copyFrames(frames, oldFrames);
    frames = new LinkedHashMap<Object, FreeFlowItem>();
    copyFrames(mLayout.getItemProxies(viewPortX, viewPortY), frames);
    LayoutChangeset changeSet = getViewChanges(oldFrames, frames, true);
    for (FreeFlowItem freeflowItem : changeSet.added) {
        addAndMeasureViewIfNeeded(freeflowItem);
        doLayout(freeflowItem);
    }
    for (Pair<FreeFlowItem, Rect> freeflowItemPair : changeSet.moved) {
        doLayout(freeflowItemPair.first);
    }
    for (FreeFlowItem freeflowItem : changeSet.removed) {
        removeViewInLayout(freeflowItem.view);
        returnItemToPoolIfNeeded(freeflowItem);
    }
    invalidate();
}
Example 20
Project: RoughCut-master  File: MediaArtistNativeHelper.java View source code
/**
     * Calculates video resolution for output clip
     * based on clip's height and aspect ratio of storyboard
     *
     * @param aspectRatio The aspect ratio of story board
     * @param height The height of clip
     *
     * @return The video resolution
     */
private int findVideoResolution(int aspectRatio, int height) {
    final Pair<Integer, Integer>[] resolutions;
    final Pair<Integer, Integer> maxResolution;
    int retValue = VideoFrameSize.SIZE_UNDEFINED;
    switch(aspectRatio) {
        case MediaProperties.ASPECT_RATIO_3_2:
            if (height == MediaProperties.HEIGHT_480)
                retValue = VideoFrameSize.NTSC;
            else if (height == MediaProperties.HEIGHT_720)
                retValue = VideoFrameSize.W720p;
            break;
        case MediaProperties.ASPECT_RATIO_16_9:
            if (height == MediaProperties.HEIGHT_480)
                retValue = VideoFrameSize.WVGA16x9;
            else if (height == MediaProperties.HEIGHT_720)
                retValue = VideoFrameSize.V720p;
            else if (height == MediaProperties.HEIGHT_1080)
                retValue = VideoFrameSize.V1080p;
            break;
        case MediaProperties.ASPECT_RATIO_4_3:
            if (height == MediaProperties.HEIGHT_480)
                retValue = VideoFrameSize.VGA;
            else if (height == MediaProperties.HEIGHT_720)
                retValue = VideoFrameSize.S720p;
            break;
        case MediaProperties.ASPECT_RATIO_5_3:
            if (height == MediaProperties.HEIGHT_480)
                retValue = VideoFrameSize.WVGA;
            break;
        case MediaProperties.ASPECT_RATIO_11_9:
            if (height == MediaProperties.HEIGHT_144)
                retValue = VideoFrameSize.QCIF;
            else if (height == MediaProperties.HEIGHT_288)
                retValue = VideoFrameSize.CIF;
            break;
    }
    if (retValue == VideoFrameSize.SIZE_UNDEFINED) {
        resolutions = MediaProperties.getSupportedResolutions(mVideoEditor.getAspectRatio());
        // Get the highest resolution
        maxResolution = resolutions[resolutions.length - 1];
        retValue = findVideoResolution(mVideoEditor.getAspectRatio(), maxResolution.second);
    }
    return retValue;
}
Example 21
Project: firetweet-master  File: Twitter4JActivitiesLoader.java View source code
@SuppressWarnings("unchecked")
@Override
public final List<ParcelableActivity> loadInBackground() {
    final File serializationFile = getSerializationFile();
    final List<ParcelableActivity> data = getData();
    if (isFirstLoad() && getTabPosition() >= 0 && serializationFile != null) {
        final List<ParcelableActivity> cached = getCachedData(serializationFile);
        if (cached != null) {
            data.addAll(cached);
            if (mComparator != null) {
                Collections.sort(data, mComparator);
            } else {
                Collections.sort(data);
            }
            return new CopyOnWriteArrayList<>(data);
        }
    }
    final List<Activity> activities;
    final boolean truncated;
    final Context context = getContext();
    final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    final int loadItemLimit = prefs.getInt(KEY_LOAD_ITEM_LIMIT, DEFAULT_LOAD_ITEM_LIMIT);
    try {
        final Paging paging = new Paging();
        paging.setCount(loadItemLimit);
        if (mMaxId > 0) {
            paging.setMaxId(mMaxId);
        }
        if (mSinceId > 0) {
            paging.setSinceId(mSinceId);
        }
        activities = new ArrayList<>();
        truncated = truncateActivities(getActivities(getTwitter(), paging), activities, mSinceId);
    } catch (final TwitterException e) {
        e.printStackTrace();
        return new CopyOnWriteArrayList<>(data);
    }
    final Pair<Long, Long> minId;
    if (activities.isEmpty()) {
        minId = new Pair<>(-1L, -1L);
    } else {
        final Activity minActivity = Collections.min(activities);
        minId = new Pair<>(minActivity.getMinPosition(), minActivity.getMaxPosition());
    }
    final boolean insertGap = minId.first > 0 && minId.second > 0 && activities.size() > 1 && !data.isEmpty() && !truncated;
    //        mHandler.post(CacheUsersStatusesTask.getRunnable(context, new StatusListResponse(mAccountIds, activities)));
    for (final Activity activity : activities) {
        final long min = activity.getMinPosition(), max = activity.getMaxPosition();
        final boolean deleted = deleteStatus(data, max);
        final boolean isGap = minId.first == min && minId.second == max && insertGap && !deleted;
        data.add(new ParcelableActivity(activity, mAccountIds, isGap));
    }
    //        }
    if (mComparator != null) {
        Collections.sort(data, mComparator);
    } else {
        Collections.sort(data);
    }
    saveCachedData(serializationFile, data);
    return new CopyOnWriteArrayList<>(data);
}
Example 22
Project: SecurePhoto-master  File: TakeImage.java View source code
@Override
protected void onPostExecute(Pair<SPFileWrapper, String> result) {
    SPFileWrapper fileWrapper = result.first;
    String outcome = result.second;
    if (fileWrapper != null) {
        Toast.makeText(TakeImage.this, getString(R.string.image_saved_successfully, fileWrapper.getName()), Toast.LENGTH_SHORT).show();
        onImageSaved(fileWrapper);
    } else
        Toast.makeText(TakeImage.this, getString(R.string.error_saving_image, outcome), Toast.LENGTH_SHORT).show();
    endBackgroundOperation();
}
Example 23
Project: platform_packages_apps_settings-master  File: TtsEngineSettingsFragment.java View source code
private void updateDefaultLocalePref(ArrayList<String> availableLangs) {
    if (availableLangs == null || availableLangs.size() == 0) {
        mLocalePreference.setEnabled(false);
        return;
    }
    Locale currentLocale = null;
    if (!mEnginesHelper.isLocaleSetToDefaultForEngine(getEngineName())) {
        currentLocale = mEnginesHelper.getLocalePrefForEngine(getEngineName());
    }
    ArrayList<Pair<String, Locale>> entryPairs = new ArrayList<Pair<String, Locale>>(availableLangs.size());
    for (int i = 0; i < availableLangs.size(); i++) {
        Locale locale = mEnginesHelper.parseLocaleString(availableLangs.get(i));
        if (locale != null) {
            entryPairs.add(new Pair<String, Locale>(locale.getDisplayName(), locale));
        }
    }
    // Sort it
    Collections.sort(entryPairs, new Comparator<Pair<String, Locale>>() {

        @Override
        public int compare(Pair<String, Locale> lhs, Pair<String, Locale> rhs) {
            return lhs.first.compareToIgnoreCase(rhs.first);
        }
    });
    // Get two arrays out of one of pairs
    // Will point to the R.string.tts_lang_use_system value
    mSelectedLocaleIndex = 0;
    CharSequence[] entries = new CharSequence[availableLangs.size() + 1];
    CharSequence[] entryValues = new CharSequence[availableLangs.size() + 1];
    entries[0] = getActivity().getString(R.string.tts_lang_use_system);
    entryValues[0] = "";
    int i = 1;
    for (Pair<String, Locale> entry : entryPairs) {
        if (entry.second.equals(currentLocale)) {
            mSelectedLocaleIndex = i;
        }
        entries[i] = entry.first;
        entryValues[i++] = entry.second.toString();
    }
    mLocalePreference.setEntries(entries);
    mLocalePreference.setEntryValues(entryValues);
    mLocalePreference.setEnabled(true);
    setLocalePreference(mSelectedLocaleIndex);
}
Example 24
Project: WordPress-Android-master  File: SiteSettingsFragment.java View source code
private void sortLanguages() {
    if (mLanguagePref == null)
        return;
    Pair<String[], String[]> pair = WPPrefUtils.createSortedLanguageDisplayStrings(mLanguagePref.getEntryValues(), WPPrefUtils.languageLocale(null));
    if (pair != null) {
        String[] sortedEntries = pair.first;
        String[] sortedValues = pair.second;
        mLanguagePref.setEntries(sortedEntries);
        mLanguagePref.setEntryValues(sortedValues);
        mLanguagePref.setDetails(WPPrefUtils.createLanguageDetailDisplayStrings(sortedValues));
    }
}
Example 25
Project: Flock-master  File: LocalContactCollection.java View source code
private List<Pair<Integer, Long>> getAggregateExceptionTypeIdPairs(Long rawContactId) throws RemoteException {
    String[] PROJECTION = new String[] { ContactsContract.AggregationExceptions.TYPE, ContactsContract.AggregationExceptions.RAW_CONTACT_ID1, ContactsContract.AggregationExceptions.RAW_CONTACT_ID2 };
    String SELECTION = ContactsContract.AggregationExceptions.RAW_CONTACT_ID1 + "=? OR " + ContactsContract.AggregationExceptions.RAW_CONTACT_ID2 + "=?";
    String[] SELECTION_ARGS = new String[] { rawContactId.toString(), rawContactId.toString() };
    List<Pair<Integer, Long>> typeIdPairs = new LinkedList<Pair<Integer, Long>>();
    Cursor cursor = client.query(ContactsContract.AggregationExceptions.CONTENT_URI, PROJECTION, SELECTION, SELECTION_ARGS, null);
    while (cursor.moveToNext()) {
        if (cursor.getLong(1) != rawContactId)
            typeIdPairs.add(new Pair<Integer, Long>(cursor.getInt(0), cursor.getLong(1)));
        else
            typeIdPairs.add(new Pair<Integer, Long>(cursor.getInt(0), cursor.getLong(2)));
    }
    cursor.close();
    return typeIdPairs;
}
Example 26
Project: edx-app-android-master  File: FragmentedMp4Extractor.java View source code
/**
   * Parses a trak atom (defined in 14496-12).
   */
private static Track parseTrak(ContainerAtom trak) {
    ContainerAtom mdia = trak.getContainerAtomOfType(Atom.TYPE_mdia);
    int trackType = parseHdlr(mdia.getLeafAtomOfType(Atom.TYPE_hdlr).data);
    Assertions.checkState(trackType == Track.TYPE_AUDIO || trackType == Track.TYPE_VIDEO);
    Pair<Integer, Long> header = parseTkhd(trak.getLeafAtomOfType(Atom.TYPE_tkhd).data);
    int id = header.first;
    // TODO: This value should be used to set a duration field on the Track object
    // instantiated below, however we've found examples where the value is 0. Revisit whether we
    // should set it anyway (and just have it be wrong for bad media streams).
    // long duration = header.second;
    long timescale = parseMdhd(mdia.getLeafAtomOfType(Atom.TYPE_mdhd).data);
    ContainerAtom stbl = mdia.getContainerAtomOfType(Atom.TYPE_minf).getContainerAtomOfType(Atom.TYPE_stbl);
    Pair<MediaFormat, TrackEncryptionBox[]> sampleDescriptions = parseStsd(stbl.getLeafAtomOfType(Atom.TYPE_stsd).data);
    return new Track(id, trackType, timescale, sampleDescriptions.first, sampleDescriptions.second);
}
Example 27
Project: WallpaperPicker-master  File: WallpaperPickerActivity.java View source code
private ArrayList<WallpaperTileInfo> findBundledWallpapers() {
    final PackageManager pm = getPackageManager();
    final ArrayList<WallpaperTileInfo> bundled = new ArrayList<WallpaperTileInfo>(24);
    Partner partner = Partner.get(pm);
    if (partner != null) {
        final Resources partnerRes = partner.getResources();
        final int resId = partnerRes.getIdentifier(Partner.RES_WALLPAPERS, "array", partner.getPackageName());
        if (resId != 0) {
            addWallpapers(bundled, partnerRes, partner.getPackageName(), resId);
        }
        // Add system wallpapers
        File systemDir = partner.getWallpaperDirectory();
        if (systemDir != null && systemDir.isDirectory()) {
            for (File file : systemDir.listFiles()) {
                if (!file.isFile()) {
                    continue;
                }
                String name = file.getName();
                int dotPos = name.lastIndexOf('.');
                String extension = "";
                if (dotPos >= -1) {
                    extension = name.substring(dotPos);
                    name = name.substring(0, dotPos);
                }
                if (name.endsWith("_small")) {
                    // it is a thumbnail
                    continue;
                }
                File thumbnail = new File(systemDir, name + "_small" + extension);
                Bitmap thumb = BitmapFactory.decodeFile(thumbnail.getAbsolutePath());
                if (thumb != null) {
                    bundled.add(new FileWallpaperInfo(file, new BitmapDrawable(thumb)));
                }
            }
        }
    }
    Pair<ApplicationInfo, Integer> r = getWallpaperArrayResourceId();
    if (r != null) {
        try {
            Resources wallpaperRes = getPackageManager().getResourcesForApplication(r.first);
            addWallpapers(bundled, wallpaperRes, r.first.packageName, r.second);
        } catch (PackageManager.NameNotFoundException e) {
        }
    }
    if (partner == null || !partner.hideDefaultWallpaper()) {
        // Add an entry for the default wallpaper (stored in system resources)
        WallpaperTileInfo defaultWallpaperInfo = (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) ? getPreKKDefaultWallpaperInfo() : getDefaultWallpaper();
        if (defaultWallpaperInfo != null) {
            bundled.add(0, defaultWallpaperInfo);
        }
    }
    return bundled;
}
Example 28
Project: SmartAndroidSource-master  File: HandleUtil.java View source code
/**
	 * Calculates the offset of the touch point from the precise location of the
	 * specified handle.
	 * 
	 * @return the offset as a Pair where the x-offset is the first value and
	 *         the y-offset is the second value; null if the handle is null
	 */
public static Pair<Float, Float> getOffset(Handle handle, float x, float y, float left, float top, float right, float bottom) {
    if (handle == null) {
        return null;
    }
    float touchOffsetX = 0;
    float touchOffsetY = 0;
    // Calculate the offset from the appropriate handle.
    switch(handle) {
        case TOP_LEFT:
            touchOffsetX = left - x;
            touchOffsetY = top - y;
            break;
        case TOP_RIGHT:
            touchOffsetX = right - x;
            touchOffsetY = top - y;
            break;
        case BOTTOM_LEFT:
            touchOffsetX = left - x;
            touchOffsetY = bottom - y;
            break;
        case BOTTOM_RIGHT:
            touchOffsetX = right - x;
            touchOffsetY = bottom - y;
            break;
        case LEFT:
            touchOffsetX = left - x;
            touchOffsetY = 0;
            break;
        case TOP:
            touchOffsetX = 0;
            touchOffsetY = top - y;
            break;
        case RIGHT:
            touchOffsetX = right - x;
            touchOffsetY = 0;
            break;
        case BOTTOM:
            touchOffsetX = 0;
            touchOffsetY = bottom - y;
            break;
        case CENTER:
            final float centerX = (right + left) / 2;
            final float centerY = (top + bottom) / 2;
            touchOffsetX = centerX - x;
            touchOffsetY = centerY - y;
            break;
    }
    final Pair<Float, Float> result = new Pair<Float, Float>(touchOffsetX, touchOffsetY);
    return result;
}
Example 29
Project: platform_tools_adt_idea-master  File: AppResourceRepository.java View source code
public void setCompiledResources(TIntObjectHashMap<Pair<ResourceType, String>> id2res, Map<IntArrayWrapper, String> styleableId2name, Map<ResourceType, TObjectIntHashMap<String>> res2id) {
    // Regularly clear dynamic seed such that we don't run out of numbers (we only have 255)
    synchronized (myName2DynamicIdMap) {
        myDynamicSeed = DYNAMIC_ID_SEED_START;
        myName2DynamicIdMap.clear();
        myDynamicId2ResourceMap.clear();
    }
    myResourceValueMap = res2id;
    myResIdValueToNameMap = id2res;
    myStyleableValueToNameMap = styleableId2name;
//    AarResourceClassRegistry.get().clear();
}
Example 30
Project: SyncthingAndroid-master  File: LoginPresenter.java View source code
void fetchApiKey() {
    if (!hasView())
        return;
    state = State.LOADING;
    showLoading();
    String url = SyncthingUtils.buildUrl(//TODO undocumented behavior (default port)
    host, StringUtils.isEmpty(port) ? (tls ? "443" : "80") : port, tls);
    Timber.d("Logging into %s", url);
    credentials.set(credentials.get().buildUpon().setUrl(url).build());
    configBuilder.setUrl(url);
    configBuilder.setAuth(SyncthingUtils.buildAuthorization(user, pass));
    configBuilder.setDebug(true);
    if (session != null) {
        manager.release(session);
    }
    session = manager.acquire(configBuilder.build());
    final SyncthingApi api = SynchingApiWrapper.wrap(session.api(), Schedulers.io());
    subscription = rx.Observable.zip(api.config(), api.system(), Pair::create).observeOn(AndroidSchedulers.mainThread()).subscribe( pair -> {
        Credentials.Builder builder = credentials.get().buildUpon();
        builder.setId(pair.second.myID);
        builder.setApiKey(pair.first.gui.apiKey);
        if (StringUtils.isEmpty(alias)) {
            for (DeviceConfig d : pair.first.devices) {
                if (StringUtils.equals(d.deviceID, pair.second.myID)) {
                    builder.setAlias(SyncthingUtils.getDisplayName(d));
                    break;
                }
            }
        } else {
            builder.setAlias(alias);
        }
        credentials.set(builder.build());
    }, this::notifyLoginError, this::saveKeyAndFinish);
}
Example 31
Project: Musubi-Android-master  File: AphidIdentityProvider.java View source code
private byte[] getAphidResultForIdentity(IBIdentity ident, String property) throws IdentityProviderException {
    Log.d(TAG, "Getting key for " + ident.principal_);
    // Populate tokens from identity providers (only Google and Facebook for now)
    try {
        cacheGoogleTokens();
    } catch (IdentityProviderException.Auth e) {
        if (e.identity.equalsStable(ident)) {
            throw new IdentityProviderException.Auth(ident);
        }
    } catch (IdentityProviderException.NeedsRetry e) {
        if (e.identity.equalsStable(ident)) {
            throw new IdentityProviderException.NeedsRetry(ident);
        }
    }
    try {
        cacheCurrentFacebookToken();
    } catch (IdentityProviderException e) {
        if (e.identity.equalsStable(ident)) {
            throw new IdentityProviderException.Auth(ident);
        }
    }
    String aphidType = null;
    String aphidToken = null;
    // Get a service-specific token if it exists
    Pair<Authority, String> userProperties = new Pair<Authority, String>(ident.authority_, ident.principal_);
    if (mKnownTokens.containsKey(userProperties)) {
        aphidToken = mKnownTokens.get(userProperties);
    }
    // The IBE server has its own identifiers for providers
    switch(ident.authority_) {
        case Facebook:
            aphidType = "facebook";
            break;
        case Email:
            if (mKnownTokens.containsKey(userProperties)) {
                aphidType = "google";
            }
            break;
        case PhoneNumber:
            // Aphid doesn't return keys for a phone number without verification
            throw new IdentityProviderException.TwoPhase(ident);
    }
    // Do not ask the server for identities we don't know how to handle
    if (aphidType == null || aphidToken == null) {
        throw new IdentityProviderException(ident);
    }
    // Bundle arguments as JSON
    JSONObject jsonObj = new JSONObject();
    try {
        jsonObj.put("type", aphidType);
        jsonObj.put("token", aphidToken);
        jsonObj.put("starttime", ident.temporalFrame_);
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
    }
    JSONArray userinfo = new JSONArray();
    userinfo.put(jsonObj);
    // Contact the server
    try {
        JSONObject resultObj = getAphidResult(userinfo);
        if (resultObj == null) {
            throw new IdentityProviderException.NeedsRetry(ident);
        }
        String encodedKey = resultObj.getString(property);
        boolean hasError = resultObj.has("error");
        if (!hasError) {
            long temporalFrame = resultObj.getLong("time");
            if (encodedKey != null && temporalFrame == ident.temporalFrame_) {
                // Success!
                return Base64.decode(encodedKey, Base64.DEFAULT);
            } else {
                // Might have jumped the gun a little bit, so try again later
                throw new IdentityProviderException.NeedsRetry(ident);
            }
        } else {
            // Aphid authentication error means Musubi has a bad token
            String error = resultObj.getString("error");
            if (error.contains("401")) {
                // Authentication errors require user action
                String accountType = Character.toString(Character.toUpperCase(aphidType.charAt(0))) + aphidType.substring(1);
                sendNotification(accountType);
                throw new IdentityProviderException.Auth(ident);
            } else {
                // Other failures should be retried silently
                throw new IdentityProviderException.NeedsRetry(ident);
            }
        }
    } catch (IOException e) {
        Log.e(TAG, e.toString());
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
    }
    throw new IdentityProviderException.NeedsRetry(ident);
}
Example 32
Project: wally-master  File: SearchFragment.java View source code
@Override
public boolean handleMessage(Message msg) {
    switch(msg.what) {
        case MSG_GET_IMAGES:
            final int index = msg.arg1;
            String query = (String) msg.obj;
            WallyApplication.getDataProviderInstance().getImages(NetworkDataProvider.PATH_SEARCH, query, currentColor, index, WallyApplication.getFilterSettings(), new DataProvider.OnImagesReceivedListener() {

                @Override
                public void onImagesReceived(ArrayList<Image> images) {
                    Message msgObj = uiHandler.obtainMessage();
                    msgObj.what = index == 1 ? MSG_IMAGES_REQUEST_CREATE : MSG_IMAGES_REQUEST_APPEND;
                    msgObj.obj = images;
                    uiHandler.sendMessage(msgObj);
                }

                @Override
                public void onError(DataProviderError dataProviderError) {
                    showError(dataProviderError, index);
                }
            });
            break;
        case MSG_SAVE_BUTTON_CLICKED:
            Image image = (Image) msg.obj;
            WallyApplication.getDataProviderInstance().getPageData(image.imagePageURL(), new DataProvider.OnPageReceivedListener() {

                @Override
                public void onPageReceived(ImagePage imagePage) {
                    Message msgImagePage = uiHandler.obtainMessage();
                    msgImagePage.what = MSG_PAGE_RECEIVED;
                    msgImagePage.obj = imagePage;
                    uiHandler.sendMessage(msgImagePage);
                }

                @Override
                public void onError(DataProviderError dataProviderError) {
                    Message msgObj = uiHandler.obtainMessage();
                    msgObj.what = MSG_ERROR_IMAGE_SAVING;
                    msgObj.obj = dataProviderError;
                    uiHandler.sendMessage(msgObj);
                }
            });
            break;
        case MSG_PAGE_RECEIVED:
            ImagePage imagePage = (ImagePage) msg.obj;
            if (imagePage != null) {
                SaveImageRequest saveImageRequest = WallyApplication.getDataProviderInstance().downloadImageIfNeeded(imagePage.imagePath(), imagePage.imageId(), getResources().getString(R.string.notification_title_image_saving));
                if (saveImageRequest.getDownloadID() != null && getActivity() instanceof MainActivity) {
                    WallyApplication.getDownloadIDs().put(saveImageRequest.getDownloadID(), imagePage.imageId());
                } else {
                    getActivity().sendBroadcast(new Intent(FileReceiver.GET_FILES));
                }
            }
            break;
        case MSG_ERROR_IMAGE_REQUEST:
            if (getActivity() != null) {
                DataProviderError dataProviderError = (DataProviderError) msg.obj;
                int imagesIndex = msg.arg1;
                showErrorMessage(dataProviderError, imagesIndex);
            }
            break;
        case MSG_ERROR_IMAGE_SAVING:
            if (getActivity() != null) {
                NotificationProvider notificationProvider = new NotificationProvider();
                notificationProvider.cancelAll(getActivity());
                Toast.makeText(getActivity(), "Couldn't save image", Toast.LENGTH_SHORT).show();
            }
            break;
        case MSG_IMAGES_REQUEST_CREATE:
            ArrayList<Image> images = (ArrayList<Image>) msg.obj;
            boolean shouldScheduleLayoutAnimation = msg.arg1 == 0;
            isLoading = false;
            if (images != null) {
                hideLoader();
                imagesAdapter = new RecyclerImagesAdapter(images, itemSize);
                imagesAdapter.setOnSaveButtonClickedListener(SearchFragment.this);
                imagesAdapter.updateSavedFilesList(savedFiles);
                gridView.setAdapter(imagesAdapter);
                setupAdapter();
                if (shouldScheduleLayoutAnimation) {
                    gridView.scheduleLayoutAnimation();
                }
            }
            break;
        case MSG_IMAGES_REQUEST_APPEND:
            ArrayList<Image> extraImages = (ArrayList<Image>) msg.obj;
            isLoading = false;
            if (extraImages != null) {
                hideLoader();
                int endPosition = imagesAdapter.getItemCount();
                ArrayList<Image> currentList = imagesAdapter.getImages();
                currentList.addAll(extraImages);
                imagesAdapter.notifyItemRangeInserted(endPosition, extraImages.size());
            }
            break;
        case MSG_SAVE_LIST_OF_SAVED_IMAGES:
            savedFiles = (HashMap<String, Boolean>) msg.obj;
            if (imagesAdapter != null) {
                imagesAdapter.updateSavedFilesList(savedFiles);
                imagesAdapter.notifySavedItemsChanged();
            }
            break;
        case MSG_NEW_COLOR_FETCHED:
            int color = msg.arg1;
            String colorHex = Integer.toHexString(color).substring(2);
            int[] colors = new int[1];
            colors[0] = color;
            //Use this to create a Palette.
            Bitmap bitmapColor = Bitmap.createBitmap(colors, 1, 1, Bitmap.Config.ARGB_8888);
            Palette palette = Palette.generate(bitmapColor);
            Message newColorMessage = uiHandler.obtainMessage();
            newColorMessage.what = MSG_RENDER_NEW_COLOR;
            newColorMessage.obj = new Pair<String, Palette>(colorHex, palette);
            uiHandler.sendMessage(newColorMessage);
            break;
        case MSG_RENDER_NEW_COLOR:
            Pair<String, Palette> pair = (Pair<String, Palette>) msg.obj;
            String colorAsHex = pair.first;
            Palette palette1 = pair.second;
            showColorTag(colorAsHex, palette1);
            break;
    }
    return false;
}
Example 33
Project: enviroCar-app-master  File: CarSelectionAddCarFragment.java View source code
private Func1<Car, Car> checkCarAlreadyExist() {
    return  car -> {
        String manu = car.getManufacturer();
        String model = car.getModel();
        String year = "" + car.getConstructionYear();
        String engine = "" + car.getEngineDisplacement();
        Pair<String, String> modelYear = new Pair<>(model, year);
        Car selectedCar = null;
        if (mManufacturerNames.contains(manu) && mCarToModelMap.get(manu) != null && mCarToModelMap.get(manu).contains(model) && mModelToYear.get(model) != null && mModelToYear.get(model).contains(year) && mModelToCCM.get(modelYear) != null && mModelToCCM.get(modelYear).contains(engine)) {
            for (Car other : mCars) {
                if (other.getManufacturer().equals(manu) && other.getModel().equals(model) && other.getConstructionYear() == car.getConstructionYear() && other.getEngineDisplacement() == car.getEngineDisplacement() && other.getFuelType() == car.getFuelType()) {
                    selectedCar = other;
                    break;
                }
            }
        }
        if (selectedCar == null) {
            LOG.info("New Car type. Register car at server.");
            carManager.registerCarAtServer(car);
            return car;
        } else {
            LOG.info(String.format("Car already existed -> [%s]", selectedCar.getId()));
            return selectedCar;
        }
    };
}
Example 34
Project: syncthing-android-master  File: SyncthingService.java View source code
@Override
protected void onPostExecute(Pair<URL, String> urlAndKey) {
    if (urlAndKey == null) {
        Toast.makeText(SyncthingService.this, R.string.config_create_failed, Toast.LENGTH_LONG).show();
        mCurrentState = State.ERROR;
        onApiChange();
        return;
    }
    mApi = new RestApi(SyncthingService.this, urlAndKey.first, urlAndKey.second, () -> {
        mCurrentState = State.ACTIVE;
        onApiChange();
        new Thread(() -> {
            for (RestApi.Folder r : mApi.getFolders()) {
                try {
                    mObservers.add(new FolderObserver(mApi, r));
                } catch (FolderObserver.FolderNotExistingException e) {
                    Log.w(TAG, "Failed to add observer for folder", e);
                } catch (StackOverflowError e) {
                    Log.w(TAG, "Failed to add folder observer", e);
                    Toast.makeText(SyncthingService.this, R.string.toast_folder_observer_stack_overflow, Toast.LENGTH_LONG).show();
                }
            }
        }).start();
    }, SyncthingService.this::onApiChange);
    mEventProcessor = new EventProcessor(SyncthingService.this, mApi);
    registerOnWebGuiAvailableListener(mApi);
    registerOnWebGuiAvailableListener(mEventProcessor);
    Log.i(TAG, "Web GUI will be available at " + mConfig.getWebGuiUrl());
    updateState();
}
Example 35
Project: XieDaDeng-master  File: AlternateRecentsComponent.java View source code
/** Prepares the search bar app widget */
void reloadSearchBarAppWidget(Context context, SystemServicesProxy ssp) {
    // have the right thumbnail bounds to animate to.
    if (Constants.DebugFlags.App.EnableSearchLayout) {
        Log.d(TAG, "reloadSearchBarAppWidget mConfig.searchBarAppWidgetId = " + mConfig.searchBarAppWidgetId);
        // If there is no id, then bind a new search app widget
        if (mConfig.searchBarAppWidgetId < 0) {
            AppWidgetHost host = new RecentsAppWidgetHost(context, Constants.Values.App.AppWidgetHostId);
            Pair<Integer, AppWidgetProviderInfo> widgetInfo = ssp.bindSearchAppWidget(host);
            if (widgetInfo != null) {
                // Save the app widget id into the settings
                mConfig.updateSearchBarAppWidgetId(context, widgetInfo.first);
            }
        }
    }
}
Example 36
Project: Nimingban-master  File: PostFragment.java View source code
@Override
public void onSuccess(Pair<Post, List<Reply>> result) {
    if (mNMBRequest == mRequest) {
        // It is current request
        // Clear
        mNMBRequest = null;
        Post post = result.first;
        mPostUser = post.getNMBDisplayUsername();
        List<Reply> replies = result.second;
        if (mPage == 0) {
            mPageSize = replies.size();
            replies.add(0, post);
        }
        boolean empty;
        if (replies.isEmpty()) {
            empty = true;
            mReplyHelper.onGetEmptyData(mTaskId);
        } else {
            empty = false;
            mReplyHelper.onGetPageData(mTaskId, replies);
        }
        if (!empty && (mTaskType == ContentLayout.ContentHelper.TYPE_NEXT_PAGE || mTaskType == ContentLayout.ContentHelper.TYPE_NEXT_PAGE_KEEP_POS || mTaskType == ContentLayout.ContentHelper.TYPE_REFRESH || mTaskType == ContentLayout.ContentHelper.TYPE_SOMEWHERE) && mReplyHelper.size() == post.getNMBReplyCount() + 1) {
            // post is in data, so +1
            // this is the last page
            mReplyHelper.setPages(mPage + 1);
        } else if (mPageSize == 0) {
            // Only post, no reply
            mReplyHelper.setPages(1);
        } else if (empty && (mTaskType == ContentLayout.ContentHelper.TYPE_NEXT_PAGE || mTaskType == ContentLayout.ContentHelper.TYPE_NEXT_PAGE_KEEP_POS)) {
            // previous page is the last page
            mReplyHelper.setPages(mPage);
        } else if (mPageSize != -1) {
            // Guess2
            mReplyHelper.setPages(MathUtils.ceilDivide(post.getNMBReplyCount(), mPageSize));
        } else if (mTaskType == ContentLayout.ContentHelper.TYPE_REFRESH_PAGE || mTaskType == ContentLayout.ContentHelper.TYPE_PRE_PAGE || mTaskType == ContentLayout.ContentHelper.TYPE_PRE_PAGE_KEEP_POS || mTaskType == ContentLayout.ContentHelper.TYPE_SOMEWHERE) {
        // Keep the pages
        } else {
            int pages = mReplyHelper.getPages();
            if (pages != -1 && pages != Integer.MAX_VALUE) {
            // Keep it
            } else if (empty) {
                // At least we get post
                mReplyHelper.setPages(1);
            } else {
                // Keep going
                mReplyHelper.setPages(Integer.MAX_VALUE);
            }
        }
    }
    // Clear
    mRequest = null;
}
Example 37
Project: download-manager-master  File: DownloadTask.java View source code
/**
     * Add custom headers for this download to the HTTP request.
     */
private void addRequestHeaders(State state, HttpURLConnection conn) {
    for (Pair<String, String> header : originalDownloadInfo.getHeaders()) {
        conn.addRequestProperty(header.first, header.second);
    }
    // Only splice in user agent when not already defined
    if (conn.getRequestProperty("User-Agent") == null) {
        conn.addRequestProperty("User-Agent", userAgent());
    }
    // Defeat transparent gzip compression, since it doesn't allow us to
    // easily resume partial downloads.
    conn.setRequestProperty("Accept-Encoding", "identity");
    if (state.continuingDownload) {
        if (state.headerETag != null) {
            conn.addRequestProperty("If-Match", state.headerETag);
        }
        conn.addRequestProperty("Range", "bytes=" + state.currentBytes + "-");
    }
}
Example 38
Project: ijoomer-adv-sdk-master  File: WebDialog.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setOnCancelListener(new OnCancelListener() {

        @Override
        public void onCancel(DialogInterface dialogInterface) {
            sendCancelToListener();
        }
    });
    spinner = new ProgressDialog(getContext());
    spinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
    spinner.setMessage(getContext().getString(R.string.com_facebook_loading));
    spinner.setOnCancelListener(new OnCancelListener() {

        @Override
        public void onCancel(DialogInterface dialogInterface) {
            sendCancelToListener();
            WebDialog.this.dismiss();
        }
    });
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    contentFrameLayout = new FrameLayout(getContext());
    // First calculate the margins around the frame layout
    Pair<Integer, Integer> margins = getMargins();
    contentFrameLayout.setPadding(margins.first, margins.second, margins.first, margins.second);
    /* Create the 'x' image, but don't add to the contentFrameLayout layout yet
         * at this point, we only need to know its drawable width and height
         * to place the webview
         */
    createCrossImage();
    /* Now we know 'x' drawable width and height,
         * layout the webview and add it the contentFrameLayout layout
         */
    int crossWidth = crossImageView.getDrawable().getIntrinsicWidth();
    setUpWebView(crossWidth / 2 + 1);
    /* Finally add the 'x' image to the contentFrameLayout layout and
        * add contentFrameLayout to the Dialog view
        */
    contentFrameLayout.addView(crossImageView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    addContentView(contentFrameLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
Example 39
Project: iosched4eclipse-master  File: SessionDetailFragment.java View source code
private void buildLinksSection(Cursor cursor) {
    final Context context = mRootView.getContext();
    // Compile list of links (I/O live link, submit feedback, and normal links)
    ViewGroup linkContainer = (ViewGroup) mRootView.findViewById(R.id.links_container);
    linkContainer.removeAllViews();
    // Build links section
    // the Object can be either a string URL or an Intent
    List<Pair<Integer, Object>> links = new ArrayList<Pair<Integer, Object>>();
    long currentTimeMillis = UIUtils.getCurrentTime(context);
    if (mHasLivestream && currentTimeMillis > mSessionStart && currentTimeMillis <= mSessionEnd) {
        links.add(new Pair<Integer, Object>(R.string.session_link_livestream, getWatchLiveIntent(context)));
    }
    // Add session feedback link, if appropriate
    if (!mAlreadyGaveFeedback && currentTimeMillis > mSessionEnd - Config.FEEDBACK_MILLIS_BEFORE_SESSION_END) {
        links.add(new Pair<Integer, Object>(R.string.session_feedback_submitlink, getFeedbackIntent()));
    }
    for (int i = 0; i < SessionsQuery.LINKS_INDICES.length; i++) {
        final String linkUrl = cursor.getString(SessionsQuery.LINKS_INDICES[i]);
        if (TextUtils.isEmpty(linkUrl)) {
            continue;
        }
        links.add(new Pair<Integer, Object>(SessionsQuery.LINKS_TITLES[i], new Intent(Intent.ACTION_VIEW, Uri.parse(linkUrl)).addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)));
    }
    // Render links
    if (links.size() > 0) {
        LayoutInflater inflater = LayoutInflater.from(context);
        int columns = context.getResources().getInteger(R.integer.links_columns);
        LinearLayout currentLinkRowView = null;
        for (int i = 0; i < links.size(); i++) {
            final Pair<Integer, Object> link = links.get(i);
            // Create link view
            TextView linkView = (TextView) inflater.inflate(R.layout.list_item_session_link, linkContainer, false);
            if (link.first == R.string.session_feedback_submitlink) {
                mSubmitFeedbackView = linkView;
            }
            linkView.setText(getString(link.first));
            linkView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    fireLinkEvent(link.first);
                    Intent intent = null;
                    if (link.second instanceof Intent) {
                        intent = (Intent) link.second;
                    } else if (link.second instanceof String) {
                        intent = new Intent(Intent.ACTION_VIEW, Uri.parse((String) link.second)).addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                    }
                    try {
                        startActivity(intent);
                    } catch (ActivityNotFoundException ignored) {
                    }
                }
            });
            // Place it inside a container
            if (columns == 1) {
                linkContainer.addView(linkView);
            } else {
                // create a new link row
                if (i % columns == 0) {
                    currentLinkRowView = (LinearLayout) inflater.inflate(R.layout.include_link_row, linkContainer, false);
                    currentLinkRowView.setWeightSum(columns);
                    linkContainer.addView(currentLinkRowView);
                }
                ((LinearLayout.LayoutParams) linkView.getLayoutParams()).width = 0;
                ((LinearLayout.LayoutParams) linkView.getLayoutParams()).weight = 1;
                currentLinkRowView.addView(linkView);
            }
        }
        mRootView.findViewById(R.id.session_links_header).setVisibility(View.VISIBLE);
        mRootView.findViewById(R.id.links_container).setVisibility(View.VISIBLE);
    } else {
        mRootView.findViewById(R.id.session_links_header).setVisibility(View.GONE);
        mRootView.findViewById(R.id.links_container).setVisibility(View.GONE);
    }
}
Example 40
Project: android_packages_apps-master  File: Workspace.java View source code
/**
     * Tests to see if the drop will be accepted by Launcher, and if so, includes additional data
     * in the returned structure related to the widgets that match the drop (or a null list if it is
     * a shortcut drop).  If the drop is not accepted then a null structure is returned.
     */
private Pair<Integer, List<WidgetMimeTypeHandlerData>> validateDrag(DragEvent event) {
    final LauncherModel model = mLauncher.getModel();
    final ClipDescription desc = event.getClipDescription();
    final int mimeTypeCount = desc.getMimeTypeCount();
    for (int i = 0; i < mimeTypeCount; ++i) {
        final String mimeType = desc.getMimeType(i);
        if (mimeType.equals(InstallShortcutReceiver.SHORTCUT_MIMETYPE)) {
            return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, null);
        } else {
            final List<WidgetMimeTypeHandlerData> widgets = model.resolveWidgetsForMimeType(mContext, mimeType);
            if (widgets.size() > 0) {
                return new Pair<Integer, List<WidgetMimeTypeHandlerData>>(i, widgets);
            }
        }
    }
    return null;
}