code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * HorizontalListView.java v1.5 * * * The MIT License * Copyright (c) 2011 Paul Soucy (paul@dev-smart.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.aviary.android.feather.widget; import java.util.LinkedList; import java.util.Queue; import android.content.Context; import android.database.DataSetObserver; import android.graphics.Rect; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.Scroller; import com.aviary.android.feather.library.log.LoggerFactory; // TODO: Auto-generated Javadoc /** * The Class HorizontialListView. */ public class HorizontalListView extends AdapterView<ListAdapter> { /** The m always override touch. */ public boolean mAlwaysOverrideTouch = true; /** The m adapter. */ protected ListAdapter mAdapter; /** The m left view index. */ private int mLeftViewIndex = -1; /** The m right view index. */ private int mRightViewIndex = 0; /** The m current x. */ protected int mCurrentX; /** The m next x. */ protected int mNextX; /** The m max x. */ private int mMaxX = Integer.MAX_VALUE; /** The m display offset. */ private int mDisplayOffset = 0; /** The m scroller. */ protected Scroller mScroller; /** The m gesture. */ private GestureDetector mGesture; /** The m removed view queue. */ private Queue<View> mRemovedViewQueue = new LinkedList<View>(); /** The m on item selected. */ private OnItemSelectedListener mOnItemSelected; /** The m on item clicked. */ private OnItemClickListener mOnItemClicked; /** The m data changed. */ private boolean mDataChanged = false; /** * Instantiates a new horizontial list view. * * @param context * the context * @param attrs * the attrs */ public HorizontalListView( Context context, AttributeSet attrs ) { super( context, attrs ); initView(); } /** * Inits the view. */ private synchronized void initView() { mLeftViewIndex = -1; mRightViewIndex = 0; mDisplayOffset = 0; mCurrentX = 0; mNextX = 0; mMaxX = Integer.MAX_VALUE; mScroller = new Scroller( getContext() ); mGesture = new GestureDetector( getContext(), mOnGesture ); } /* * (non-Javadoc) * * @see android.widget.AdapterView#setOnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener) */ @Override public void setOnItemSelectedListener( AdapterView.OnItemSelectedListener listener ) { mOnItemSelected = listener; } /* * (non-Javadoc) * * @see android.widget.AdapterView#setOnItemClickListener(android.widget.AdapterView.OnItemClickListener) */ @Override public void setOnItemClickListener( AdapterView.OnItemClickListener listener ) { mOnItemClicked = listener; } /** The m data observer. */ private DataSetObserver mDataObserver = new DataSetObserver() { @Override public void onChanged() { synchronized ( HorizontalListView.this ) { mDataChanged = true; } invalidate(); requestLayout(); } @Override public void onInvalidated() { reset(); invalidate(); requestLayout(); } }; /** The m height measure spec. */ private int mHeightMeasureSpec; /** The m width measure spec. */ private int mWidthMeasureSpec; /* * (non-Javadoc) * * @see android.widget.AdapterView#getAdapter() */ @Override public ListAdapter getAdapter() { return mAdapter; } /* * (non-Javadoc) * * @see android.widget.AdapterView#getSelectedView() */ @Override public View getSelectedView() { // TODO: implement return null; } /* * (non-Javadoc) * * @see android.widget.AdapterView#setAdapter(android.widget.Adapter) */ @Override public void setAdapter( ListAdapter adapter ) { if ( mAdapter != null ) { mAdapter.unregisterDataSetObserver( mDataObserver ); } mAdapter = adapter; if ( null != mAdapter ) { mAdapter.registerDataSetObserver( mDataObserver ); } reset(); } /** * Reset. */ private synchronized void reset() { initView(); removeAllViewsInLayout(); requestLayout(); } /* * (non-Javadoc) * * @see android.widget.AdapterView#setSelection(int) */ @Override public void setSelection( int position ) { // TODO: implement } /* * (non-Javadoc) * * @see android.view.View#onMeasure(int, int) */ @Override protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec ) { Log.d( VIEW_LOG_TAG, "onMeasure" ); super.onMeasure( widthMeasureSpec, heightMeasureSpec ); mHeightMeasureSpec = heightMeasureSpec; mWidthMeasureSpec = widthMeasureSpec; } /** * Adds the and measure child. * * @param child * the child * @param viewPos * the view pos */ private void addAndMeasureChild( final View child, int viewPos ) { LayoutParams params = child.getLayoutParams(); if ( params == null ) { params = new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT ); } addViewInLayout( child, viewPos, params ); forceChildLayout( child, params ); } public void forceChildLayout( final View child, final LayoutParams params ) { int childHeightSpec = ViewGroup.getChildMeasureSpec( mHeightMeasureSpec, getPaddingTop() + getPaddingBottom(), params.height ); int childWidthSpec = ViewGroup.getChildMeasureSpec( mWidthMeasureSpec, getPaddingLeft() + getPaddingRight(), params.width ); child.measure( childWidthSpec, childHeightSpec ); } /** * Gets the real height. * * @return the real height */ @SuppressWarnings("unused") private int getRealHeight() { return getHeight() - ( getPaddingTop() + getPaddingBottom() ); } /** * Gets the real width. * * @return the real width */ @SuppressWarnings("unused") private int getRealWidth() { return getWidth() - ( getPaddingLeft() + getPaddingRight() ); } public void requestFullLayout() { mDataChanged = true; invalidate(); requestLayout(); } /* * (non-Javadoc) * * @see android.widget.AdapterView#onLayout(boolean, int, int, int, int) */ @Override protected synchronized void onLayout( boolean changed, int left, int top, int right, int bottom ) { super.onLayout( changed, left, top, right, bottom ); Log.d( VIEW_LOG_TAG, "onLayout: " + changed ); if ( mAdapter == null ) { return; } if ( mDataChanged ) { int oldCurrentX = mCurrentX; initView(); removeAllViewsInLayout(); mNextX = oldCurrentX; mDataChanged = false; } if ( mScroller.computeScrollOffset() ) { int scrollx = mScroller.getCurrX(); mNextX = scrollx; } if ( mNextX < 0 ) { mNextX = 0; mScroller.forceFinished( true ); } if ( mNextX > mMaxX ) { mNextX = mMaxX; mScroller.forceFinished( true ); } int dx = mCurrentX - mNextX; removeNonVisibleItems( dx ); fillList( dx ); positionItems( dx ); mCurrentX = mNextX; if ( !mScroller.isFinished() ) { post( mRequestLayoutRunnable ); } } private Runnable mRequestLayoutRunnable = new Runnable() { @Override public void run() { requestLayout(); } }; /** * Fill list. * * @param dx * the dx */ private void fillList( final int dx ) { int edge = 0; View child = getChildAt( getChildCount() - 1 ); if ( child != null ) { edge = child.getRight(); } fillListRight( edge, dx ); edge = 0; child = getChildAt( 0 ); if ( child != null ) { edge = child.getLeft(); } fillListLeft( edge, dx ); } /** * Fill list right. * * @param rightEdge * the right edge * @param dx * the dx */ private void fillListRight( int rightEdge, final int dx ) { while ( rightEdge + dx < getWidth() && mRightViewIndex < mAdapter.getCount() ) { View child = mAdapter.getView( mRightViewIndex, mRemovedViewQueue.poll(), this ); addAndMeasureChild( child, -1 ); rightEdge += child.getMeasuredWidth(); if ( mRightViewIndex == mAdapter.getCount() - 1 ) { mMaxX = mCurrentX + rightEdge - getWidth(); } mRightViewIndex++; } } /** * Fill list left. * * @param leftEdge * the left edge * @param dx * the dx */ private void fillListLeft( int leftEdge, final int dx ) { while ( leftEdge + dx > 0 && mLeftViewIndex >= 0 ) { View child = mAdapter.getView( mLeftViewIndex, mRemovedViewQueue.poll(), this ); addAndMeasureChild( child, 0 ); leftEdge -= child.getMeasuredWidth(); mLeftViewIndex--; mDisplayOffset -= child.getMeasuredWidth(); } } /** * Removes the non visible items. * * @param dx * the dx */ private void removeNonVisibleItems( final int dx ) { View child = getChildAt( 0 ); while ( child != null && child.getRight() + dx <= 0 ) { mDisplayOffset += child.getMeasuredWidth(); mRemovedViewQueue.offer( child ); removeViewInLayout( child ); mLeftViewIndex++; child = getChildAt( 0 ); } child = getChildAt( getChildCount() - 1 ); while ( child != null && child.getLeft() + dx >= getWidth() ) { mRemovedViewQueue.offer( child ); removeViewInLayout( child ); mRightViewIndex--; child = getChildAt( getChildCount() - 1 ); } } /** * Position items. * * @param dx * the dx */ private void positionItems( final int dx ) { if ( getChildCount() > 0 ) { mDisplayOffset += dx; int left = mDisplayOffset; for ( int i = 0; i < getChildCount(); i++ ) { View child = getChildAt( i ); int childWidth = child.getMeasuredWidth(); int childTop = getPaddingTop(); child.layout( left, childTop, left + childWidth, childTop + child.getMeasuredHeight() ); left += childWidth; } } } /** * Scroll to. * * @param x * the x */ public synchronized void scrollTo( int x ) { mScroller.startScroll( mNextX, 0, x - mNextX, 0 ); requestLayout(); } /* * (non-Javadoc) * * @see android.view.ViewGroup#dispatchTouchEvent(android.view.MotionEvent) */ @Override public boolean dispatchTouchEvent( MotionEvent ev ) { boolean handled = mGesture.onTouchEvent( ev ); return handled; } /** * On fling. * * @param e1 * the e1 * @param e2 * the e2 * @param velocityX * the velocity x * @param velocityY * the velocity y * @return true, if successful */ protected boolean onFling( MotionEvent e1, MotionEvent e2, float velocityX, float velocityY ) { synchronized ( HorizontalListView.this ) { Log.i( LoggerFactory.LOG_TAG, "onFling: " + -velocityX + ", " + mMaxX ); mScroller.fling( mNextX, 0, (int) -( velocityX / 2 ), 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0 ); } requestLayout(); return true; } /** The m scroller running. */ boolean mScrollerRunning; /** * On down. * * @param e * the e * @return true, if successful */ protected boolean onDown( MotionEvent e ) { if ( !mScroller.isFinished() ) { mScrollerRunning = true; } else { mScrollerRunning = false; } mScroller.forceFinished( true ); return true; } /** The m on gesture. */ private OnGestureListener mOnGesture = new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDown( MotionEvent e ) { return HorizontalListView.this.onDown( e ); } @Override public boolean onFling( MotionEvent e1, MotionEvent e2, float velocityX, float velocityY ) { return HorizontalListView.this.onFling( e1, e2, velocityX, velocityY ); } @Override public boolean onScroll( MotionEvent e1, MotionEvent e2, float distanceX, float distanceY ) { synchronized ( HorizontalListView.this ) { mNextX += (int) distanceX; } requestLayout(); return true; } @Override public boolean onSingleTapConfirmed( MotionEvent e ) { Log.i( LoggerFactory.LOG_TAG, "onSingleTapConfirmed" ); if ( mScrollerRunning ) return false; Rect viewRect = new Rect(); for ( int i = 0; i < getChildCount(); i++ ) { View child = getChildAt( i ); int left = child.getLeft(); int right = child.getRight(); int top = child.getTop(); int bottom = child.getBottom(); viewRect.set( left, top, right, bottom ); if ( viewRect.contains( (int) e.getX(), (int) e.getY() ) ) { if ( mOnItemClicked != null ) { mOnItemClicked.onItemClick( HorizontalListView.this, child, mLeftViewIndex + 1 + i, mAdapter.getItemId( mLeftViewIndex + 1 + i ) ); } if ( mOnItemSelected != null ) { mOnItemSelected.onItemSelected( HorizontalListView.this, child, mLeftViewIndex + 1 + i, mAdapter.getItemId( mLeftViewIndex + 1 + i ) ); } break; } } return true; } }; }
Java
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aviary.android.feather.widget; import android.R; import android.content.Context; import android.graphics.Rect; import android.os.Handler; import android.os.Message; import android.os.Vibrator; import android.util.AttributeSet; import android.util.Log; import android.view.ContextMenu.ContextMenuInfo; import android.view.GestureDetector; import android.view.Gravity; import android.view.HapticFeedbackConstants; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SoundEffectConstants; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.animation.Transformation; import com.aviary.android.feather.library.utils.ReflectionUtils; import com.aviary.android.feather.library.utils.ReflectionUtils.ReflectionException; import com.aviary.android.feather.widget.IFlingRunnable.FlingRunnableView; // TODO: Auto-generated Javadoc /** * A view that shows items in a center-locked, horizontally scrolling list. * <p> * The default values for the Gallery assume you will be using {@link android.R.styleable#Theme_galleryItemBackground} as the * background for each View given to the Gallery from the Adapter. If you are not doing this, you may need to adjust some Gallery * properties, such as the spacing. * <p> * Views given to the Gallery should use {@link Gallery.LayoutParams} as their layout parameters type. * * <p> * See the <a href="{@docRoot}resources/tutorials/views/hello-gallery.html">Gallery tutorial</a>. * </p> * * @attr ref android.R.styleable#Gallery_animationDuration * @attr ref android.R.styleable#Gallery_spacing * @attr ref android.R.styleable#Gallery_gravity */ public class Gallery extends AbsSpinner implements GestureDetector.OnGestureListener, FlingRunnableView, VibrationWidget { /** * The listener interface for receiving onItemsScroll events. The class that is interested in processing a onItemsScroll event * implements this interface, and the object created with that class is registered with a component using the component's * <code>addOnItemsScrollListener<code> method. When * the onItemsScroll event occurs, that object's appropriate * method is invoked. * * @see OnItemsScrollEvent */ public interface OnItemsScrollListener { /** * On scroll started. * * @param parent * the parent * @param view * the view * @param position * the position * @param id * the id */ void onScrollStarted( AdapterView<?> parent, View view, int position, long id ); /** * On scroll. * * @param parent * the parent * @param view * the view * @param position * the position * @param id * the id */ void onScroll( AdapterView<?> parent, View view, int position, long id ); /** * On scroll finished. * * @param parent * the parent * @param view * the view * @param position * the position * @param id * the id */ void onScrollFinished( AdapterView<?> parent, View view, int position, long id ); } /** The Constant TAG. */ private static final String TAG = "gallery"; /** The Constant MSG_VIBRATE. */ private static final int MSG_VIBRATE = 1; /** Vibration. */ Vibrator mVibrator; /** The m vibration handler. */ static Handler mVibrationHandler; /** set child selected automatically. */ private boolean mAutoSelectChild = false; /** The m items scroll listener. */ private OnItemsScrollListener mItemsScrollListener = null; /** * Duration in milliseconds from the start of a scroll during which we're unsure whether the user is scrolling or flinging. */ private static final int SCROLL_TO_FLING_UNCERTAINTY_TIMEOUT = 250; /** * Horizontal spacing between items. */ private int mSpacing = 0; /** * How long the transition animation should run when a child view changes position, measured in milliseconds. */ private int mAnimationDuration = 400; /** * The alpha of items that are not selected. */ private float mUnselectedAlpha; /** * Left most edge of a child seen so far during layout. */ private int mLeftMost; /** * Right most edge of a child seen so far during layout. */ private int mRightMost; /** The m gravity. */ private int mGravity; /** * Helper for detecting touch gestures. */ private GestureDetector mGestureDetector; /** * The position of the item that received the user's down touch. */ private int mDownTouchPosition; /** * The view of the item that received the user's down touch. */ private View mDownTouchView; /** * Executes the delta scrolls from a fling or scroll movement. */ private IFlingRunnable mFlingRunnable; /** The m auto scroll to center. */ private boolean mAutoScrollToCenter = true; /** The m touch slop. */ int mTouchSlop; /** * Sets mSuppressSelectionChanged = false. This is used to set it to false in the future. It will also trigger a selection * changed. */ private Runnable mDisableSuppressSelectionChangedRunnable = new Runnable() { @Override public void run() { mSuppressSelectionChanged = false; selectionChanged(); } }; /** * When fling runnable runs, it resets this to false. Any method along the path until the end of its run() can set this to true * to abort any remaining fling. For example, if we've reached either the leftmost or rightmost item, we will set this to true. */ @SuppressWarnings("unused") private boolean mShouldStopFling; /** * The currently selected item's child. */ private View mSelectedChild; /** * Whether to continuously callback on the item selected listener during a fling. */ private boolean mShouldCallbackDuringFling = false; /** * Whether to callback when an item that is not selected is clicked. */ private boolean mShouldCallbackOnUnselectedItemClick = true; /** * If true, do not callback to item selected listener. */ private boolean mSuppressSelectionChanged = true; /** * If true, we have received the "invoke" (center or enter buttons) key down. This is checked before we action on the "invoke" * key up, and is subsequently cleared. */ private boolean mReceivedInvokeKeyDown; /** The m context menu info. */ private AdapterContextMenuInfo mContextMenuInfo; /** * If true, this onScroll is the first for this user's drag (remember, a drag sends many onScrolls). */ private boolean mIsFirstScroll; /** * If true, mFirstPosition is the position of the rightmost child, and the children are ordered right to left. */ private boolean mIsRtl = true; /** The m last motion value. */ private int mLastMotionValue; /** * Instantiates a new gallery. * * @param context * the context */ public Gallery( Context context ) { this( context, null ); } /** * Instantiates a new gallery. * * @param context * the context * @param attrs * the attrs */ public Gallery( Context context, AttributeSet attrs ) { this( context, attrs, R.attr.galleryStyle ); } /** * Instantiates a new gallery. * * @param context * the context * @param attrs * the attrs * @param defStyle * the def style */ public Gallery( Context context, AttributeSet attrs, int defStyle ) { super( context, attrs, defStyle ); mGestureDetector = new GestureDetector( context, this ); mGestureDetector.setIsLongpressEnabled( false ); ViewConfiguration configuration = ViewConfiguration.get( context ); mTouchSlop = configuration.getScaledTouchSlop(); if ( android.os.Build.VERSION.SDK_INT > 8 ) { try { mFlingRunnable = (IFlingRunnable) ReflectionUtils.newInstance( "com.aviary.android.feather.widget.Fling9Runnable", new Class<?>[] { FlingRunnableView.class, int.class }, this, mAnimationDuration ); } catch ( ReflectionException e ) { mFlingRunnable = new Fling8Runnable( this, mAnimationDuration ); } } else { mFlingRunnable = new Fling8Runnable( this, mAnimationDuration ); } Log.d( VIEW_LOG_TAG, "fling class: " + mFlingRunnable.getClass().getName() ); try { mVibrator = (Vibrator) context.getSystemService( Context.VIBRATOR_SERVICE ); } catch ( Exception e ) { Log.e( TAG, e.toString() ); } if ( mVibrator != null ) { setVibrationEnabled( true ); } } @Override public synchronized void setVibrationEnabled( boolean value ) { if ( !value ) { mVibrationHandler = null; } else { if ( null == mVibrationHandler ) { mVibrationHandler = new Handler() { @Override public void handleMessage( Message msg ) { super.handleMessage( msg ); switch ( msg.what ) { case MSG_VIBRATE: try { mVibrator.vibrate( 10 ); } catch ( SecurityException e ) { // missing VIBRATE permission } } } }; } } } @Override public synchronized boolean getVibrationEnabled() { return mVibrationHandler != null; } /** * Sets the on items scroll listener. * * @param value * the new on items scroll listener */ public void setOnItemsScrollListener( OnItemsScrollListener value ) { mItemsScrollListener = value; } /** * Sets the auto scroll to center. * * @param value * the new auto scroll to center */ public void setAutoScrollToCenter( boolean value ) { mAutoScrollToCenter = value; } /** * Whether or not to callback on any {@link #getOnItemSelectedListener()} while the items are being flinged. If false, only the * final selected item will cause the callback. If true, all items between the first and the final will cause callbacks. * * @param shouldCallback * Whether or not to callback on the listener while the items are being flinged. */ public void setCallbackDuringFling( boolean shouldCallback ) { mShouldCallbackDuringFling = shouldCallback; } /* * (non-Javadoc) * * @see com.aviary.android.feather.widget.AdapterView#onDetachedFromWindow() */ @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); removeCallbacks( mScrollSelectionNotifier ); } /** * Whether or not to callback when an item that is not selected is clicked. If false, the item will become selected (and * re-centered). If true, the {@link #getOnItemClickListener()} will get the callback. * * @param shouldCallback * Whether or not to callback on the listener when a item that is not selected is clicked. * @hide */ public void setCallbackOnUnselectedItemClick( boolean shouldCallback ) { mShouldCallbackOnUnselectedItemClick = shouldCallback; } /** * Sets how long the transition animation should run when a child view changes position. Only relevant if animation is turned on. * * @param animationDurationMillis * The duration of the transition, in milliseconds. * * @attr ref android.R.styleable#Gallery_animationDuration */ public void setAnimationDuration( int animationDurationMillis ) { mAnimationDuration = animationDurationMillis; } /** * Sets the spacing between items in a Gallery. * * @param spacing * The spacing in pixels between items in the Gallery * @attr ref android.R.styleable#Gallery_spacing */ public void setSpacing( int spacing ) { mSpacing = spacing; } /** * Sets the alpha of items that are not selected in the Gallery. * * @param unselectedAlpha * the alpha for the items that are not selected. * * @attr ref android.R.styleable#Gallery_unselectedAlpha */ public void setUnselectedAlpha( float unselectedAlpha ) { mUnselectedAlpha = unselectedAlpha; } /* * (non-Javadoc) * * @see android.view.ViewGroup#getChildStaticTransformation(android.view.View, android.view.animation.Transformation) */ @Override protected boolean getChildStaticTransformation( View child, Transformation t ) { t.clear(); t.setAlpha( child == mSelectedChild ? 1.0f : mUnselectedAlpha ); return true; } /* * (non-Javadoc) * * @see android.view.View#computeHorizontalScrollExtent() */ @Override protected int computeHorizontalScrollExtent() { // Only 1 item is considered to be selected return 1; } /* * (non-Javadoc) * * @see android.view.View#computeHorizontalScrollOffset() */ @Override protected int computeHorizontalScrollOffset() { return mSelectedPosition; } /* * (non-Javadoc) * * @see android.view.View#computeHorizontalScrollRange() */ @Override protected int computeHorizontalScrollRange() { // Scroll range is the same as the item count return mItemCount; } /* * (non-Javadoc) * * @see android.view.ViewGroup#checkLayoutParams(android.view.ViewGroup.LayoutParams) */ @Override protected boolean checkLayoutParams( ViewGroup.LayoutParams p ) { return p instanceof LayoutParams; } /* * (non-Javadoc) * * @see android.view.ViewGroup#generateLayoutParams(android.view.ViewGroup.LayoutParams) */ @Override protected ViewGroup.LayoutParams generateLayoutParams( ViewGroup.LayoutParams p ) { return new LayoutParams( p ); } /* * (non-Javadoc) * * @see android.view.ViewGroup#generateLayoutParams(android.util.AttributeSet) */ @Override public ViewGroup.LayoutParams generateLayoutParams( AttributeSet attrs ) { return new LayoutParams( getContext(), attrs ); } /* * (non-Javadoc) * * @see com.aviary.android.feather.widget.AbsSpinner#generateDefaultLayoutParams() */ @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { /* * Gallery expects Gallery.LayoutParams. */ return new Gallery.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ); } /* * (non-Javadoc) * * @see com.aviary.android.feather.widget.AdapterView#onLayout(boolean, int, int, int, int) */ @Override protected void onLayout( boolean changed, int l, int t, int r, int b ) { super.onLayout( changed, l, t, r, b ); /* * Remember that we are in layout to prevent more layout request from being generated. */ mInLayout = true; layout( 0, false, changed ); mInLayout = false; } /* * (non-Javadoc) * * @see com.aviary.android.feather.widget.AbsSpinner#getChildHeight(android.view.View) */ @Override int getChildHeight( View child ) { return child.getMeasuredHeight(); } /** * Tracks a motion scroll. In reality, this is used to do just about any movement to items (touch scroll, arrow-key scroll, set * an item as selected). * * @param deltaX * Change in X from the previous event. */ @Override public void trackMotionScroll( int delta ) { int deltaX = mFlingRunnable.getLastFlingX() - delta; // Pretend that each frame of a fling scroll is a touch scroll if ( delta > 0 ) { mDownTouchPosition = mIsRtl ? ( mFirstPosition + getChildCount() - 1 ) : mFirstPosition; // Don't fling more than 1 screen delta = Math.min( getWidth() - mPaddingLeft - mPaddingRight - 1, delta ); } else { mDownTouchPosition = mIsRtl ? mFirstPosition : ( mFirstPosition + getChildCount() - 1 ); // Don't fling more than 1 screen delta = Math.max( -( getWidth() - mPaddingRight - mPaddingLeft - 1 ), delta ); } if ( getChildCount() == 0 ) { return; } boolean toLeft = deltaX < 0; int limitedDeltaX = deltaX; // getLimitedMotionScrollAmount(toLeft, deltaX); int realDeltaX = getLimitedMotionScrollAmount( toLeft, deltaX ); if ( realDeltaX != deltaX ) { // mFlingRunnable.springBack( realDeltaX ); limitedDeltaX = realDeltaX; } if ( limitedDeltaX != deltaX ) { mFlingRunnable.endFling( false ); if ( limitedDeltaX == 0 ) onFinishedMovement(); } offsetChildrenLeftAndRight( limitedDeltaX ); detachOffScreenChildren( toLeft ); if ( toLeft ) { // If moved left, there will be empty space on the right fillToGalleryRight(); } else { // Similarly, empty space on the left fillToGalleryLeft(); } // Clear unused views // mRecycler.clear(); // mRecyclerInvalidItems.clear(); setSelectionToCenterChild(); onScrollChanged( 0, 0, 0, 0 ); // dummy values, View's implementation does not use these. invalidate(); } /** * Gets the limited motion scroll amount. * * @param motionToLeft * the motion to left * @param deltaX * the delta x * @return the limited motion scroll amount */ int getLimitedMotionScrollAmount( boolean motionToLeft, int deltaX ) { int extremeItemPosition = motionToLeft != mIsRtl ? mItemCount - 1 : 0; View extremeChild = getChildAt( extremeItemPosition - mFirstPosition ); if ( extremeChild == null ) { return deltaX; } int extremeChildCenter = getCenterOfView( extremeChild ) + ( motionToLeft ? extremeChild.getWidth() / 2 : -extremeChild.getWidth() / 2 ); int galleryCenter = getCenterOfGallery(); if ( motionToLeft ) { if ( extremeChildCenter <= galleryCenter ) { // The extreme child is past his boundary point! return 0; } } else { if ( extremeChildCenter >= galleryCenter ) { // The extreme child is past his boundary point! return 0; } } int centerDifference = galleryCenter - extremeChildCenter; return motionToLeft ? Math.max( centerDifference, deltaX ) : Math.min( centerDifference, deltaX ); } /** * Gets the limited motion scroll amount2. * * @param motionToLeft * the motion to left * @param deltaX * the delta x * @return the limited motion scroll amount2 */ int getLimitedMotionScrollAmount2( boolean motionToLeft, int deltaX ) { int extremeItemPosition = motionToLeft != mIsRtl ? mItemCount - 1 : 0; View extremeChild = getChildAt( extremeItemPosition - mFirstPosition ); if ( extremeChild == null ) { return deltaX; } int extremeChildCenter = getCenterOfView( extremeChild ) + ( motionToLeft ? extremeChild.getWidth() / 2 : -extremeChild.getWidth() / 2 ); int galleryCenter = getCenterOfGallery(); int centerDifference = galleryCenter - extremeChildCenter; return motionToLeft ? Math.max( centerDifference, deltaX ) : Math.min( centerDifference, deltaX ); } /** * Gets the over scroll delta. * * @param motionToLeft * the motion to left * @param deltaX * the delta x * @return the over scroll delta */ int getOverScrollDelta( boolean motionToLeft, int deltaX ) { int extremeItemPosition = motionToLeft != mIsRtl ? mItemCount - 1 : 0; View extremeChild = getChildAt( extremeItemPosition - mFirstPosition ); if ( extremeChild == null ) { return 0; } int extremeChildCenter = getCenterOfView( extremeChild ); int galleryCenter = getCenterOfGallery(); if ( motionToLeft ) { if ( extremeChildCenter < galleryCenter ) { return extremeChildCenter - galleryCenter; } } else { if ( extremeChildCenter > galleryCenter ) { return galleryCenter - extremeChildCenter; } } return 0; } protected void onOverScrolled( int scrollX, int scrollY, boolean clampedX, boolean clampedY ) {} /** * Offset the horizontal location of all children of this view by the specified number of pixels. * * @param offset * the number of pixels to offset */ private void offsetChildrenLeftAndRight( int offset ) { for ( int i = getChildCount() - 1; i >= 0; i-- ) { getChildAt( i ).offsetLeftAndRight( offset ); } } /** * Gets the center of gallery. * * @return The center of this Gallery. */ private int getCenterOfGallery() { return ( getWidth() - mPaddingLeft - mPaddingRight ) / 2 + mPaddingLeft; } /** * Gets the center of view. * * @param view * the view * @return The center of the given view. */ private static int getCenterOfView( View view ) { return view.getLeft() + view.getWidth() / 2; } /** * Detaches children that are off the screen (i.e.: Gallery bounds). * * @param toLeft * Whether to detach children to the left of the Gallery, or to the right. */ private void detachOffScreenChildren( boolean toLeft ) { int numChildren = getChildCount(); int firstPosition = mFirstPosition; int start = 0; int count = 0; if ( toLeft ) { final int galleryLeft = mPaddingLeft; for ( int i = 0; i < numChildren; i++ ) { int n = mIsRtl ? ( numChildren - 1 - i ) : i; final View child = getChildAt( n ); if ( child.getRight() >= galleryLeft ) { break; } else { start = n; count++; int viewType = mAdapter.getItemViewType( firstPosition + n ); mRecycleBin.get( viewType ).add( child ); //if ( firstPosition + n < 0 ) { // mRecyclerInvalidItems.put( firstPosition + n, child ); //} else { // mRecycler.put( firstPosition + n, child ); //} } } if ( !mIsRtl ) { start = 0; } } else { final int galleryRight = getWidth() - mPaddingRight; for ( int i = numChildren - 1; i >= 0; i-- ) { int n = mIsRtl ? numChildren - 1 - i : i; final View child = getChildAt( n ); if ( child.getLeft() <= galleryRight ) { break; } else { start = n; count++; int viewType = mAdapter.getItemViewType( firstPosition + n ); mRecycleBin.get( viewType ).add( child ); //if ( firstPosition + n >= mItemCount ) { // mRecyclerInvalidItems.put( firstPosition + n, child ); //} else { // mRecycler.put( firstPosition + n, child ); //} } } if ( mIsRtl ) { start = 0; } } detachViewsFromParent( start, count ); if ( toLeft != mIsRtl ) { mFirstPosition += count; } } /** * Scrolls the items so that the selected item is in its 'slot' (its center is the gallery's center). */ @Override public void scrollIntoSlots() { if ( getChildCount() == 0 || mSelectedChild == null ) return; if ( mAutoScrollToCenter ) { int selectedCenter = getCenterOfView( mSelectedChild ); int targetCenter = getCenterOfGallery(); int scrollAmount = targetCenter - selectedCenter; if ( scrollAmount != 0 ) { mFlingRunnable.startUsingDistance( 0, -scrollAmount ); // fireVibration(); } else { onFinishedMovement(); } } else { onFinishedMovement(); } } /** * Scrolls the items so that the selected item is in its 'slot' (its center is the gallery's center). * * @return true, if is over scrolled */ private boolean isOverScrolled() { if ( getChildCount() < 2 || mSelectedChild == null ) return false; if ( mSelectedPosition == 0 || mSelectedPosition == mItemCount - 1 ) { int selectedCenter0 = getCenterOfView( mSelectedChild ); int targetCenter = getCenterOfGallery(); if ( mSelectedPosition == 0 && selectedCenter0 > targetCenter ) return true; if ( ( mSelectedPosition == mItemCount - 1 ) && selectedCenter0 < targetCenter ) return true; } return false; } /** * On finished movement. */ private void onFinishedMovement() { if ( isDown ) return; if ( mSuppressSelectionChanged ) { mSuppressSelectionChanged = false; // We haven't been callbacking during the fling, so do it now super.selectionChanged(); } scrollCompleted(); invalidate(); } /* * (non-Javadoc) * * @see com.aviary.android.feather.widget.AdapterView#selectionChanged() */ @Override void selectionChanged() { if ( !mSuppressSelectionChanged ) { super.selectionChanged(); } } /** * Looks for the child that is closest to the center and sets it as the selected child. */ private void setSelectionToCenterChild() { View selView = mSelectedChild; if ( mSelectedChild == null ) return; int galleryCenter = getCenterOfGallery(); // Common case where the current selected position is correct if ( selView.getLeft() <= galleryCenter && selView.getRight() >= galleryCenter ) { return; } // TODO better search int closestEdgeDistance = Integer.MAX_VALUE; int newSelectedChildIndex = 0; for ( int i = getChildCount() - 1; i >= 0; i-- ) { View child = getChildAt( i ); if ( child.getLeft() <= galleryCenter && child.getRight() >= galleryCenter ) { // This child is in the center newSelectedChildIndex = i; break; } int childClosestEdgeDistance = Math.min( Math.abs( child.getLeft() - galleryCenter ), Math.abs( child.getRight() - galleryCenter ) ); if ( childClosestEdgeDistance < closestEdgeDistance ) { closestEdgeDistance = childClosestEdgeDistance; newSelectedChildIndex = i; } } int newPos = mFirstPosition + newSelectedChildIndex; if ( newPos != mSelectedPosition ) { newPos = Math.min( Math.max( newPos, 0 ), mItemCount - 1 ); setSelectedPositionInt( newPos, true ); setNextSelectedPositionInt( newPos ); checkSelectionChanged(); } } /** * Creates and positions all views for this Gallery. * <p> * We layout rarely, most of the time {@link #trackMotionScroll(int)} takes care of repositioning, adding, and removing children. * * @param delta * Change in the selected position. +1 means the selection is moving to the right, so views are scrolling to the left. * -1 means the selection is moving to the left. * @param animate * the animate */ @Override void layout( int delta, boolean animate, boolean changed ) { mIsRtl = false; int childrenLeft = mSpinnerPadding.left; int childrenWidth = getRight() - getLeft() - mSpinnerPadding.left - mSpinnerPadding.right; if ( mDataChanged ) { handleDataChanged(); } // Handle an empty gallery by removing all views. if ( mItemCount == 0 ) { resetList(); return; } // Update to the new selected position. if ( mNextSelectedPosition >= 0 ) { setSelectedPositionInt( mNextSelectedPosition, animate ); } // All views go in recycler while we are in layout recycleAllViews(); // Clear out old views // removeAllViewsInLayout(); detachAllViewsFromParent(); /* * These will be used to give initial positions to views entering the gallery as we scroll */ mRightMost = 0; mLeftMost = 0; // Make selected view and center it /* * mFirstPosition will be decreased as we add views to the left later on. The 0 for x will be offset in a couple lines down. */ mFirstPosition = mSelectedPosition; View sel = makeAndAddView( mSelectedPosition, 0, 0, true ); // Put the selected child in the center int selectedOffset = childrenLeft + ( childrenWidth / 2 ) - ( sel.getWidth() / 2 ); sel.offsetLeftAndRight( selectedOffset ); fillToGalleryRight(); fillToGalleryLeft(); // Flush any cached views that did not get reused above //mRecycler.clear(); //mRecyclerInvalidItems.clear(); emptySubRecycler(); invalidate(); checkSelectionChanged(); mDataChanged = false; mNeedSync = false; setNextSelectedPositionInt( mSelectedPosition ); updateSelectedItemMetadata( animate, changed ); } /** * Fill to gallery left. */ private void fillToGalleryLeft() { if ( mIsRtl ) { fillToGalleryLeftRtl(); } else { fillToGalleryLeftLtr(); } } /** * Fill to gallery left rtl. */ private void fillToGalleryLeftRtl() { int itemSpacing = mSpacing; int galleryLeft = mPaddingLeft; int numChildren = getChildCount(); // Set state for initial iteration View prevIterationView = getChildAt( numChildren - 1 ); int curPosition; int curRightEdge; if ( prevIterationView != null ) { curPosition = mFirstPosition + numChildren; curRightEdge = prevIterationView.getLeft() - itemSpacing; } else { // No children available! mFirstPosition = curPosition = mItemCount - 1; curRightEdge = getRight() - getLeft() - mPaddingRight; mShouldStopFling = true; } while ( curRightEdge > galleryLeft && curPosition < mItemCount ) { prevIterationView = makeAndAddView( curPosition, curPosition - mSelectedPosition, curRightEdge, false ); // Set state for next iteration curRightEdge = prevIterationView.getLeft() - itemSpacing; curPosition++; } } /** * Fill to gallery left ltr. */ private void fillToGalleryLeftLtr() { int itemSpacing = mSpacing; int galleryLeft = mPaddingLeft; // Set state for initial iteration View prevIterationView = getChildAt( 0 ); int curPosition; int curRightEdge; if ( prevIterationView != null ) { curPosition = mFirstPosition - 1; curRightEdge = prevIterationView.getLeft() - itemSpacing; } else { // No children available! curPosition = 0; curRightEdge = getRight() - getLeft() - mPaddingRight; mShouldStopFling = true; } while ( curRightEdge > galleryLeft /* && curPosition >= 0 */) { prevIterationView = makeAndAddView( curPosition, curPosition - mSelectedPosition, curRightEdge, false ); // Remember some state mFirstPosition = curPosition; // Set state for next iteration curRightEdge = prevIterationView.getLeft() - itemSpacing; curPosition--; } } /** * Fill to gallery right. */ private void fillToGalleryRight() { if ( mIsRtl ) { fillToGalleryRightRtl(); } else { fillToGalleryRightLtr(); } } /** * Fill to gallery right rtl. */ private void fillToGalleryRightRtl() { int itemSpacing = mSpacing; int galleryRight = getRight() - getLeft() - mPaddingRight; // Set state for initial iteration View prevIterationView = getChildAt( 0 ); int curPosition; int curLeftEdge; if ( prevIterationView != null ) { curPosition = mFirstPosition - 1; curLeftEdge = prevIterationView.getRight() + itemSpacing; } else { curPosition = 0; curLeftEdge = mPaddingLeft; mShouldStopFling = true; } while ( curLeftEdge < galleryRight && curPosition >= 0 ) { prevIterationView = makeAndAddView( curPosition, curPosition - mSelectedPosition, curLeftEdge, true ); // Remember some state mFirstPosition = curPosition; // Set state for next iteration curLeftEdge = prevIterationView.getRight() + itemSpacing; curPosition--; } } /** * Fill to gallery right ltr. */ private void fillToGalleryRightLtr() { int itemSpacing = mSpacing; int galleryRight = getRight() - getLeft() - mPaddingRight; int numChildren = getChildCount(); // Set state for initial iteration View prevIterationView = getChildAt( numChildren - 1 ); int curPosition; int curLeftEdge; if ( prevIterationView != null ) { curPosition = mFirstPosition + numChildren; curLeftEdge = prevIterationView.getRight() + itemSpacing; } else { mFirstPosition = curPosition = mItemCount - 1; curLeftEdge = mPaddingLeft; mShouldStopFling = true; } while ( curLeftEdge < galleryRight /* && curPosition < numItems */) { prevIterationView = makeAndAddView( curPosition, curPosition - mSelectedPosition, curLeftEdge, true ); // Set state for next iteration curLeftEdge = prevIterationView.getRight() + itemSpacing; curPosition++; } } /** * Obtain a view, either by pulling an existing view from the recycler or by getting a new one from the adapter. If we are * animating, make sure there is enough information in the view's layout parameters to animate from the old to new positions. * * @param position * Position in the gallery for the view to obtain * @param offset * Offset from the selected position * @param x * X-coordinate indicating where this view should be placed. This will either be the left or right edge of the view, * depending on the fromLeft parameter * @param fromLeft * Are we positioning views based on the left edge? (i.e., building from left to right)? * @return A view that has been added to the gallery */ private View makeAndAddView( int position, int offset, int x, boolean fromLeft ) { View child; int viewType = mAdapter.getItemViewType( position ); if ( !mDataChanged ) { child = mRecycleBin.get( viewType ).poll(); /* if ( valid ) { child = mRecycler.get( position ); } else { child = mRecyclerInvalidItems.get( position ); } */ if ( child != null ) { // Can reuse an existing view child = mAdapter.getView( position, child, this ); int childLeft = child.getLeft(); // Remember left and right edges of where views have been placed mRightMost = Math.max( mRightMost, childLeft + child.getMeasuredWidth() ); mLeftMost = Math.min( mLeftMost, childLeft ); // Position the view setUpChild( child, offset, x, fromLeft ); return child; } } // Nothing found in the recycler -- ask the adapter for a view child = mAdapter.getView( position, null, this ); // Position the view setUpChild( child, offset, x, fromLeft ); return child; } public void invalidateViews() { int count = getChildCount(); for ( int i = 0; i < count; i++ ) { View child = getChildAt( i ); mAdapter.getView( mFirstPosition + i, child, this ); } } /** * Helper for makeAndAddView to set the position of a view and fill out its layout parameters. * * @param child * The view to position * @param offset * Offset from the selected position * @param x * X-coordinate indicating where this view should be placed. This will either be the left or right edge of the view, * depending on the fromLeft parameter * @param fromLeft * Are we positioning views based on the left edge? (i.e., building from left to right)? */ private void setUpChild( View child, int offset, int x, boolean fromLeft ) { // Respect layout params that are already in the view. Otherwise // make some up... Gallery.LayoutParams lp = (Gallery.LayoutParams) child.getLayoutParams(); if ( lp == null ) { lp = (Gallery.LayoutParams) generateDefaultLayoutParams(); } addViewInLayout( child, fromLeft != mIsRtl ? -1 : 0, lp ); if ( mAutoSelectChild ) child.setSelected( offset == 0 ); // Get measure specs int childHeightSpec = ViewGroup.getChildMeasureSpec( mHeightMeasureSpec, mSpinnerPadding.top + mSpinnerPadding.bottom, lp.height ); int childWidthSpec = ViewGroup .getChildMeasureSpec( mWidthMeasureSpec, mSpinnerPadding.left + mSpinnerPadding.right, lp.width ); // Measure child child.measure( childWidthSpec, childHeightSpec ); int childLeft; int childRight; // Position vertically based on gravity setting int childTop = calculateTop( child, true ); int childBottom = childTop + child.getMeasuredHeight(); int width = child.getMeasuredWidth(); if ( fromLeft ) { childLeft = x; childRight = childLeft + width; } else { childLeft = x - width; childRight = x; } child.layout( childLeft, childTop, childRight, childBottom ); } /** * Figure out vertical placement based on mGravity. * * @param child * Child to place * @param duringLayout * the during layout * @return Where the top of the child should be */ private int calculateTop( View child, boolean duringLayout ) { int myHeight = duringLayout ? getMeasuredHeight() : getHeight(); int childHeight = duringLayout ? child.getMeasuredHeight() : child.getHeight(); int childTop = 0; switch ( mGravity ) { case Gravity.TOP: childTop = mSpinnerPadding.top; break; case Gravity.CENTER_VERTICAL: int availableSpace = myHeight - mSpinnerPadding.bottom - mSpinnerPadding.top - childHeight; childTop = mSpinnerPadding.top + ( availableSpace / 2 ); break; case Gravity.BOTTOM: childTop = myHeight - mSpinnerPadding.bottom - childHeight; break; } return childTop; } /* * (non-Javadoc) * * @see android.view.View#onTouchEvent(android.view.MotionEvent) */ @Override public boolean onTouchEvent( MotionEvent event ) { // Give everything to the gesture detector boolean retValue = mGestureDetector.onTouchEvent( event ); int action = event.getAction(); if ( action == MotionEvent.ACTION_UP ) { // Helper method for lifted finger onUp(); } else if ( action == MotionEvent.ACTION_CANCEL ) { onCancel(); } return retValue; } /* * (non-Javadoc) * * @see android.view.GestureDetector.OnGestureListener#onSingleTapUp(android.view.MotionEvent) */ @Override public boolean onSingleTapUp( MotionEvent e ) { if ( mDownTouchPosition >= 0 && mDownTouchPosition < mItemCount ) { // An item tap should make it selected, so scroll to this child. scrollToChild( mDownTouchPosition - mFirstPosition ); // Also pass the click so the client knows, if it wants to. if ( mShouldCallbackOnUnselectedItemClick || mDownTouchPosition == mSelectedPosition ) { performItemClick( mDownTouchView, mDownTouchPosition, mAdapter.getItemId( mDownTouchPosition ) ); } return true; } return false; } /* * (non-Javadoc) * * @see android.view.GestureDetector.OnGestureListener#onFling(android.view.MotionEvent, android.view.MotionEvent, float, float) */ @Override public boolean onFling( MotionEvent e1, MotionEvent e2, float velocityX, float velocityY ) { if ( !mShouldCallbackDuringFling ) { // We want to suppress selection changes // Remove any future code to set mSuppressSelectionChanged = false removeCallbacks( mDisableSuppressSelectionChangedRunnable ); // This will get reset once we scroll into slots if ( !mSuppressSelectionChanged ) mSuppressSelectionChanged = true; } // Fling the gallery! int initialVelocity = (int) -velocityX / 2; int initialX = initialVelocity < 0 ? Integer.MAX_VALUE : 0; mFlingRunnable.startUsingVelocity( initialX, initialVelocity ); return true; } /* * (non-Javadoc) * * @see android.view.GestureDetector.OnGestureListener#onScroll(android.view.MotionEvent, android.view.MotionEvent, float, float) */ @Override public boolean onScroll( MotionEvent e1, MotionEvent e2, float distanceX, float distanceY ) { /* * Now's a good time to tell our parent to stop intercepting our events! The user has moved more than the slop amount, since * GestureDetector ensures this before calling this method. Also, if a parent is more interested in this touch's events than * we are, it would have intercepted them by now (for example, we can assume when a Gallery is in the ListView, a vertical * scroll would not end up in this method since a ListView would have intercepted it by now). */ getParent().requestDisallowInterceptTouchEvent( true ); // As the user scrolls, we want to callback selection changes so related- // info on the screen is up-to-date with the gallery's selection if ( !mShouldCallbackDuringFling ) { if ( mIsFirstScroll ) { if ( !mSuppressSelectionChanged ) mSuppressSelectionChanged = true; postDelayed( mDisableSuppressSelectionChangedRunnable, SCROLL_TO_FLING_UNCERTAINTY_TIMEOUT ); if ( mItemsScrollListener != null ) { int selection = this.getSelectedItemPosition(); if ( selection >= 0 ) { View v = getSelectedView(); mItemsScrollListener.onScrollStarted( this, v, selection, getAdapter().getItemId( selection ) ); } } } } else { if ( mSuppressSelectionChanged ) mSuppressSelectionChanged = false; } // Track the motion if ( mIsFirstScroll ) { if ( distanceX > 0 ) distanceX -= mTouchSlop; else distanceX += mTouchSlop; } int delta = -1 * (int) distanceX; float limitedDelta = getOverScrollDelta( delta < 0, delta ); if ( limitedDelta != 0 ) { delta = (int) ( delta / Math.max( 1, Math.abs( limitedDelta / 10 ) ) ); } trackMotionScroll( -delta ); mIsFirstScroll = false; return true; } /** The is down. */ private boolean isDown; /* * (non-Javadoc) * * @see android.view.GestureDetector.OnGestureListener#onDown(android.view.MotionEvent) */ @Override public boolean onDown( MotionEvent e ) { isDown = true; // Kill any existing fling/scroll mFlingRunnable.stop( false ); // Get the item's view that was touched mDownTouchPosition = pointToPosition( (int) e.getX(), (int) e.getY() ); if ( mDownTouchPosition >= 0 && mDownTouchPosition < mItemCount ) { mDownTouchView = getChildAt( mDownTouchPosition - mFirstPosition ); mDownTouchView.setPressed( true ); } // Reset the multiple-scroll tracking state mIsFirstScroll = true; // Must return true to get matching events for this down event. return true; } /** * Called when a touch event's action is MotionEvent.ACTION_UP. */ void onUp() { isDown = false; if ( mFlingRunnable.isFinished() ) { scrollIntoSlots(); } else { if ( isOverScrolled() ) { scrollIntoSlots(); } } dispatchUnpress(); } /** * Called when a touch event's action is MotionEvent.ACTION_CANCEL. */ void onCancel() { onUp(); } /* * (non-Javadoc) * * @see android.view.GestureDetector.OnGestureListener#onLongPress(android.view.MotionEvent) */ @Override public void onLongPress( MotionEvent e ) { if ( mDownTouchPosition < 0 || mDownTouchPosition <= mItemCount ) { return; } performHapticFeedback( HapticFeedbackConstants.LONG_PRESS ); long id = getItemIdAtPosition( mDownTouchPosition ); dispatchLongPress( mDownTouchView, mDownTouchPosition, id ); } // Unused methods from GestureDetector.OnGestureListener below /* * (non-Javadoc) * * @see android.view.GestureDetector.OnGestureListener#onShowPress(android.view.MotionEvent) */ @Override public void onShowPress( MotionEvent e ) {} // Unused methods from GestureDetector.OnGestureListener above /** * Dispatch press. * * @param child * the child */ private void dispatchPress( View child ) { if ( child != null ) { child.setPressed( true ); } setPressed( true ); } /** * Dispatch unpress. */ private void dispatchUnpress() { for ( int i = getChildCount() - 1; i >= 0; i-- ) { getChildAt( i ).setPressed( false ); } setPressed( false ); } /* * (non-Javadoc) * * @see android.view.ViewGroup#dispatchSetSelected(boolean) */ @Override public void dispatchSetSelected( boolean selected ) { /* * We don't want to pass the selected state given from its parent to its children since this widget itself has a selected * state to give to its children. */ } /* * (non-Javadoc) * * @see android.view.ViewGroup#dispatchSetPressed(boolean) */ @Override protected void dispatchSetPressed( boolean pressed ) { // Show the pressed state on the selected child if ( mSelectedChild != null ) { mSelectedChild.setPressed( pressed ); } } /* * (non-Javadoc) * * @see android.view.View#getContextMenuInfo() */ @Override protected ContextMenuInfo getContextMenuInfo() { return mContextMenuInfo; } /* * (non-Javadoc) * * @see android.view.ViewGroup#showContextMenuForChild(android.view.View) */ @Override public boolean showContextMenuForChild( View originalView ) { final int longPressPosition = getPositionForView( originalView ); if ( longPressPosition < 0 ) { return false; } final long longPressId = mAdapter.getItemId( longPressPosition ); return dispatchLongPress( originalView, longPressPosition, longPressId ); } /* * (non-Javadoc) * * @see android.view.View#showContextMenu() */ @Override public boolean showContextMenu() { if ( isPressed() && mSelectedPosition >= 0 ) { int index = mSelectedPosition - mFirstPosition; View v = getChildAt( index ); return dispatchLongPress( v, mSelectedPosition, mSelectedRowId ); } return false; } /** * Dispatch long press. * * @param view * the view * @param position * the position * @param id * the id * @return true, if successful */ private boolean dispatchLongPress( View view, int position, long id ) { boolean handled = false; if ( mOnItemLongClickListener != null ) { handled = mOnItemLongClickListener.onItemLongClick( this, mDownTouchView, mDownTouchPosition, id ); } if ( !handled ) { mContextMenuInfo = new AdapterContextMenuInfo( view, position, id ); handled = super.showContextMenuForChild( this ); } if ( handled ) { performHapticFeedback( HapticFeedbackConstants.LONG_PRESS ); } return handled; } /** * Handles left, right, and clicking. * * @param keyCode * the key code * @param event * the event * @return true, if successful * @see android.view.View#onKeyDown */ @Override public boolean onKeyDown( int keyCode, KeyEvent event ) { switch ( keyCode ) { case KeyEvent.KEYCODE_DPAD_LEFT: if ( movePrevious() ) { playSoundEffect( SoundEffectConstants.NAVIGATION_LEFT ); } return true; case KeyEvent.KEYCODE_DPAD_RIGHT: if ( moveNext() ) { playSoundEffect( SoundEffectConstants.NAVIGATION_RIGHT ); } return true; case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_ENTER: mReceivedInvokeKeyDown = true; // fallthrough to default handling } return false; } @Override public boolean dispatchKeyEvent( KeyEvent event ) { boolean handled = event.dispatch( this, null, null ); return handled; } /* * (non-Javadoc) * * @see android.view.View#onKeyUp(int, android.view.KeyEvent) */ @Override public boolean onKeyUp( int keyCode, KeyEvent event ) { switch ( keyCode ) { case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_ENTER: { if ( mReceivedInvokeKeyDown ) { if ( mItemCount > 0 ) { dispatchPress( mSelectedChild ); postDelayed( new Runnable() { @Override public void run() { dispatchUnpress(); } }, ViewConfiguration.getPressedStateDuration() ); int selectedIndex = mSelectedPosition - mFirstPosition; performItemClick( getChildAt( selectedIndex ), mSelectedPosition, mAdapter.getItemId( mSelectedPosition ) ); } } // Clear the flag mReceivedInvokeKeyDown = false; return true; } } return false; } /** * Move previous. * * @return true, if successful */ boolean movePrevious() { if ( mItemCount > 0 && mSelectedPosition > 0 ) { scrollToChild( mSelectedPosition - mFirstPosition - 1 ); return true; } else { return false; } } /** * Move next. * * @return true, if successful */ boolean moveNext() { if ( mItemCount > 0 && mSelectedPosition < mItemCount - 1 ) { scrollToChild( mSelectedPosition - mFirstPosition + 1 ); return true; } else { return false; } } /** * Scroll to child. * * @param childPosition * the child position * @return true, if successful */ private boolean scrollToChild( int childPosition ) { View child = getChildAt( childPosition ); if ( child != null ) { if ( mItemsScrollListener != null ) { int selection = this.getSelectedItemPosition(); if ( selection >= 0 ) { View v = getSelectedView(); mItemsScrollListener.onScrollStarted( this, v, selection, getAdapter().getItemId( selection ) ); } } int distance = getCenterOfGallery() - getCenterOfView( child ); mFlingRunnable.startUsingDistance( 0, -distance ); return true; } return false; } /* * (non-Javadoc) * * @see com.aviary.android.feather.widget.AdapterView#setSelectedPositionInt(int) */ void setSelectedPositionInt( int position, boolean animate ) { super.setSelectedPositionInt( position ); updateSelectedItemMetadata( animate, false ); } /** * Update selected item metadata. */ private void updateSelectedItemMetadata( boolean animate, boolean changed ) { View oldSelectedChild = mSelectedChild; View child = mSelectedChild = getChildAt( mSelectedPosition - mFirstPosition ); if ( child == null ) { return; } if ( mAutoSelectChild ) child.setSelected( true ); if ( mItemsScrollListener != null ) { mItemsScrollListener.onScroll( this, child, mSelectedPosition, getAdapter().getItemId( mSelectedPosition ) ); } // fire vibration if ( mSelectedPosition != mLastMotionValue && animate ) { fireVibration(); } mLastMotionValue = mSelectedPosition; child.setFocusable( true ); if ( hasFocus() ) { child.requestFocus(); } // We unfocus the old child down here so the above hasFocus check // returns true if ( oldSelectedChild != null && oldSelectedChild != child ) { // Make sure its drawable state doesn't contain 'selected' if ( mAutoSelectChild ) oldSelectedChild.setSelected( false ); // Make sure it is not focusable anymore, since otherwise arrow keys // can make this one be focused oldSelectedChild.setFocusable( false ); if ( !animate && changed ) scrollCompleted(); } } /** * Fire vibration. */ private void fireVibration() { if ( mVibrationHandler != null ) { mVibrationHandler.sendEmptyMessage( MSG_VIBRATE ); } } /** * Describes how the child views are aligned. * * @param gravity * the new gravity * @attr ref android.R.styleable#Gallery_gravity */ public void setGravity( int gravity ) { if ( mGravity != gravity ) { mGravity = gravity; requestLayout(); } } /* * (non-Javadoc) * * @see android.view.ViewGroup#getChildDrawingOrder(int, int) */ @Override protected int getChildDrawingOrder( int childCount, int i ) { int selectedIndex = mSelectedPosition - mFirstPosition; // Just to be safe if ( selectedIndex < 0 ) return i; if ( i == childCount - 1 ) { // Draw the selected child last return selectedIndex; } else if ( i >= selectedIndex ) { // Move the children after the selected child earlier one return i + 1; } else { // Keep the children before the selected child the same return i; } } /* * (non-Javadoc) * * @see android.view.View#onFocusChanged(boolean, int, android.graphics.Rect) */ @Override protected void onFocusChanged( boolean gainFocus, int direction, Rect previouslyFocusedRect ) { super.onFocusChanged( gainFocus, direction, previouslyFocusedRect ); /* * The gallery shows focus by focusing the selected item. So, give focus to our selected item instead. We steal keys from our * selected item elsewhere. */ if ( gainFocus && mSelectedChild != null ) { mSelectedChild.requestFocus( direction ); if ( mAutoSelectChild ) mSelectedChild.setSelected( true ); } } /** The m scroll selection notifier. */ ScrollSelectionNotifier mScrollSelectionNotifier; /** * The Class ScrollSelectionNotifier. */ private class ScrollSelectionNotifier implements Runnable { /* * (non-Javadoc) * * @see java.lang.Runnable#run() */ @Override public void run() { if ( mDataChanged ) { if ( getAdapter() != null ) { post( this ); } } else { fireOnScrollCompleted(); } } } /** * Scroll completed. */ void scrollCompleted() { if ( mItemsScrollListener != null ) { if ( mInLayout || mBlockLayoutRequests ) { // If we are in a layout traversal, defer notification // by posting. This ensures that the view tree is // in a consistent state and is able to accomodate // new layout or invalidate requests. if ( mScrollSelectionNotifier == null ) { mScrollSelectionNotifier = new ScrollSelectionNotifier(); } post( mScrollSelectionNotifier ); } else { fireOnScrollCompleted(); } } } /** * Fire on scroll completed. */ private void fireOnScrollCompleted() { if ( mItemsScrollListener == null ) return; int selection = this.getSelectedItemPosition(); if ( selection >= 0 && selection < mItemCount ) { View v = getSelectedView(); mItemsScrollListener.onScrollFinished( this, v, selection, getAdapter().getItemId( selection ) ); } } /** * Gallery extends LayoutParams to provide a place to hold current Transformation information along with previous * position/transformation info. */ public static class LayoutParams extends ViewGroup.LayoutParams { /** * Instantiates a new layout params. * * @param c * the c * @param attrs * the attrs */ public LayoutParams( Context c, AttributeSet attrs ) { super( c, attrs ); } /** * Instantiates a new layout params. * * @param w * the w * @param h * the h */ public LayoutParams( int w, int h ) { super( w, h ); } /** * Instantiates a new layout params. * * @param source * the source */ public LayoutParams( ViewGroup.LayoutParams source ) { super( source ); } } @Override public int getMinX() { return 0; } @Override public int getMaxX() { return Integer.MAX_VALUE; } }
Java
package com.aviary.android.feather.widget; import it.sephiroth.android.library.imagezoom.ImageViewTouch; import android.content.Context; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.MotionEvent; import com.aviary.android.feather.library.graphics.drawable.IBitmapDrawable; // TODO: Auto-generated Javadoc /** * The Class ImageViewSpotDraw. */ public class ImageViewSpotDraw extends ImageViewTouch { /** * The Enum TouchMode. */ public static enum TouchMode { /** The IMAGE. */ IMAGE, /** The DRAW. */ DRAW }; /** * The listener interface for receiving onDraw events. The class that is interested in processing a onDraw event implements this * interface, and the object created with that class is registered with a component using the component's * <code>addOnDrawListener<code> method. When * the onDraw event occurs, that object's appropriate * method is invoked. * * @see OnDrawEvent */ public static interface OnDrawListener { /** * On draw start. * * @param points * the points * @param radius * the radius */ void onDrawStart( float points[], int radius ); /** * On drawing. * * @param points * the points * @param radius * the radius */ void onDrawing( float points[], int radius ); /** * On draw end. */ void onDrawEnd(); }; /** The m paint. */ protected Paint mPaint; /** The m current scale. */ protected float mCurrentScale = 1; /** The m brush size. */ protected float mBrushSize = 30; /** The tmp path. */ protected Path tmpPath = new Path(); /** The m canvas. */ protected Canvas mCanvas; /** The m touch mode. */ protected TouchMode mTouchMode = TouchMode.DRAW; /** The m y. */ protected float mX, mY; protected float mStartX, mStartY; /** The m identity matrix. */ protected Matrix mIdentityMatrix = new Matrix(); /** The m inverted matrix. */ protected Matrix mInvertedMatrix = new Matrix(); /** The Constant TOUCH_TOLERANCE. */ protected static final float TOUCH_TOLERANCE = 2; /** The m draw listener. */ private OnDrawListener mDrawListener; /** draw restriction **/ private double mRestiction = 0; /** * Instantiates a new image view spot draw. * * @param context * the context * @param attrs * the attrs */ public ImageViewSpotDraw( Context context, AttributeSet attrs ) { super( context, attrs ); } /** * Sets the on draw start listener. * * @param listener * the new on draw start listener */ public void setOnDrawStartListener( OnDrawListener listener ) { mDrawListener = listener; } /* * (non-Javadoc) * * @see it.sephiroth.android.library.imagezoom.ImageViewTouch#init() */ @Override protected void init() { super.init(); mPaint = new Paint( Paint.ANTI_ALIAS_FLAG ); mPaint.setFilterBitmap( false ); mPaint.setDither( true ); mPaint.setColor( 0x66FFFFCC ); mPaint.setStyle( Paint.Style.STROKE ); mPaint.setStrokeCap( Paint.Cap.ROUND ); tmpPath = new Path(); } public void setDrawLimit( double value ) { mRestiction = value; } /** * Sets the brush size. * * @param value * the new brush size */ public void setBrushSize( float value ) { mBrushSize = value; if ( mPaint != null ) { mPaint.setStrokeWidth( mBrushSize ); } } /** * Gets the draw mode. * * @return the draw mode */ public TouchMode getDrawMode() { return mTouchMode; } /** * Sets the draw mode. * * @param mode * the new draw mode */ public void setDrawMode( TouchMode mode ) { if ( mode != mTouchMode ) { mTouchMode = mode; onDrawModeChanged(); } } /** * On draw mode changed. */ protected void onDrawModeChanged() { if ( mTouchMode == TouchMode.DRAW ) { Matrix m1 = new Matrix( getImageMatrix() ); mInvertedMatrix.reset(); float[] v1 = getMatrixValues( m1 ); m1.invert( m1 ); float[] v2 = getMatrixValues( m1 ); mInvertedMatrix.postTranslate( -v1[Matrix.MTRANS_X], -v1[Matrix.MTRANS_Y] ); mInvertedMatrix.postScale( v2[Matrix.MSCALE_X], v2[Matrix.MSCALE_Y] ); mCanvas.setMatrix( mInvertedMatrix ); mCurrentScale = getScale(); mPaint.setStrokeWidth( mBrushSize ); } } /** * Gets the paint. * * @return the paint */ public Paint getPaint() { return mPaint; } /** * Sets the paint. * * @param paint * the new paint */ public void setPaint( Paint paint ) { mPaint.set( paint ); } /* * (non-Javadoc) * * @see android.widget.ImageView#onDraw(android.graphics.Canvas) */ @Override protected void onDraw( Canvas canvas ) { super.onDraw( canvas ); canvas.drawPath( tmpPath, mPaint ); } public RectF getImageRect() { if ( getDrawable() != null ) { return new RectF( 0, 0, getDrawable().getIntrinsicWidth(), getDrawable().getIntrinsicHeight() ); } else { return null; } } /* * (non-Javadoc) * * @see it.sephiroth.android.library.imagezoom.ImageViewTouch#onBitmapChanged(android.graphics.drawable.Drawable) */ @Override protected void onBitmapChanged( Drawable drawable ) { super.onBitmapChanged( drawable ); if ( drawable != null && ( drawable instanceof IBitmapDrawable ) ) { mCanvas = new Canvas(); mCanvas.drawColor( 0 ); onDrawModeChanged(); } } /** The m moved. */ private boolean mMoved = false; /** * Touch_start. * * @param x * the x * @param y * the y */ private void touch_start( float x, float y ) { mMoved = false; tmpPath.reset(); tmpPath.moveTo( x, y ); mX = x; mY = y; mStartX = x; mStartY = y; if ( mDrawListener != null ) { float mappedPoints[] = new float[2]; mappedPoints[0] = x; mappedPoints[1] = y; mInvertedMatrix.mapPoints( mappedPoints ); tmpPath.lineTo( x + .1f, y ); mDrawListener.onDrawStart( mappedPoints, (int) ( mBrushSize / mCurrentScale ) ); } } /** * Touch_move. * * @param x * the x * @param y * the y */ private void touch_move( float x, float y ) { float dx = Math.abs( x - mX ); float dy = Math.abs( y - mY ); if ( dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE ) { if ( !mMoved ) { tmpPath.setLastPoint( mX, mY ); } mMoved = true; if ( mRestiction > 0 ) { double r = Math.sqrt( Math.pow( x - mStartX, 2 ) + Math.pow( y - mStartY, 2 ) ); double theta = Math.atan2( y - mStartY, x - mStartX ); final float w = getWidth(); final float h = getHeight(); double scale = ( mRestiction / mCurrentScale ) / (double) ( w + h ) / ( mBrushSize / mCurrentScale ); double rNew = Math.log( r * scale + 1 ) / scale; x = (float) ( mStartX + rNew * Math.cos( theta ) ); y = (float) ( mStartY + rNew * Math.sin( theta ) ); } tmpPath.quadTo( mX, mY, ( x + mX ) / 2, ( y + mY ) / 2 ); mX = x; mY = y; } if ( mDrawListener != null ) { float mappedPoints[] = new float[2]; mappedPoints[0] = x; mappedPoints[1] = y; mInvertedMatrix.mapPoints( mappedPoints ); mDrawListener.onDrawing( mappedPoints, (int) ( mBrushSize / mCurrentScale ) ); } } /** * Touch_up. */ private void touch_up() { tmpPath.reset(); if ( mDrawListener != null ) { mDrawListener.onDrawEnd(); } } /** * Gets the matrix values. * * @param m * the m * @return the matrix values */ public static float[] getMatrixValues( Matrix m ) { float[] values = new float[9]; m.getValues( values ); return values; } /* * (non-Javadoc) * * @see it.sephiroth.android.library.imagezoom.ImageViewTouch#onTouchEvent(android.view.MotionEvent) */ @Override public boolean onTouchEvent( MotionEvent event ) { if ( mTouchMode == TouchMode.DRAW && event.getPointerCount() == 1 ) { float x = event.getX(); float y = event.getY(); switch ( event.getAction() ) { case MotionEvent.ACTION_DOWN: touch_start( x, y ); invalidate(); break; case MotionEvent.ACTION_MOVE: touch_move( x, y ); invalidate(); break; case MotionEvent.ACTION_UP: touch_up(); invalidate(); break; } return true; } else { if ( mTouchMode == TouchMode.IMAGE ) return super.onTouchEvent( event ); else return false; } } }
Java
package com.aviary.android.feather.widget; import android.content.Context; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.MotionEvent; import android.view.View; /** * acts a an swipe gesture overylay for a view */ public class SwipeView extends View { public static interface OnSwipeListener { // allow classes to implement as they wish when they overlay a SwipeView public void onSwipe( boolean leftToRight ); } private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_MAX_OFF_PATH = 250; private static final int SWIPE_THRESHOLD_VELOCITY = 200; private OnSwipeListener mOnSwipeListener; View.OnTouchListener gestureListener; private GestureDetector gestureDetector; public SwipeView( Context context ) { super( context ); // TODO Auto-generated constructor stub gestureDetector = new GestureDetector( new SwipeDetector() ); gestureListener = new View.OnTouchListener() { public boolean onTouch( View v, MotionEvent event ) { return gestureDetector.onTouchEvent( event ); } }; this.setOnTouchListener( gestureListener ); } public SwipeView( Context context, AttributeSet attrs ) { super( context, attrs ); // TODO Auto-generated constructor stub gestureDetector = new GestureDetector( new SwipeDetector() ); gestureListener = new View.OnTouchListener() { public boolean onTouch( View v, MotionEvent event ) { return gestureDetector.onTouchEvent( event ); } }; this.setOnTouchListener( gestureListener ); } public SwipeView( Context context, AttributeSet attrs, int defStyle ) { super( context, attrs, defStyle ); // TODO Auto-generated constructor stub gestureDetector = new GestureDetector( new SwipeDetector() ); gestureListener = new View.OnTouchListener() { public boolean onTouch( View v, MotionEvent event ) { return gestureDetector.onTouchEvent( event ); } }; this.setOnTouchListener( gestureListener ); } public OnSwipeListener getOnSwipeListener() { return mOnSwipeListener; } public void setOnSwipeListener( OnSwipeListener swipeDetector ) { mOnSwipeListener = swipeDetector; } public class SwipeDetector extends SimpleOnGestureListener { @Override public boolean onDoubleTap( MotionEvent e ) { return false; } @Override public boolean onScroll( MotionEvent e1, MotionEvent e2, float distanceX, float distanceY ) { return false; } @Override public boolean onFling( MotionEvent e1, MotionEvent e2, float velocityX, float velocityY ) { try { if ( Math.abs( e1.getY() - e2.getY() ) > SWIPE_MAX_OFF_PATH ) return false; // right to left swipe if ( e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs( velocityX ) > SWIPE_THRESHOLD_VELOCITY ) { if ( mOnSwipeListener != null ) { mOnSwipeListener.onSwipe( false ); } } // left to right swipe else if ( e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs( velocityX ) > SWIPE_THRESHOLD_VELOCITY ) { if ( mOnSwipeListener != null ) { mOnSwipeListener.onSwipe( true ); } } } catch ( Exception e ) { // nothing } return false; } } }
Java
package com.aviary.android.feather.widget; import it.sephiroth.android.library.imagezoom.easing.Easing; import it.sephiroth.android.library.imagezoom.easing.Expo; import it.sephiroth.android.library.imagezoom.easing.Linear; import android.content.ContentResolver; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BlurMaskFilter; import android.graphics.BlurMaskFilter.Blur; import android.graphics.Camera; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PointF; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Handler; import android.util.AttributeSet; import android.util.FloatMath; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.RemoteViews.RemoteView; import com.outsourcing.bottle.R; import com.aviary.android.feather.library.graphics.Point2D; import com.aviary.android.feather.library.log.LoggerFactory; import com.aviary.android.feather.library.log.LoggerFactory.Logger; import com.aviary.android.feather.library.log.LoggerFactory.LoggerType; import com.aviary.android.feather.library.utils.ReflectionUtils; import com.aviary.android.feather.library.utils.ReflectionUtils.ReflectionException; // TODO: Auto-generated Javadoc /** * Displays an arbitrary image, such as an icon. The ImageView class can load images from various sources (such as resources or * content providers), takes care of computing its measurement from the image so that it can be used in any layout manager, and * provides various display options such as scaling and tinting. * * @attr ref android.R.styleable#ImageView_adjustViewBounds * @attr ref android.R.styleable#ImageView_src * @attr ref android.R.styleable#ImageView_maxWidth * @attr ref android.R.styleable#ImageView_maxHeight * @attr ref android.R.styleable#ImageView_tint * @attr ref android.R.styleable#ImageView_scaleType * @attr ref android.R.styleable#ImageView_cropToPadding */ @RemoteView public class AdjustImageView extends View { /** The Constant LOG_TAG. */ static final String LOG_TAG = "rotate"; // settable by the client /** The m uri. */ private Uri mUri; /** The m resource. */ private int mResource = 0; /** The m matrix. */ private Matrix mMatrix; /** The m scale type. */ private ScaleType mScaleType; /** The m adjust view bounds. */ private boolean mAdjustViewBounds = false; /** The m max width. */ private int mMaxWidth = Integer.MAX_VALUE; /** The m max height. */ private int mMaxHeight = Integer.MAX_VALUE; // these are applied to the drawable /** The m color filter. */ private ColorFilter mColorFilter; /** The m alpha. */ private int mAlpha = 255; /** The m view alpha scale. */ private int mViewAlphaScale = 256; /** The m color mod. */ private boolean mColorMod = false; /** The m drawable. */ private Drawable mDrawable = null; /** The m state. */ private int[] mState = null; /** The m merge state. */ private boolean mMergeState = false; /** The m level. */ private int mLevel = 0; /** The m drawable width. */ private int mDrawableWidth; /** The m drawable height. */ private int mDrawableHeight; /** The m draw matrix. */ private Matrix mDrawMatrix = null; private Matrix mTempMatrix = new Matrix(); /** The m rotate matrix. */ private Matrix mRotateMatrix = new Matrix(); /** The m flip matrix. */ private Matrix mFlipMatrix = new Matrix(); // Avoid allocations... /** The m temp src. */ private RectF mTempSrc = new RectF(); /** The m temp dst. */ private RectF mTempDst = new RectF(); /** The m crop to padding. */ private boolean mCropToPadding; /** The m baseline. */ private int mBaseline = -1; /** The m baseline align bottom. */ private boolean mBaselineAlignBottom = false; /** The m have frame. */ private boolean mHaveFrame; /** The m easing. */ private Easing mEasing = new Expo(); /** View is in the reset state. */ boolean isReset = false; /** reset animation time. */ int resetAnimTime = 200; Path mClipPath = new Path(); Path mInversePath = new Path(); Rect mViewDrawRect = new Rect(); RectF mViewInvertRect = new RectF(); Paint mOutlinePaint = new Paint(); Paint mOutlineFill = new Paint(); RectF mDrawRect; PointF mCenter = new PointF(); Path mLinesPath = new Path(); Paint mLinesPaint = new Paint(); Paint mLinesPaintShadow = new Paint(); // Drawable Drawable; Drawable mStraightenDrawable; int handleWidth, handleHeight; final int grid_rows = 8; final int grid_cols = 8; private boolean mEnableFreeRotate; static Logger logger = LoggerFactory.getLogger( "rotate", LoggerType.ConsoleLoggerType ); /** * Sets the reset anim duration. * * @param value * the new reset anim duration */ public void setResetAnimDuration( int value ) { resetAnimTime = value; } public void setEnableFreeRotate( boolean value ) { mEnableFreeRotate = value; } public boolean isFreeRotateEnabled() { return mEnableFreeRotate; } /** * The listener interface for receiving onReset events. The class that is interested in processing a onReset event implements * this interface, and the object created with that class is registered with a component using the component's * <code>addOnResetListener<code> method. When * the onReset event occurs, that object's appropriate * method is invoked. * * @see OnResetEvent */ public interface OnResetListener { /** * On reset complete. */ void onResetComplete(); } /** The m reset listener. */ private OnResetListener mResetListener; /** * Sets the on reset listener. * * @param listener * the new on reset listener */ public void setOnResetListener( OnResetListener listener ) { mResetListener = listener; } /** The Constant sScaleTypeArray. */ @SuppressWarnings("unused") private static final ScaleType[] sScaleTypeArray = { ScaleType.MATRIX, ScaleType.FIT_XY, ScaleType.FIT_START, ScaleType.FIT_CENTER, ScaleType.FIT_END, ScaleType.CENTER, ScaleType.CENTER_CROP, ScaleType.CENTER_INSIDE }; /** * Instantiates a new adjust image view. * * @param context * the context */ public AdjustImageView( Context context ) { super( context ); initImageView(); } /** * Instantiates a new adjust image view. * * @param context * the context * @param attrs * the attrs */ public AdjustImageView( Context context, AttributeSet attrs ) { this( context, attrs, 0 ); } /** * Instantiates a new adjust image view. * * @param context * the context * @param attrs * the attrs * @param defStyle * the def style */ public AdjustImageView( Context context, AttributeSet attrs, int defStyle ) { super( context, attrs, defStyle ); initImageView(); } /** * Sets the easing. * * @param value * the new easing */ public void setEasing( Easing value ) { mEasing = value; } int mOutlinePaintAlpha, mOutlineFillAlpha, mLinesAlpha, mLinesShadowAlpha; /** * Inits the image view. */ private void initImageView() { mMatrix = new Matrix(); mScaleType = ScaleType.FIT_CENTER; Context context = getContext(); int highlight_color = context.getResources().getColor( R.color.feather_rotate_highlight_stroke_color ); int highlight_stroke_internal_color = context.getResources().getColor( R.color.feather_rotate_highlight_grid_stroke_color ); int highlight_stroke_internal_width = context.getResources() .getInteger( R.integer.feather_rotate_highlight_grid_stroke_width ); int highlight_outside_color = context.getResources().getColor( R.color.feather_rotate_highlight_outside ); int highlight_stroke_width = context.getResources().getInteger( R.integer.feather_rotate_highlight_stroke_width ); mOutlinePaint.setStrokeWidth( highlight_stroke_width ); mOutlinePaint.setStyle( Paint.Style.STROKE ); mOutlinePaint.setAntiAlias( true ); mOutlinePaint.setColor( highlight_color ); mOutlineFill.setStyle( Paint.Style.FILL ); mOutlineFill.setAntiAlias( false ); mOutlineFill.setColor( highlight_outside_color ); mOutlineFill.setDither( false ); try { ReflectionUtils.invokeMethod( mOutlineFill, "setHinting", new Class<?>[] { int.class }, 0 ); } catch ( ReflectionException e ) {} mLinesPaint.setStrokeWidth( highlight_stroke_internal_width ); mLinesPaint.setAntiAlias( false ); mLinesPaint.setDither( false ); mLinesPaint.setStyle( Paint.Style.STROKE ); mLinesPaint.setColor( highlight_stroke_internal_color ); try { ReflectionUtils.invokeMethod( mLinesPaint, "setHinting", new Class<?>[] { int.class }, 0 ); } catch ( ReflectionException e ) {} mLinesPaintShadow.setStrokeWidth( highlight_stroke_internal_width ); mLinesPaintShadow.setAntiAlias( true ); mLinesPaintShadow.setColor( Color.BLACK ); mLinesPaintShadow.setStyle( Paint.Style.STROKE ); mLinesPaintShadow.setMaskFilter( new BlurMaskFilter( 2, Blur.NORMAL ) ); mOutlineFillAlpha = mOutlineFill.getAlpha(); mOutlinePaintAlpha = mOutlinePaint.getAlpha(); mLinesAlpha = mLinesPaint.getAlpha(); mLinesShadowAlpha = mLinesPaintShadow.getAlpha(); mOutlinePaint.setAlpha( 0 ); mOutlineFill.setAlpha( 0 ); mLinesPaint.setAlpha( 0 ); mLinesPaintShadow.setAlpha( 0 ); android.content.res.Resources resources = getContext().getResources(); mStraightenDrawable = resources.getDrawable( R.drawable.feather_straighten_knob ); double w = mStraightenDrawable.getIntrinsicWidth(); double h = mStraightenDrawable.getIntrinsicHeight(); handleWidth = (int) Math.ceil( w / 2.0 ); handleHeight = (int) Math.ceil( h / 2.0 ); } /* * (non-Javadoc) * * @see android.view.View#verifyDrawable(android.graphics.drawable.Drawable) */ @Override protected boolean verifyDrawable( Drawable dr ) { return mDrawable == dr || super.verifyDrawable( dr ); } /* * (non-Javadoc) * * @see android.view.View#invalidateDrawable(android.graphics.drawable.Drawable) */ @Override public void invalidateDrawable( Drawable dr ) { if ( dr == mDrawable ) { /* * we invalidate the whole view in this case because it's very hard to know where the drawable actually is. This is made * complicated because of the offsets and transformations that can be applied. In theory we could get the drawable's bounds * and run them through the transformation and offsets, but this is probably not worth the effort. */ invalidate(); } else { super.invalidateDrawable( dr ); } } /* * (non-Javadoc) * * @see android.view.View#onSetAlpha(int) */ @Override protected boolean onSetAlpha( int alpha ) { if ( getBackground() == null ) { int scale = alpha + ( alpha >> 7 ); if ( mViewAlphaScale != scale ) { mViewAlphaScale = scale; mColorMod = true; applyColorMod(); } return true; } return false; } private PointF getCenter() { final int vwidth = getWidth() - getPaddingLeft() - getPaddingRight(); final int vheight = getHeight() - getPaddingTop() - getPaddingBottom(); return new PointF( (float) vwidth / 2, (float) vheight / 2 ); } private RectF getViewRect() { final int vwidth = getWidth() - getPaddingLeft() - getPaddingRight(); final int vheight = getHeight() - getPaddingTop() - getPaddingBottom(); return new RectF( 0, 0, vwidth, vheight ); } private RectF getImageRect() { return new RectF( 0, 0, mDrawableWidth, mDrawableHeight ); } private void onTouchStart() { if ( mFadeHandlerStarted ) { fadeinGrid( 300 ); } else { fadeinOutlines( 600 ); } } /** * private void onTouchMove( float x, float y ) { if ( isDown ) { PointF current = new PointF( x, y ); PointF center = * getCenter(); * * float angle = (float) Point2D.angle360( originalAngle - Point2D.angleBetweenPoints( center, current ) ); * * logger.log( "ANGLE: " + angle + " .. " + getAngle90( angle ) ); * * setImageRotation( angle, false ); mRotation = angle; invalidate(); } } */ private void setImageRotation( double angle, boolean invert ) { PointF center = getCenter(); Matrix tempMatrix = new Matrix( mDrawMatrix ); RectF src = getImageRect(); RectF dst = getViewRect(); tempMatrix.setRotate( (float) angle, center.x, center.y ); tempMatrix.mapRect( src ); tempMatrix.setRectToRect( src, dst, scaleTypeToScaleToFit( mScaleType ) ); float[] scale = getMatrixScale( tempMatrix ); float fScale = Math.min( scale[0], scale[1] ); if ( invert ) { mRotateMatrix.setRotate( (float) angle, center.x, center.y ); mRotateMatrix.postScale( fScale, fScale, center.x, center.y ); } else { mRotateMatrix.setScale( fScale, fScale, center.x, center.y ); mRotateMatrix.postRotate( (float) angle, center.x, center.y ); } } private void onTouchUp() { invalidate(); fadeoutGrid( 300 ); } boolean straightenStarted = false; double previousStraightenAngle = 0; double prevGrowth = 1; double currentNewPosition; boolean testStraighten = true; double prevGrowthAngle = 0; float currentGrowth = 0; Matrix mStraightenMatrix = new Matrix(); double previousAngle = 0; boolean intersectPoints = true; boolean portrait = false; int orientation = 0; // the orientation of the screen, whether in landscape or portrait public double getGrowthFactor() { return prevGrowth; } public double getStraightenAngle() { return previousStraightenAngle; } /** * * Calculates the new angle and size of of the image through matrix and geometric operations * * @param angleDifference * - difference between previous angle and current angle * @param direction * - if there is an increase or decrease in angle * @param newPosition * - the new destination angle */ private void setStraightenRotation( double newPosition ) { logger.info( "setStraightenRotation: " + newPosition + ", prev: " + previousStraightenAngle ); // angle here is the difference between previous angle and new angle // you need to take advantage of the third parameter, newPosition double growthFactor = 1; //newPosition = newPosition / 2; currentNewPosition = newPosition; PointF center = getCenter(); mStraightenMatrix.postRotate( (float) -previousStraightenAngle, center.x, center.y ); mStraightenMatrix.postRotate( (float) newPosition, center.x, center.y ); previousStraightenAngle = newPosition; double divideGrowth = 1 / prevGrowth; mStraightenMatrix.postScale( (float) divideGrowth, (float) divideGrowth, center.x, center.y ); prevGrowthAngle = newPosition; if ( portrait ) { // this algorithm works slightly differently between landscape and portrait images because of the proportions final double sin_rad = Math.sin( Math.toRadians( currentNewPosition ) ); final double cos_rad = Math.cos( Math.toRadians( currentNewPosition ) ); float[] testPoint = { (float) ( imageCaptureRegion.left + sin_rad * getPaddingLeft() + cos_rad * getPaddingLeft() ), (float) ( imageCaptureRegion.top - sin_rad * getPaddingTop() + cos_rad * getPaddingLeft() ), (float) ( imageCaptureRegion.right + sin_rad * getPaddingRight() + cos_rad * getPaddingRight() ), (float) ( imageCaptureRegion.top - sin_rad * getPaddingTop() + cos_rad * getPaddingLeft() ), (float) ( imageCaptureRegion.left + sin_rad * getPaddingLeft() + cos_rad * getPaddingLeft() ), (float) ( imageCaptureRegion.bottom - sin_rad * getPaddingBottom() + cos_rad * getPaddingBottom() ), (float) ( imageCaptureRegion.right + sin_rad * getPaddingRight() + cos_rad * getPaddingRight() ), (float) ( imageCaptureRegion.bottom - sin_rad * getPaddingBottom() + cos_rad * getPaddingBottom() ) }; mStraightenMatrix.mapPoints( testPoint ); /** * ax = trueRect.left+getPaddingLeft(); ay = trueRect.top+getPaddingTop(); bx = trueRect.right+getPaddingRight(); by = * trueRect.top+getPaddingTop(); cx = trueRect.left+getPaddingLeft(); cy = trueRect.bottom+getPaddingBottom(); dx = * trueRect.right+getPaddingRight(); dy = trueRect.bottom+getPaddingBottom(); */ float x1 = (float) ( imageCaptureRegion.right + sin_rad * getPaddingRight() + cos_rad * getPaddingRight() ); float y1 = (float) ( imageCaptureRegion.top - sin_rad * getPaddingTop() + cos_rad * getPaddingTop() ); float x2 = (float) ( imageCaptureRegion.right + sin_rad * getPaddingRight() + cos_rad * getPaddingRight() ); float y2 = (float) ( imageCaptureRegion.bottom - sin_rad * getPaddingBottom() + cos_rad * getPaddingBottom() ); float x3 = testPoint[2]; float y3 = testPoint[3]; float x4 = testPoint[6]; float y4 = testPoint[7]; double numerator2 = ( x1 * y2 - y1 * x2 ) * ( y3 - y4 ) - ( y1 - y2 ) * ( x3 * y4 - y3 * x4 ); double denominator2 = ( ( x1 - x2 ) * ( y3 - y4 ) - ( y1 - y2 ) * ( x3 - x4 ) ); double Px = imageCaptureRegion.right + getPaddingRight(); double Py = ( numerator2 ) / ( denominator2 ) + getPaddingBottom(); orientation = getResources().getConfiguration().orientation; if ( orientation == Configuration.ORIENTATION_LANDSCAPE && newPosition > 0 ) { Py = ( numerator2 ) / ( denominator2 ) + sin_rad * getPaddingBottom(); } double dx = Px - x2; double dy = Py - y2; if ( newPosition < 0 ) { dx = Px - x1; dy = Py - y1; } double distance = Math.sqrt( dx * dx + dy * dy ); double amountNeededToGrow = ( 2 * distance * ( Math.sin( Math.toRadians( Math.abs( newPosition ) ) ) ) ); distance = FloatMath.sqrt( ( testPoint[0] - testPoint[2] ) * ( testPoint[0] - testPoint[2] ) ); if ( newPosition != 0 ) { growthFactor = ( distance + amountNeededToGrow ) / distance; mStraightenMatrix.postScale( (float) growthFactor, (float) growthFactor, center.x, center.y ); } else { growthFactor = 1; } // intersectx = (float) Px; // intersecty = (float) Py; } else { final double sin_rad = Math.sin( Math.toRadians( currentNewPosition ) ); final double cos_rad = Math.cos( Math.toRadians( currentNewPosition ) ); float[] testPoint = { (float) ( imageCaptureRegion.left + sin_rad * getPaddingLeft() + cos_rad * getPaddingLeft() ), (float) ( imageCaptureRegion.top - sin_rad * getPaddingTop() + cos_rad * getPaddingLeft() ), (float) ( imageCaptureRegion.right + sin_rad * getPaddingRight() + cos_rad * getPaddingRight() ), (float) ( imageCaptureRegion.top - sin_rad * getPaddingTop() + cos_rad * getPaddingLeft() ), (float) ( imageCaptureRegion.left + sin_rad * getPaddingLeft() + cos_rad * getPaddingLeft() ), (float) ( imageCaptureRegion.bottom - sin_rad * getPaddingBottom() + cos_rad * getPaddingBottom() ), (float) ( imageCaptureRegion.right + sin_rad * getPaddingRight() + cos_rad * getPaddingRight() ), (float) ( imageCaptureRegion.bottom - sin_rad * getPaddingBottom() + cos_rad * getPaddingBottom() ) }; mStraightenMatrix.mapPoints( testPoint ); /** * ax = testPoint[0]; ay = testPoint[1]; bx = testPoint[2]; by = testPoint[3]; cx = testPoint[4]; cy = testPoint[5]; dx = * testPoint[6]; dy = testPoint[7]; */ float x1 = (float) ( imageCaptureRegion.left + sin_rad * getPaddingLeft() + cos_rad * getPaddingLeft() ); float y1 = (float) ( imageCaptureRegion.bottom - sin_rad * getPaddingBottom() + cos_rad * getPaddingBottom() ); float x2 = (float) ( imageCaptureRegion.right + sin_rad * getPaddingRight() + cos_rad * getPaddingRight() ); float y2 = (float) ( imageCaptureRegion.bottom - sin_rad * getPaddingBottom() + cos_rad * getPaddingBottom() ); float x3 = testPoint[4]; float y3 = testPoint[5]; float x4 = testPoint[6]; float y4 = testPoint[7]; double numerator1 = ( x1 * y2 - y1 * x2 ) * ( x3 - x4 ) - ( x1 - x2 ) * ( x3 * y4 - y3 * x4 ); double denominator1 = ( ( x1 - x2 ) * ( y3 - y4 ) - ( y1 - y2 ) * ( x3 - x4 ) ); double Px = ( numerator1 ) / ( denominator1 ) + getPaddingLeft(); double Py = imageCaptureRegion.bottom + getPaddingBottom(); double dx = Px - x1; double dy = Py - y1; if ( newPosition < 0 ) { dx = Px - x2; dy = Py - y2; } double distance = Math.sqrt( dx * dx + dy * dy ); double amountNeededToGrow = ( 2 * distance * ( Math.sin( Math.toRadians( Math.abs( newPosition ) ) ) ) ); distance = FloatMath.sqrt( ( testPoint[5] - testPoint[1] ) * ( testPoint[5] - testPoint[1] ) ); if ( newPosition != 0 ) { growthFactor = ( distance + amountNeededToGrow ) / distance; mStraightenMatrix.postScale( (float) growthFactor, (float) growthFactor, center.x, center.y ); } else { growthFactor = 1; } // intersectx = (float) Px; // intersecty = (float) Py; } // now the resize-grow stuff prevGrowth = growthFactor; } /** * * The top level call for the straightening of the image * * @param newPosition * - the destination angle for the image * @param durationMs * - animation time * @param direction * - if there is increase or decrease of angle of rotation */ public void straighten( final double newPosition, final int durationMs ) { if ( mRunning ) { return; } mRunning = true; straightenStarted = true; invalidate(); mHandler.post( new Runnable() { @Override public void run() { /** * If, for example, the current rotation position is 2 degrees and then we want the original photo to be rotated 45 * degrees, we can simply rotate the current photo 43 degrees... */ setStraightenRotation( newPosition ); invalidate(); mRunning = false; } } ); } /** * * The top level call for the straightening of the image * * @param newPosition * - the destination angle for the image * @param durationMs * - animation time * @param direction * - if there is increase or decrease of angle of rotation */ public void straightenBy( final double newPosition, final int durationMs ) { logger.info( "straightenBy: " + newPosition + ", duration: " + durationMs ); if ( mRunning ) { return; } mRunning = true; straightenStarted = true; final long startTime = System.currentTimeMillis(); final double destRotation = getStraightenAngle() + newPosition; final double srcRotation = getStraightenAngle(); logger.info( "destRotation: " + destRotation ); invalidate(); mHandler.post( new Runnable() { @Override public void run() { long now = System.currentTimeMillis(); float currentMs = Math.min( durationMs, now - startTime ); double new_rotation = (mEasing.easeInOut( currentMs, 0, newPosition, durationMs )); logger.log( "straightenBy... new_rotation: " + new_rotation ); logger.log( "time: " + currentMs ); setStraightenRotation( srcRotation + new_rotation ); invalidate(); if( currentMs < durationMs ){ mHandler.post( this ); } else { setStraightenRotation( destRotation ); invalidate(); mRunning = false; if( isReset ){ straightenStarted = false; onReset(); } } } } ); } private float mLastTouchX; private float mPosX; Rect testRect = new Rect( 0, 0, 0, 0 ); final int straightenDuration = 50; int previousPosition = 0; boolean initTool = true; @Override public boolean onTouchEvent( MotionEvent ev ) { if ( !mEnableFreeRotate ) return true; final int action = ev.getAction(); if ( initStraighten ) { resetStraighten(); } switch ( action ) { case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); onTouchStart(); // Remember where we started mLastTouchX = x; break; } case MotionEvent.ACTION_MOVE: { final float x = ev.getX(); final float y = ev.getY(); // Calculate the distance moved final float dx = x - mLastTouchX; // Move the object mPosX += dx; // Remember this touch position for the next move event mLastTouchX = x; Rect bounds = mStraightenDrawable.getBounds(); Rect straightenMoveRegion = new Rect( (int) imageCaptureRegion.left + getPaddingLeft(), bounds.top - 50, (int) imageCaptureRegion.right + getPaddingRight(), bounds.bottom + 70 ); testRect = new Rect( straightenMoveRegion ); if ( straightenMoveRegion.contains( (int) x, (int) y ) ) { // if the move is within the straighten tool touch bounds if ( mPosX > imageCaptureRegion.right ) { mPosX = imageCaptureRegion.right; } if ( mPosX < imageCaptureRegion.left ) { mPosX = imageCaptureRegion.left; } mStraightenDrawable.setBounds( (int) ( mPosX - handleWidth ), (int) ( imageCaptureRegion.bottom - handleHeight ), (int) ( mPosX + handleWidth ), (int) ( imageCaptureRegion.bottom + handleHeight ) ); // now get the angle from the distance double midPoint = getCenter().x; double maxAngle = ( 45 * imageCaptureRegion.right ) / midPoint - 45; double tempAngle = ( 45 * mPosX ) / midPoint - 45; double angle = ( 45 * tempAngle ) / maxAngle; straighten( angle/2, straightenDuration ); } // Invalidate to request a redraw invalidate(); break; } case MotionEvent.ACTION_UP: { onTouchUp(); break; } } return true; } private double getRotationFromMatrix( Matrix matrix ) { float[] pts = { 0, 0, 0, -100 }; matrix.mapPoints( pts ); double angle = Point2D.angleBetweenPoints( pts[0], pts[1], pts[2], pts[3], 0 ); return -angle; } /** * Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable. * * @param adjustViewBounds * Whether to adjust the bounds of this view to presrve the original aspect ratio of the drawable * * @attr ref android.R.styleable#ImageView_adjustViewBounds */ public void setAdjustViewBounds( boolean adjustViewBounds ) { mAdjustViewBounds = adjustViewBounds; if ( adjustViewBounds ) { setScaleType( ScaleType.FIT_CENTER ); } } /** * An optional argument to supply a maximum width for this view. Only valid if {@link #setAdjustViewBounds(boolean)} has been set * to true. To set an image to be a maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set * adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width layout params to WRAP_CONTENT. * * <p> * Note that this view could be still smaller than 100 x 100 using this approach if the original image is small. To set an image * to a fixed size, specify that size in the layout params and then use {@link #setScaleType(android.widget.ImageView.ScaleType)} * to determine how to fit the image within the bounds. * </p> * * @param maxWidth * maximum width for this view * * @attr ref android.R.styleable#ImageView_maxWidth */ public void setMaxWidth( int maxWidth ) { mMaxWidth = maxWidth; } /** * An optional argument to supply a maximum height for this view. Only valid if {@link #setAdjustViewBounds(boolean)} has been * set to true. To set an image to be a maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set * adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width layout params to WRAP_CONTENT. * * <p> * Note that this view could be still smaller than 100 x 100 using this approach if the original image is small. To set an image * to a fixed size, specify that size in the layout params and then use {@link #setScaleType(android.widget.ImageView.ScaleType)} * to determine how to fit the image within the bounds. * </p> * * @param maxHeight * maximum height for this view * * @attr ref android.R.styleable#ImageView_maxHeight */ public void setMaxHeight( int maxHeight ) { mMaxHeight = maxHeight; } /** * Return the view's drawable, or null if no drawable has been assigned. * * @return the drawable */ public Drawable getDrawable() { return mDrawable; } /** * Sets a drawable as the content of this ImageView. * * <p class="note"> * This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using * * @param resId * the resource identifier of the the drawable {@link #setImageDrawable(android.graphics.drawable.Drawable)} or * {@link #setImageBitmap(android.graphics.Bitmap)} and {@link android.graphics.BitmapFactory} instead. * </p> * @attr ref android.R.styleable#ImageView_src */ public void setImageResource( int resId ) { if ( mUri != null || mResource != resId ) { updateDrawable( null ); mResource = resId; mUri = null; resolveUri(); requestLayout(); invalidate(); } } /** * Sets the content of this ImageView to the specified Uri. * * <p class="note"> * This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using * * @param uri * The Uri of an image {@link #setImageDrawable(android.graphics.drawable.Drawable)} or * {@link #setImageBitmap(android.graphics.Bitmap)} and {@link android.graphics.BitmapFactory} instead. * </p> */ public void setImageURI( Uri uri ) { if ( mResource != 0 || ( mUri != uri && ( uri == null || mUri == null || !uri.equals( mUri ) ) ) ) { updateDrawable( null ); mResource = 0; mUri = uri; resolveUri(); requestLayout(); invalidate(); } } /** * Sets a drawable as the content of this ImageView. * * @param drawable * The drawable to set */ public void setImageDrawable( Drawable drawable ) { if ( mDrawable != drawable ) { mResource = 0; mUri = null; int oldWidth = mDrawableWidth; int oldHeight = mDrawableHeight; updateDrawable( drawable ); if ( oldWidth != mDrawableWidth || oldHeight != mDrawableHeight ) { requestLayout(); } invalidate(); } } /** * Sets a Bitmap as the content of this ImageView. * * @param bm * The bitmap to set */ public void setImageBitmap( Bitmap bm ) { // if this is used frequently, may handle bitmaps explicitly // to reduce the intermediate drawable object setImageDrawable( new BitmapDrawable( getContext().getResources(), bm ) ); } /** * Sets the image state. * * @param state * the state * @param merge * the merge */ public void setImageState( int[] state, boolean merge ) { mState = state; mMergeState = merge; if ( mDrawable != null ) { refreshDrawableState(); resizeFromDrawable(); } } /* * (non-Javadoc) * * @see android.view.View#setSelected(boolean) */ @Override public void setSelected( boolean selected ) { super.setSelected( selected ); resizeFromDrawable(); } /** * Sets the image level, when it is constructed from a {@link android.graphics.drawable.LevelListDrawable}. * * @param level * The new level for the image. */ public void setImageLevel( int level ) { mLevel = level; if ( mDrawable != null ) { mDrawable.setLevel( level ); resizeFromDrawable(); } } /** * Options for scaling the bounds of an image to the bounds of this view. */ public enum ScaleType { /** * Scale using the image matrix when drawing. The image matrix can be set using {@link ImageView#setImageMatrix(Matrix)}. From * XML, use this syntax: <code>android:scaleType="matrix"</code>. */ MATRIX( 0 ), /** * Scale the image using {@link Matrix.ScaleToFit#FILL}. From XML, use this syntax: <code>android:scaleType="fitXY"</code>. */ FIT_XY( 1 ), /** * Scale the image using {@link Matrix.ScaleToFit#START}. From XML, use this syntax: <code>android:scaleType="fitStart"</code> * . */ FIT_START( 2 ), /** * Scale the image using {@link Matrix.ScaleToFit#CENTER}. From XML, use this syntax: * <code>android:scaleType="fitCenter"</code>. */ FIT_CENTER( 3 ), /** * Scale the image using {@link Matrix.ScaleToFit#END}. From XML, use this syntax: <code>android:scaleType="fitEnd"</code>. */ FIT_END( 4 ), /** * Center the image in the view, but perform no scaling. From XML, use this syntax: <code>android:scaleType="center"</code>. */ CENTER( 5 ), /** * Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will * be equal to or larger than the corresponding dimension of the view (minus padding). The image is then centered in the view. * From XML, use this syntax: <code>android:scaleType="centerCrop"</code>. */ CENTER_CROP( 6 ), /** * Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will * be equal to or less than the corresponding dimension of the view (minus padding). The image is then centered in the view. * From XML, use this syntax: <code>android:scaleType="centerInside"</code>. */ CENTER_INSIDE( 7 ); /** * Instantiates a new scale type. * * @param ni * the ni */ ScaleType( int ni ) { nativeInt = ni; } /** The native int. */ final int nativeInt; } /** * Controls how the image should be resized or moved to match the size of this ImageView. * * @param scaleType * The desired scaling mode. * * @attr ref android.R.styleable#ImageView_scaleType */ public void setScaleType( ScaleType scaleType ) { if ( scaleType == null ) { throw new NullPointerException(); } if ( mScaleType != scaleType ) { mScaleType = scaleType; setWillNotCacheDrawing( mScaleType == ScaleType.CENTER ); requestLayout(); invalidate(); } } /** * Return the current scale type in use by this ImageView. * * @return the scale type * @see ImageView.ScaleType * @attr ref android.R.styleable#ImageView_scaleType */ public ScaleType getScaleType() { return mScaleType; } /** * Return the view's optional matrix. This is applied to the view's drawable when it is drawn. If there is not matrix, this * method will return null. Do not change this matrix in place. If you want a different matrix applied to the drawable, be sure * to call setImageMatrix(). * * @return the image matrix */ public Matrix getImageMatrix() { return mMatrix; } /** * Sets the image matrix. * * @param matrix * the new image matrix */ public void setImageMatrix( Matrix matrix ) { // collaps null and identity to just null if ( matrix != null && matrix.isIdentity() ) { matrix = null; } // don't invalidate unless we're actually changing our matrix if ( matrix == null && !mMatrix.isIdentity() || matrix != null && !mMatrix.equals( matrix ) ) { mMatrix.set( matrix ); configureBounds(); invalidate(); } } /** * Resolve uri. */ private void resolveUri() { if ( mDrawable != null ) { return; } Resources rsrc = getResources(); if ( rsrc == null ) { return; } Drawable d = null; if ( mResource != 0 ) { try { d = rsrc.getDrawable( mResource ); } catch ( Exception e ) { Log.w( LOG_TAG, "Unable to find resource: " + mResource, e ); // Don't try again. mUri = null; } } else if ( mUri != null ) { String scheme = mUri.getScheme(); if ( ContentResolver.SCHEME_ANDROID_RESOURCE.equals( scheme ) ) { } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) || ContentResolver.SCHEME_FILE.equals( scheme ) ) { try { d = Drawable.createFromStream( getContext().getContentResolver().openInputStream( mUri ), null ); } catch ( Exception e ) { Log.w( LOG_TAG, "Unable to open content: " + mUri, e ); } } else { d = Drawable.createFromPath( mUri.toString() ); } if ( d == null ) { System.out.println( "resolveUri failed on bad bitmap uri: " + mUri ); // Don't try again. mUri = null; } } else { return; } updateDrawable( d ); } /* * (non-Javadoc) * * @see android.view.View#onCreateDrawableState(int) */ @Override public int[] onCreateDrawableState( int extraSpace ) { if ( mState == null ) { return super.onCreateDrawableState( extraSpace ); } else if ( !mMergeState ) { return mState; } else { return mergeDrawableStates( super.onCreateDrawableState( extraSpace + mState.length ), mState ); } } /** * Update drawable. * * @param d * the d */ private void updateDrawable( Drawable d ) { if ( mDrawable != null ) { mDrawable.setCallback( null ); unscheduleDrawable( mDrawable ); } mDrawable = d; if ( d != null ) { d.setCallback( this ); if ( d.isStateful() ) { d.setState( getDrawableState() ); } d.setLevel( mLevel ); mDrawableWidth = d.getIntrinsicWidth(); mDrawableHeight = d.getIntrinsicHeight(); applyColorMod(); configureBounds(); } else { mDrawableWidth = mDrawableHeight = -1; } } /** * Resize from drawable. */ private void resizeFromDrawable() { Drawable d = mDrawable; if ( d != null ) { int w = d.getIntrinsicWidth(); if ( w < 0 ) w = mDrawableWidth; int h = d.getIntrinsicHeight(); if ( h < 0 ) h = mDrawableHeight; if ( w != mDrawableWidth || h != mDrawableHeight ) { mDrawableWidth = w; mDrawableHeight = h; requestLayout(); } } } /** The Constant sS2FArray. */ private static final Matrix.ScaleToFit[] sS2FArray = { Matrix.ScaleToFit.FILL, Matrix.ScaleToFit.START, Matrix.ScaleToFit.CENTER, Matrix.ScaleToFit.END }; /** * Scale type to scale to fit. * * @param st * the st * @return the matrix. scale to fit */ private static Matrix.ScaleToFit scaleTypeToScaleToFit( ScaleType st ) { // ScaleToFit enum to their corresponding Matrix.ScaleToFit values return sS2FArray[st.nativeInt - 1]; } /* * (non-Javadoc) * * @see android.view.View#onLayout(boolean, int, int, int, int) */ @Override protected void onLayout( boolean changed, int left, int top, int right, int bottom ) { super.onLayout( changed, left, top, right, bottom ); if ( changed ) { mHaveFrame = true; double oldRotation = mRotation; boolean flip_h = getHorizontalFlip(); boolean flip_v = getVerticalFlip(); configureBounds(); if ( flip_h || flip_v ) { flip( flip_h, flip_v ); } if ( oldRotation != 0 ) { setImageRotation( oldRotation, false ); mRotation = oldRotation; } invalidate(); } } /* * (non-Javadoc) * * @see android.view.View#onMeasure(int, int) */ @Override protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec ) { resolveUri(); int w; int h; // Desired aspect ratio of the view's contents (not including padding) float desiredAspect = 0.0f; // We are allowed to change the view's width boolean resizeWidth = false; // We are allowed to change the view's height boolean resizeHeight = false; final int widthSpecMode = MeasureSpec.getMode( widthMeasureSpec ); final int heightSpecMode = MeasureSpec.getMode( heightMeasureSpec ); if ( mDrawable == null ) { // If no drawable, its intrinsic size is 0. mDrawableWidth = -1; mDrawableHeight = -1; w = h = 0; } else { w = mDrawableWidth; h = mDrawableHeight; if ( w <= 0 ) w = 1; if ( h <= 0 ) h = 1; if ( mDrawableHeight > mDrawableWidth ) { portrait = true; } orientation = getResources().getConfiguration().orientation; // We are supposed to adjust view bounds to match the aspect // ratio of our drawable. See if that is possible. if ( mAdjustViewBounds ) { resizeWidth = widthSpecMode != MeasureSpec.EXACTLY; resizeHeight = heightSpecMode != MeasureSpec.EXACTLY; desiredAspect = (float) w / (float) h; } } int pleft = getPaddingLeft(); int pright = getPaddingRight(); int ptop = getPaddingTop(); int pbottom = getPaddingBottom(); int widthSize; int heightSize; if ( resizeWidth || resizeHeight ) { /* * If we get here, it means we want to resize to match the drawables aspect ratio, and we have the freedom to change at * least one dimension. */ // Get the max possible width given our constraints widthSize = resolveAdjustedSize( w + pleft + pright, mMaxWidth, widthMeasureSpec ); // Get the max possible height given our constraints heightSize = resolveAdjustedSize( h + ptop + pbottom, mMaxHeight, heightMeasureSpec ); if ( desiredAspect != 0.0f ) { // See what our actual aspect ratio is float actualAspect = (float) ( widthSize - pleft - pright ) / ( heightSize - ptop - pbottom ); if ( Math.abs( actualAspect - desiredAspect ) > 0.0000001 ) { boolean done = false; // Try adjusting width to be proportional to height if ( resizeWidth ) { int newWidth = (int) ( desiredAspect * ( heightSize - ptop - pbottom ) ) + pleft + pright; if ( newWidth <= widthSize ) { widthSize = newWidth; done = true; } } // Try adjusting height to be proportional to width if ( !done && resizeHeight ) { int newHeight = (int) ( ( widthSize - pleft - pright ) / desiredAspect ) + ptop + pbottom; if ( newHeight <= heightSize ) { heightSize = newHeight; } } } } } else { /* * We are either don't want to preserve the drawables aspect ratio, or we are not allowed to change view dimensions. Just * measure in the normal way. */ w += pleft + pright; h += ptop + pbottom; w = Math.max( w, getSuggestedMinimumWidth() ); h = Math.max( h, getSuggestedMinimumHeight() ); widthSize = resolveSize( w, widthMeasureSpec ); heightSize = resolveSize( h, heightMeasureSpec ); } setMeasuredDimension( widthSize, heightSize ); // drawResource(); } /** * Resolve adjusted size. * * @param desiredSize * the desired size * @param maxSize * the max size * @param measureSpec * the measure spec * @return the int */ private int resolveAdjustedSize( int desiredSize, int maxSize, int measureSpec ) { int result = desiredSize; int specMode = MeasureSpec.getMode( measureSpec ); int specSize = MeasureSpec.getSize( measureSpec ); switch ( specMode ) { case MeasureSpec.UNSPECIFIED: /* * Parent says we can be as big as we want. Just don't be larger than max size imposed on ourselves. */ result = Math.min( desiredSize, maxSize ); break; case MeasureSpec.AT_MOST: // Parent says we can be as big as we want, up to specSize. // Don't be larger than specSize, and don't be larger than // the max size imposed on ourselves. result = Math.min( Math.min( desiredSize, specSize ), maxSize ); break; case MeasureSpec.EXACTLY: // No choice. Do what we are told. result = specSize; break; } return result; } /** * Configure bounds. */ private void configureBounds() { if ( mDrawable == null || !mHaveFrame ) { return; } int dwidth = mDrawableWidth; int dheight = mDrawableHeight; int vwidth = getWidth() - getPaddingLeft() - getPaddingRight(); int vheight = getHeight() - getPaddingTop() - getPaddingBottom(); boolean fits = ( dwidth < 0 || vwidth == dwidth ) && ( dheight < 0 || vheight == dheight ); if ( dwidth <= 0 || dheight <= 0 || ScaleType.FIT_XY == mScaleType ) { /* * If the drawable has no intrinsic size, or we're told to scaletofit, then we just fill our entire view. */ mDrawable.setBounds( 0, 0, vwidth, vheight ); mDrawMatrix = null; } else { // We need to do the scaling ourself, so have the drawable // use its native size. mDrawable.setBounds( 0, 0, dwidth, dheight ); if ( ScaleType.MATRIX == mScaleType ) { // Use the specified matrix as-is. if ( mMatrix.isIdentity() ) { mDrawMatrix = null; } else { mDrawMatrix = mMatrix; } } else if ( fits ) { // The bitmap fits exactly, no transform needed. mDrawMatrix = null; } else if ( ScaleType.CENTER == mScaleType ) { // Center bitmap in view, no scaling. mDrawMatrix = mMatrix; mDrawMatrix.setTranslate( (int) ( ( vwidth - dwidth ) * 0.5f + 0.5f ), (int) ( ( vheight - dheight ) * 0.5f + 0.5f ) ); } else if ( ScaleType.CENTER_CROP == mScaleType ) { mDrawMatrix = mMatrix; float scale; float dx = 0, dy = 0; if ( dwidth * vheight > vwidth * dheight ) { scale = (float) vheight / (float) dheight; dx = ( vwidth - dwidth * scale ) * 0.5f; } else { scale = (float) vwidth / (float) dwidth; dy = ( vheight - dheight * scale ) * 0.5f; } mDrawMatrix.setScale( scale, scale ); mDrawMatrix.postTranslate( (int) ( dx + 0.5f ), (int) ( dy + 0.5f ) ); } else if ( ScaleType.CENTER_INSIDE == mScaleType ) { mDrawMatrix = mMatrix; float scale; float dx; float dy; if ( dwidth <= vwidth && dheight <= vheight ) { scale = 1.0f; } else { scale = Math.min( (float) vwidth / (float) dwidth, (float) vheight / (float) dheight ); } dx = (int) ( ( vwidth - dwidth * scale ) * 0.5f + 0.5f ); dy = (int) ( ( vheight - dheight * scale ) * 0.5f + 0.5f ); mDrawMatrix.setScale( scale, scale ); mDrawMatrix.postTranslate( dx, dy ); } else { // Generate the required transform. mTempSrc.set( 0, 0, dwidth, dheight ); mTempDst.set( 0, 0, vwidth, vheight ); mDrawMatrix = mMatrix; mDrawMatrix.setRectToRect( mTempSrc, mTempDst, scaleTypeToScaleToFit( mScaleType ) ); mCurrentScale = getMatrixScale( mDrawMatrix )[0]; Matrix tempMatrix = new Matrix( mMatrix ); RectF src = new RectF(); RectF dst = new RectF(); src.set( 0, 0, dheight, dwidth ); dst.set( 0, 0, vwidth, vheight ); tempMatrix.setRectToRect( src, dst, scaleTypeToScaleToFit( mScaleType ) ); tempMatrix = new Matrix( mDrawMatrix ); tempMatrix.invert( tempMatrix ); float invertScale = getMatrixScale( tempMatrix )[0]; mDrawMatrix.postScale( invertScale, invertScale, vwidth / 2, vheight / 2 ); mRotateMatrix.reset(); mStraightenMatrix.reset(); mFlipMatrix.reset(); mFlipType = FlipType.FLIP_NONE.nativeInt; mRotation = 0; mRotateMatrix.postScale( mCurrentScale, mCurrentScale, vwidth / 2, vheight / 2 ); // mStraightenMatrix.postScale( mCurrentScale, mCurrentScale, vwidth / 2, vheight / 2 ); mDrawRect = getImageRect(); mCenter = getCenter(); } } } /* * (non-Javadoc) * * @see android.view.View#drawableStateChanged() */ @Override protected void drawableStateChanged() { super.drawableStateChanged(); Drawable d = mDrawable; if ( d != null && d.isStateful() ) { d.setState( getDrawableState() ); } } @Override protected void onDraw( Canvas canvas ) { super.onDraw( canvas ); if ( mDrawable == null ) { return; // couldn't resolve the URI } if ( mDrawableWidth == 0 || mDrawableHeight == 0 ) { return; // nothing to draw (empty bounds) } final int mPaddingTop = getPaddingTop(); final int mPaddingLeft = getPaddingLeft(); final int mPaddingBottom = getPaddingBottom(); final int mPaddingRight = getPaddingRight(); if ( mDrawMatrix == null && mPaddingTop == 0 && mPaddingLeft == 0 ) { mDrawable.draw( canvas ); } else { int saveCount = canvas.getSaveCount(); canvas.save(); if ( mCropToPadding ) { final int scrollX = getScrollX(); final int scrollY = getScrollY(); canvas.clipRect( scrollX + mPaddingLeft, scrollY + mPaddingTop, scrollX + getRight() - getLeft() - mPaddingRight, scrollY + getBottom() - getTop() - mPaddingBottom ); } canvas.translate( mPaddingLeft, mPaddingTop ); if ( mFlipMatrix != null ) canvas.concat( mFlipMatrix ); if ( mRotateMatrix != null ) canvas.concat( mRotateMatrix ); // if ( mStraightenMatrix != null ) canvas.concat( mStraightenMatrix ); if ( mDrawMatrix != null ) canvas.concat( mDrawMatrix ); mDrawable.draw( canvas ); canvas.restoreToCount( saveCount ); if ( mEnableFreeRotate ) { mDrawRect = getImageRect(); getDrawingRect( mViewDrawRect ); mClipPath.reset(); mInversePath.reset(); mLinesPath.reset(); float[] points = new float[] { mDrawRect.left, mDrawRect.top, mDrawRect.right, mDrawRect.top, mDrawRect.right, mDrawRect.bottom, mDrawRect.left, mDrawRect.bottom }; mTempMatrix.set( mDrawMatrix ); mTempMatrix.postConcat( mRotateMatrix ); mTempMatrix.postConcat( mStraightenMatrix ); mTempMatrix.mapPoints( points ); mViewInvertRect.set( mViewDrawRect ); mViewInvertRect.top -= mPaddingLeft; mViewInvertRect.left -= mPaddingTop; mInversePath.addRect( mViewInvertRect, Path.Direction.CW ); double sx = Point2D.distance( points[2], points[3], points[0], points[1] ); double sy = Point2D.distance( points[6], points[7], points[0], points[1] ); double angle = getAngle90( mRotation ); RectF rect; if ( initStraighten ) { if ( angle < 45 ) { rect = crop( (float) sx, (float) sy, angle, mDrawableWidth, mDrawableHeight, mCenter, null ); } else { rect = crop( (float) sx, (float) sy, angle, mDrawableHeight, mDrawableWidth, mCenter, null ); } float colStep = (float) rect.height() / grid_cols; float rowStep = (float) rect.width() / grid_rows; for ( int i = 1; i < grid_cols; i++ ) { // mLinesPath.addRect( (int)rect.left, (int)(rect.top + colStep * i), (int)rect.right, (int)(rect.top + colStep * // i) + 3, Path.Direction.CW ); mLinesPath.moveTo( (int) rect.left, (int) ( rect.top + colStep * i ) ); mLinesPath.lineTo( (int) rect.right, (int) ( rect.top + colStep * i ) ); } for ( int i = 1; i < grid_rows; i++ ) { // mLinesPath.addRect( (int)(rect.left + rowStep * i), (int)rect.top, (int)(rect.left + rowStep * i) + 3, // (int)rect.bottom, Path.Direction.CW ); mLinesPath.moveTo( (int) ( rect.left + rowStep * i ), (int) rect.top ); mLinesPath.lineTo( (int) ( rect.left + rowStep * i ), (int) rect.bottom ); } imageCaptureRegion = rect; PointF center = getCenter(); mStraightenDrawable.setBounds( (int) ( center.x - handleWidth ), (int) ( imageCaptureRegion.bottom - handleHeight ), (int) ( center.x + handleWidth ), (int) ( imageCaptureRegion.bottom + handleHeight ) ); mPosX = center.x; initStraighten = false; } else { rect = imageCaptureRegion; float colStep = (float) rect.height() / grid_cols; float rowStep = (float) rect.width() / grid_rows; for ( int i = 1; i < grid_cols; i++ ) { // mLinesPath.addRect( (int)rect.left, (int)(rect.top + colStep * i), (int)rect.right, (int)(rect.top + colStep * // i) + 3, Path.Direction.CW ); mLinesPath.moveTo( (int) rect.left, (int) ( rect.top + colStep * i ) ); mLinesPath.lineTo( (int) rect.right, (int) ( rect.top + colStep * i ) ); } for ( int i = 1; i < grid_rows; i++ ) { // mLinesPath.addRect( (int)(rect.left + rowStep * i), (int)rect.top, (int)(rect.left + rowStep * i) + 3, // (int)rect.bottom, Path.Direction.CW ); mLinesPath.moveTo( (int) ( rect.left + rowStep * i ), (int) rect.top ); mLinesPath.lineTo( (int) ( rect.left + rowStep * i ), (int) rect.bottom ); } } mClipPath.addRect( rect, Path.Direction.CW ); mInversePath.addRect( rect, Path.Direction.CCW ); saveCount = canvas.save(); canvas.translate( mPaddingLeft, mPaddingTop ); canvas.drawPath( mInversePath, mOutlineFill ); // canvas.drawPath( mLinesPath, mLinesPaintShadow ); canvas.drawPath( mLinesPath, mLinesPaint ); canvas.drawPath( mClipPath, mOutlinePaint ); // if ( mFlipMatrix != null ) canvas.concat( mFlipMatrix ); // if ( mRotateMatrix != null ) canvas.concat( mRotateMatrix ); // if ( mDrawMatrix != null ) canvas.concat( mDrawMatrix ); // mResizeDrawable.setBounds( (int) mDrawRect.right - handleWidth, (int) mDrawRect.bottom - handleHeight, (int) // mDrawRect.right + handleWidth, (int) mDrawRect.bottom + handleHeight ); // mResizeDrawable.draw( canvas ); canvas.restoreToCount( saveCount ); saveCount = canvas.save(); canvas.translate( mPaddingLeft, mPaddingTop ); // mResizeDrawable.setBounds( (int)(points[4] - handleWidth), (int)(points[5] - handleHeight), (int)(points[4] + // handleWidth), (int)(points[5] + handleHeight) ); // mResizeDrawable.draw( canvas ); mStraightenDrawable.draw( canvas ); canvas.restoreToCount( saveCount ); } /** * if(intersectPoints){ //intersectPaint.setColor(Color.YELLOW); //canvas.drawCircle(intersectx, intersecty, 10, * intersectPaint); //canvas.drawLine(trueRect.left + getPaddingLeft(), trueRect.bottom + getPaddingBottom(), * trueRect.right + getPaddingRight(), trueRect.bottom+ getPaddingBottom(), intersectPaint); //canvas.drawRect(testRect, * intersectPaint); } */ } } float ax = 0; float ay = 0; float bx = 0; float by = 0; float cx = 0; float cy = 0; float dx = 0; float dy = 0; float intersectx = 0; float intersecty = 0; Paint intersectPaint = new Paint(); RectF imageCaptureRegion = null; boolean initStraighten = true; Matrix rotateCopy; boolean firstDraw = true; Handler mFadeHandler = new Handler(); boolean mFadeHandlerStarted; public void setInitStraighten( boolean value ) { initStraighten = value; } protected void fadeinGrid( final int durationMs ) { final long startTime = System.currentTimeMillis(); final float startAlpha = mLinesPaint.getAlpha(); final float startAlphaShadow = mLinesPaintShadow.getAlpha(); final Linear easing = new Linear(); mFadeHandler.post( new Runnable() { @Override public void run() { long now = System.currentTimeMillis(); float currentMs = Math.min( durationMs, now - startTime ); float new_alpha_lines = (float) easing.easeNone( currentMs, startAlpha, mLinesAlpha, durationMs ); float new_alpha_lines_shadow = (float) easing.easeNone( currentMs, startAlphaShadow, mLinesShadowAlpha, durationMs ); mLinesPaint.setAlpha( (int) new_alpha_lines ); mLinesPaintShadow.setAlpha( (int) new_alpha_lines_shadow ); invalidate(); if ( currentMs < durationMs ) { mFadeHandler.post( this ); } else { mLinesPaint.setAlpha( mLinesAlpha ); mLinesPaintShadow.setAlpha( mLinesShadowAlpha ); invalidate(); } } } ); } protected void fadeoutGrid( final int durationMs ) { final long startTime = System.currentTimeMillis(); final float startAlpha = mLinesPaint.getAlpha(); final float startAlphaShadow = mLinesPaintShadow.getAlpha(); final Linear easing = new Linear(); mFadeHandler.post( new Runnable() { @Override public void run() { long now = System.currentTimeMillis(); float currentMs = Math.min( durationMs, now - startTime ); float new_alpha_lines = (float) easing.easeNone( currentMs, 0, startAlpha, durationMs ); float new_alpha_lines_shadow = (float) easing.easeNone( currentMs, 0, startAlphaShadow, durationMs ); mLinesPaint.setAlpha( (int) startAlpha - (int) new_alpha_lines ); mLinesPaintShadow.setAlpha( (int) startAlphaShadow - (int) new_alpha_lines_shadow ); invalidate(); if ( currentMs < durationMs ) { mFadeHandler.post( this ); } else { mLinesPaint.setAlpha( 0 ); mLinesPaintShadow.setAlpha( 0 ); invalidate(); } } } ); } protected void fadeinOutlines( final int durationMs ) { if ( mFadeHandlerStarted ) return; mFadeHandlerStarted = true; final long startTime = System.currentTimeMillis(); final Linear easing = new Linear(); mFadeHandler.post( new Runnable() { @Override public void run() { long now = System.currentTimeMillis(); float currentMs = Math.min( durationMs, now - startTime ); float new_alpha_fill = (float) easing.easeNone( currentMs, 0, mOutlineFillAlpha, durationMs ); float new_alpha_paint = (float) easing.easeNone( currentMs, 0, mOutlinePaintAlpha, durationMs ); float new_alpha_lines = (float) easing.easeNone( currentMs, 0, mLinesAlpha, durationMs ); float new_alpha_lines_shadow = (float) easing.easeNone( currentMs, 0, mLinesShadowAlpha, durationMs ); mOutlineFill.setAlpha( (int) new_alpha_fill ); mOutlinePaint.setAlpha( (int) new_alpha_paint ); mLinesPaint.setAlpha( (int) new_alpha_lines ); mLinesPaintShadow.setAlpha( (int) new_alpha_lines_shadow ); invalidate(); if ( currentMs < durationMs ) { mFadeHandler.post( this ); } else { mOutlineFill.setAlpha( mOutlineFillAlpha ); mOutlinePaint.setAlpha( mOutlinePaintAlpha ); mLinesPaint.setAlpha( mLinesAlpha ); mLinesPaintShadow.setAlpha( mLinesShadowAlpha ); invalidate(); } } } ); } protected void fadeoutOutlines( final int durationMs ) { final long startTime = System.currentTimeMillis(); final Linear easing = new Linear(); final int alpha1 = mOutlineFill.getAlpha(); final int alpha2 = mOutlinePaint.getAlpha(); final int alpha3 = mLinesPaint.getAlpha(); final int alpha4 = mLinesPaintShadow.getAlpha(); mFadeHandler.post( new Runnable() { @Override public void run() { long now = System.currentTimeMillis(); float currentMs = Math.min( durationMs, now - startTime ); float new_alpha_fill = (float) easing.easeNone( currentMs, alpha1, 0, durationMs ); float new_alpha_paint = (float) easing.easeNone( currentMs, alpha2, 0, durationMs ); float new_alpha_lines = (float) easing.easeNone( currentMs, alpha3, 0, durationMs ); float new_alpha_lines_shadow = (float) easing.easeNone( currentMs, alpha4, 0, durationMs ); mOutlineFill.setAlpha( (int) new_alpha_fill ); mOutlinePaint.setAlpha( (int) new_alpha_paint ); mLinesPaint.setAlpha( (int) new_alpha_lines ); mLinesPaintShadow.setAlpha( (int) new_alpha_lines_shadow ); invalidate(); if ( currentMs < durationMs ) { mFadeHandler.post( this ); } else { hideOutlines(); } } } ); } protected void hideOutlines() { mFadeHandlerStarted = false; mOutlineFill.setAlpha( 0 ); mOutlinePaint.setAlpha( 0 ); mLinesPaint.setAlpha( 0 ); mLinesPaintShadow.setAlpha( 0 ); invalidate(); } static double getAngle90( double value ) { double rotation = Point2D.angle360( value ); double angle = rotation; if ( rotation >= 270 ) { angle = 360 - rotation; } else if ( rotation >= 180 ) { angle = rotation - 180; } else if ( rotation > 90 ) { angle = 180 - rotation; } return angle; } RectF crop( float originalWidth, float originalHeight, double angle, float targetWidth, float targetHeight, PointF center, Canvas canvas ) { double radians = Point2D.radians( angle ); PointF[] original = new PointF[] { new PointF( 0, 0 ), new PointF( originalWidth, 0 ), new PointF( originalWidth, originalHeight ), new PointF( 0, originalHeight ) }; Point2D.translate( original, -originalWidth / 2, -originalHeight / 2 ); PointF[] rotated = new PointF[original.length]; System.arraycopy( original, 0, rotated, 0, original.length ); Point2D.rotate( rotated, radians ); if ( angle >= 0 ) { PointF[] ray = new PointF[] { new PointF( 0, 0 ), new PointF( -targetWidth / 2, -targetHeight / 2 ) }; PointF[] bound = new PointF[] { rotated[0], rotated[3] }; // Top Left intersection. PointF intersectTL = Point2D.intersection( ray, bound ); PointF[] ray2 = new PointF[] { new PointF( 0, 0 ), new PointF( targetWidth / 2, -targetHeight / 2 ) }; PointF[] bound2 = new PointF[] { rotated[0], rotated[1] }; // Top Right intersection. PointF intersectTR = Point2D.intersection( ray2, bound2 ); // Pick the intersection closest to the origin PointF intersect = new PointF( Math.max( intersectTL.x, -intersectTR.x ), Math.max( intersectTL.y, intersectTR.y ) ); RectF newRect = new RectF( intersect.x, intersect.y, -intersect.x, -intersect.y ); newRect.offset( center.x, center.y ); if ( canvas != null ) { // debug Point2D.translate( rotated, center.x, center.y ); Point2D.translate( ray, center.x, center.y ); Point2D.translate( ray2, center.x, center.y ); Paint paint = new Paint( Paint.ANTI_ALIAS_FLAG ); paint.setColor( 0x66FFFF00 ); paint.setStyle( Paint.Style.STROKE ); paint.setStrokeWidth( 2 ); // draw rotated drawRect( rotated, canvas, paint ); paint.setColor( Color.GREEN ); drawLine( ray, canvas, paint ); paint.setColor( Color.BLUE ); drawLine( ray2, canvas, paint ); paint.setColor( Color.CYAN ); drawLine( bound, canvas, paint ); paint.setColor( Color.WHITE ); drawLine( bound2, canvas, paint ); paint.setColor( Color.GRAY ); canvas.drawRect( newRect, paint ); } return newRect; } else { throw new IllegalArgumentException( "angle cannot be < 0" ); } } void drawLine( PointF[] line, Canvas canvas, Paint paint ) { canvas.drawLine( line[0].x, line[0].y, line[1].x, line[1].y, paint ); } void drawRect( PointF[] rect, Canvas canvas, Paint paint ) { // draw rotated Path path = new Path(); path.moveTo( rect[0].x, rect[0].y ); path.lineTo( rect[1].x, rect[1].y ); path.lineTo( rect[2].x, rect[2].y ); path.lineTo( rect[3].x, rect[3].y ); path.lineTo( rect[0].x, rect[0].y ); canvas.drawPath( path, paint ); } /** * <p> * Return the offset of the widget's text baseline from the widget's top boundary. * </p> * * @return the offset of the baseline within the widget's bounds or -1 if baseline alignment is not supported. */ @Override public int getBaseline() { if ( mBaselineAlignBottom ) { return getMeasuredHeight(); } else { return mBaseline; } } /** * <p> * Set the offset of the widget's text baseline from the widget's top boundary. This value is overridden by the * * @param baseline * The baseline to use, or -1 if none is to be provided. {@link #setBaselineAlignBottom(boolean)} property. * </p> * @see #setBaseline(int) * @attr ref android.R.styleable#ImageView_baseline */ public void setBaseline( int baseline ) { if ( mBaseline != baseline ) { mBaseline = baseline; requestLayout(); } } /** * Set whether to set the baseline of this view to the bottom of the view. Setting this value overrides any calls to setBaseline. * * @param aligned * If true, the image view will be baseline aligned with based on its bottom edge. * * @attr ref android.R.styleable#ImageView_baselineAlignBottom */ public void setBaselineAlignBottom( boolean aligned ) { if ( mBaselineAlignBottom != aligned ) { mBaselineAlignBottom = aligned; requestLayout(); } } /** * Return whether this view's baseline will be considered the bottom of the view. * * @return the baseline align bottom * @see #setBaselineAlignBottom(boolean) */ public boolean getBaselineAlignBottom() { return mBaselineAlignBottom; } /** * Set a tinting option for the image. * * @param color * Color tint to apply. * @param mode * How to apply the color. The standard mode is {@link PorterDuff.Mode#SRC_ATOP} * * @attr ref android.R.styleable#ImageView_tint */ public final void setColorFilter( int color, PorterDuff.Mode mode ) { setColorFilter( new PorterDuffColorFilter( color, mode ) ); } /** * Set a tinting option for the image. Assumes {@link PorterDuff.Mode#SRC_ATOP} blending mode. * * @param color * Color tint to apply. * @attr ref android.R.styleable#ImageView_tint */ public final void setColorFilter( int color ) { setColorFilter( color, PorterDuff.Mode.SRC_ATOP ); } /** * Clear color filter. */ public final void clearColorFilter() { setColorFilter( null ); } /** * Apply an arbitrary colorfilter to the image. * * @param cf * the colorfilter to apply (may be null) */ public void setColorFilter( ColorFilter cf ) { if ( mColorFilter != cf ) { mColorFilter = cf; mColorMod = true; applyColorMod(); invalidate(); } } /** * Sets the alpha. * * @param alpha * the new alpha */ public void setAlpha( int alpha ) { alpha &= 0xFF; // keep it legal if ( mAlpha != alpha ) { mAlpha = alpha; mColorMod = true; applyColorMod(); invalidate(); } } /** * Apply color mod. */ private void applyColorMod() { // Only mutate and apply when modifications have occurred. This should // not reset the mColorMod flag, since these filters need to be // re-applied if the Drawable is changed. if ( mDrawable != null && mColorMod ) { mDrawable = mDrawable.mutate(); mDrawable.setColorFilter( mColorFilter ); mDrawable.setAlpha( mAlpha * mViewAlphaScale >> 8 ); } } /** The m handler. */ protected Handler mHandler = new Handler(); /** The m rotation. */ protected double mRotation = 0; /** The m current scale. */ protected float mCurrentScale = 0; /** The m running. */ protected boolean mRunning = false; /** * Rotate90. * * @param cw * the cw * @param durationMs * the duration ms */ public void rotate90( boolean cw, int durationMs ) { final double destRotation = ( cw ? 90 : -90 ); rotateBy( destRotation, durationMs ); hideOutlines(); portrait = !portrait; } public boolean getStraightenStarted() { return straightenStarted; } /** * Rotate to. * * @param cw * the cw * @param durationMs * the duration ms */ protected void rotateBy( final double deltaRotation, final int durationMs ) { if ( mRunning ) { return; } mRunning = true; final long startTime = System.currentTimeMillis(); final double destRotation = mRotation + deltaRotation; final double srcRotation = mRotation; setImageRotation( mRotation, false ); invalidate(); mHandler.post( new Runnable() { @SuppressWarnings("unused") float old_scale = 0; @SuppressWarnings("unused") float old_rotation = 0; @Override public void run() { long now = System.currentTimeMillis(); float currentMs = Math.min( durationMs, now - startTime ); float new_rotation = (float) mEasing.easeInOut( currentMs, 0, deltaRotation, durationMs ); mRotation = Point2D.angle360( srcRotation + new_rotation ); setImageRotation( mRotation, false ); old_rotation = new_rotation; initStraighten = true; invalidate(); if ( currentMs < durationMs ) { mHandler.post( this ); } else { mRotation = Point2D.angle360( destRotation ); setImageRotation( mRotation, true ); initStraighten = true; invalidate(); printDetails(); mRunning = false; if ( isReset ) { onReset(); } } } } ); if ( straightenStarted && !isReset ) { initStraighten = true; resetStraighten(); invalidate(); } } private void resetStraighten() { mStraightenMatrix.reset(); straightenStarted = false; previousStraightenAngle = 0; prevGrowth = 1; prevGrowthAngle = 0; currentNewPosition = 0; testStraighten = true; currentGrowth = 0; previousAngle = 0; } /** * Prints the details. */ public void printDetails() { Log.i( LOG_TAG, "details:" ); Log.d( LOG_TAG, " flip horizontal: " + ( ( mFlipType & FlipType.FLIP_HORIZONTAL.nativeInt ) == FlipType.FLIP_HORIZONTAL.nativeInt ) ); Log.d( LOG_TAG, " flip vertical: " + ( ( mFlipType & FlipType.FLIP_VERTICAL.nativeInt ) == FlipType.FLIP_VERTICAL.nativeInt ) ); Log.d( LOG_TAG, " rotation: " + mRotation ); Log.d( LOG_TAG, "--------" ); } /** * Flip. * * @param horizontal * the horizontal * @param durationMs * the duration ms */ public void flip( boolean horizontal, int durationMs ) { flipTo( horizontal, durationMs ); hideOutlines(); } /** The m camera enabled. */ private boolean mCameraEnabled; /** * Sets the camera enabled. * * @param value * the new camera enabled */ public void setCameraEnabled( final boolean value ) { if ( android.os.Build.VERSION.SDK_INT >= 14 && value ) mCameraEnabled = value; else mCameraEnabled = false; } /** * Flip to. * * @param horizontal * the horizontal * @param durationMs * the duration ms */ protected void flipTo( final boolean horizontal, final int durationMs ) { if ( mRunning ) { return; } mRunning = true; final long startTime = System.currentTimeMillis(); final int vwidth = getWidth() - getPaddingLeft() - getPaddingRight(); final int vheight = getHeight() - getPaddingTop() - getPaddingBottom(); final float centerx = vwidth / 2; final float centery = vheight / 2; final Camera camera = new Camera(); mHandler.post( new Runnable() { @Override public void run() { long now = System.currentTimeMillis(); double currentMs = Math.min( durationMs, now - startTime ); if ( mCameraEnabled ) { float degrees = (float) ( 0 + ( ( -180 - 0 ) * ( currentMs / durationMs ) ) ); camera.save(); if ( horizontal ) { camera.rotateY( degrees ); } else { camera.rotateX( degrees ); } camera.getMatrix( mFlipMatrix ); camera.restore(); mFlipMatrix.preTranslate( -centerx, -centery ); mFlipMatrix.postTranslate( centerx, centery ); } else { double new_scale = mEasing.easeInOut( currentMs, 1, -2, durationMs ); if ( horizontal ) mFlipMatrix.setScale( (float) new_scale, 1, centerx, centery ); else mFlipMatrix.setScale( 1, (float) new_scale, centerx, centery ); } invalidate(); if ( currentMs < durationMs ) { mHandler.post( this ); } else { if ( horizontal ) { mFlipType ^= FlipType.FLIP_HORIZONTAL.nativeInt; mDrawMatrix.postScale( -1, 1, centerx, centery ); } else { mFlipType ^= FlipType.FLIP_VERTICAL.nativeInt; mDrawMatrix.postScale( 1, -1, centerx, centery ); } mRotateMatrix.postRotate( (float) ( -mRotation * 2 ), centerx, centery ); mRotation = Point2D.angle360( getRotationFromMatrix( mRotateMatrix ) ); mFlipMatrix.reset(); invalidate(); printDetails(); mRunning = false; if ( isReset ) { onReset(); } } } } ); if ( straightenStarted && !isReset ) { initStraighten = true; resetStraighten(); invalidate(); } } private void flip( boolean horizontal, boolean vertical ) { invalidate(); PointF center = getCenter(); if ( horizontal ) { mFlipType ^= FlipType.FLIP_HORIZONTAL.nativeInt; mDrawMatrix.postScale( -1, 1, center.x, center.y ); } if ( vertical ) { mFlipType ^= FlipType.FLIP_VERTICAL.nativeInt; mDrawMatrix.postScale( 1, -1, center.x, center.y ); } mRotateMatrix.postRotate( (float) ( -mRotation * 2 ), center.x, center.y ); mRotation = Point2D.angle360( getRotationFromMatrix( mRotateMatrix ) ); mFlipMatrix.reset(); } /** The m matrix values. */ protected final float[] mMatrixValues = new float[9]; /** * Gets the value. * * @param matrix * the matrix * @param whichValue * the which value * @return the value */ protected float getValue( Matrix matrix, int whichValue ) { matrix.getValues( mMatrixValues ); return mMatrixValues[whichValue]; } /** * Gets the matrix scale. * * @param matrix * the matrix * @return the matrix scale */ protected float[] getMatrixScale( Matrix matrix ) { float[] result = new float[2]; result[0] = getValue( matrix, Matrix.MSCALE_X ); result[1] = getValue( matrix, Matrix.MSCALE_Y ); return result; } /** The m flip type. */ protected int mFlipType = FlipType.FLIP_NONE.nativeInt; /** * The Enum FlipType. */ public enum FlipType { /** The FLI p_ none. */ FLIP_NONE( 1 << 0 ), /** The FLI p_ horizontal. */ FLIP_HORIZONTAL( 1 << 1 ), /** The FLI p_ vertical. */ FLIP_VERTICAL( 1 << 2 ); /** * Instantiates a new flip type. * * @param ni * the ni */ FlipType( int ni ) { nativeInt = ni; } /** The native int. */ public final int nativeInt; } /* * (non-Javadoc) * * @see android.view.View#getRotation() */ public float getRotation() { return (float) mRotation; } /** * Gets the horizontal flip. * * @return the horizontal flip */ public boolean getHorizontalFlip() { if ( mFlipType != FlipType.FLIP_NONE.nativeInt ) { return ( mFlipType & FlipType.FLIP_HORIZONTAL.nativeInt ) == FlipType.FLIP_HORIZONTAL.nativeInt; } return false; } /** * Gets the vertical flip. * * @return the vertical flip */ public boolean getVerticalFlip() { if ( mFlipType != FlipType.FLIP_NONE.nativeInt ) { return ( mFlipType & FlipType.FLIP_VERTICAL.nativeInt ) == FlipType.FLIP_VERTICAL.nativeInt; } return false; } /** * Gets the flip type. * * @return the flip type */ public int getFlipType() { return mFlipType; } /** * Checks if is running. * * @return true, if is running */ public boolean isRunning() { return mRunning; } /** * Reset the image to the original state. */ public void reset() { isReset = true; onReset(); } /** * On reset. */ private void onReset() { if ( isReset ) { double rotation = (double) getRotation(); double straightenRotation = getStraightenAngle(); boolean resetStraighten = getStraightenStarted(); straightenStarted = false; rotation = rotation%360; if( rotation > 180 ){ rotation = rotation - 360; } final boolean hflip = getHorizontalFlip(); final boolean vflip = getVerticalFlip(); boolean handled = false; initStraighten = false; invalidate(); if ( rotation != 0 || resetStraighten ) { if( resetStraighten ){ straightenBy( -straightenRotation, resetAnimTime ); } else { rotateBy( -rotation, resetAnimTime ); } handled = true; } if ( hflip ) { flip( true, resetAnimTime ); handled = true; } if ( vflip ) { flip( false, resetAnimTime ); handled = true; } if ( !handled ) { fireOnResetComplete(); } } } /** * Fire on reset complete. */ private void fireOnResetComplete() { if ( mResetListener != null ) { mResetListener.onResetComplete(); } } /** * */ @Override protected void onConfigurationChanged( Configuration newConfig ) { // TODO // During straighten, we must bring it to the start if orientation is changed orientation = getResources().getConfiguration().orientation; initStraighten = true; invalidate(); if ( straightenStarted ) { initStraighten = true; resetStraighten(); invalidate(); } } }
Java
package com.aviary.android.feather.widget; abstract class IFlingRunnable implements Runnable { public static interface FlingRunnableView { boolean removeCallbacks( Runnable action ); boolean post( Runnable action ); void scrollIntoSlots(); void trackMotionScroll( int newX ); int getMinX(); int getMaxX(); } protected int mLastFlingX; protected boolean mShouldStopFling; protected FlingRunnableView mParent; protected int mAnimationDuration; protected static final String LOG_TAG = "fling"; public IFlingRunnable( FlingRunnableView parent, int animationDuration ) { mParent = parent; mAnimationDuration = animationDuration; } public int getLastFlingX() { return mLastFlingX; } protected void startCommon() { mParent.removeCallbacks( this ); } public void stop( boolean scrollIntoSlots ) { mParent.removeCallbacks( this ); endFling( scrollIntoSlots ); } public void startUsingDistance( int initialX, int distance ) { if ( distance == 0 ) return; startCommon(); mLastFlingX = initialX; _startUsingDistance( mLastFlingX, distance ); mParent.post( this ); } public void startUsingVelocity( int initialX, int initialVelocity ) { if ( initialVelocity == 0 ) return; startCommon(); mLastFlingX = initialX; _startUsingVelocity( mLastFlingX, initialVelocity ); mParent.post( this ); } protected void endFling( boolean scrollIntoSlots ) { forceFinished( true ); mLastFlingX = 0; if ( scrollIntoSlots ) { mParent.scrollIntoSlots(); } } @Override public void run() { mShouldStopFling = false; final boolean more = computeScrollOffset(); int x = getCurrX(); mParent.trackMotionScroll( x ); if ( more && !mShouldStopFling ) { mLastFlingX = x; mParent.post( this ); } else { endFling( true ); } } public abstract boolean springBack( int startX, int startY, int minX, int maxX, int minY, int maxY ); protected abstract boolean computeScrollOffset(); protected abstract int getCurrX(); public abstract float getCurrVelocity(); protected abstract void forceFinished( boolean finished ); protected abstract void _startUsingVelocity( int initialX, int velocity ); protected abstract void _startUsingDistance( int initialX, int distance ); public abstract boolean isFinished(); }
Java
package com.aviary.android.feather.graphics; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.ColorMatrixColorFilter; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.StateListDrawable; /** * The Class ToolIconsDrawable. */ public class ToolIconsDrawable extends StateListDrawable { Drawable mDrawable; final static int state_pressed = android.R.attr.state_pressed; /** The white color filter. */ ColorMatrixColorFilter whiteColorFilter = new ColorMatrixColorFilter( new float[] { 1, 0, 0, 0, 255, 0, 1, 0, 0, 255, 0, 0, 1, 0, 255, 0, 0, 0, 1, 0, } ); /** * Instantiates a new tool icons drawable. * * @param res * the res * @param resId * the res id */ public ToolIconsDrawable( Resources res, int resId ) { super(); mDrawable = res.getDrawable( resId ); } /* * (non-Javadoc) * * @see android.graphics.drawable.DrawableContainer#onBoundsChange(android.graphics.Rect) */ @Override protected void onBoundsChange( Rect bounds ) { super.onBoundsChange( bounds ); mDrawable.setBounds( bounds ); } /* * (non-Javadoc) * * @see android.graphics.drawable.DrawableContainer#getIntrinsicHeight() */ @Override public int getIntrinsicHeight() { if ( mDrawable != null ) return mDrawable.getIntrinsicHeight(); return super.getIntrinsicHeight(); } /* * (non-Javadoc) * * @see android.graphics.drawable.DrawableContainer#getIntrinsicWidth() */ @Override public int getIntrinsicWidth() { if ( mDrawable != null ) return mDrawable.getIntrinsicWidth(); return super.getIntrinsicWidth(); } /* * (non-Javadoc) * * @see android.graphics.drawable.DrawableContainer#draw(android.graphics.Canvas) */ @Override public void draw( Canvas canvas ) { if ( mDrawable != null ) { mDrawable.draw( canvas ); } } /* * (non-Javadoc) * * @see android.graphics.drawable.DrawableContainer#getOpacity() */ @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } /* * (non-Javadoc) * * @see android.graphics.drawable.DrawableContainer#setAlpha(int) */ @Override public void setAlpha( int alpha ) { if ( mDrawable != null ) mDrawable.setAlpha( alpha ); } /* * (non-Javadoc) * * @see android.graphics.drawable.DrawableContainer#setColorFilter(android.graphics.ColorFilter) */ @Override public void setColorFilter( ColorFilter cf ) { if ( mDrawable != null ) { mDrawable.setColorFilter( cf ); } invalidateSelf(); } /* * (non-Javadoc) * * @see android.graphics.drawable.StateListDrawable#onStateChange(int[]) */ @Override protected boolean onStateChange( int[] state ) { boolean pressed = false; if ( state != null && state.length > 0 ) { for ( int i = 0; i < state.length; i++ ) { if ( state[i] == state_pressed ) { pressed = true; break; } } } boolean result = pressed != mPressed; setPressed( pressed ); return result; } /** The m pressed. */ private boolean mPressed; /** * Sets the pressed. * * @param value * the new pressed */ public void setPressed( boolean value ) { if ( value ) { setColorFilter( whiteColorFilter ); } else { setColorFilter( null ); } mPressed = value; } }
Java
package com.aviary.android.feather.graphics; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable.Orientation; /** * Draw a linear gradient. * * @author alessandro */ public class LinearGradientDrawable extends Drawable { private final Paint mFillPaint = new Paint( Paint.ANTI_ALIAS_FLAG ); private float mCornerRadius = 0; private boolean mRectIsDirty = true; private int mAlpha = 0xFF; // modified by the caller private boolean mDither = true; private ColorFilter mColorFilter; private Orientation mOrientation = Orientation.LEFT_RIGHT; private int[] mColors; private float[] mPositions; private final RectF mRect = new RectF(); /** * Instantiates a new linear gradient drawable. * * @param orientation * the orientation * @param colors * the colors * @param positions * the positions */ public LinearGradientDrawable( Orientation orientation, int[] colors, float[] positions ) { mOrientation = orientation; mColors = colors; mPositions = positions; } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#draw(android.graphics.Canvas) */ @Override public void draw( Canvas canvas ) { if ( !ensureValidRect() ) return; mFillPaint.setAlpha( mAlpha ); mFillPaint.setDither( mDither ); mFillPaint.setColorFilter( mColorFilter ); if ( mCornerRadius > 0 ) { float rad = mCornerRadius; float r = Math.min( mRect.width(), mRect.height() ) * 0.5f; if ( rad > r ) { rad = r; } canvas.drawRoundRect( mRect, rad, rad, mFillPaint ); } else { canvas.drawRect( mRect, mFillPaint ); } } /** * Ensure valid rect. * * @return true, if successful */ private boolean ensureValidRect() { if ( mRectIsDirty ) { mRectIsDirty = false; Rect bounds = getBounds(); float inset = 0; mRect.set( bounds.left + inset, bounds.top + inset, bounds.right - inset, bounds.bottom - inset ); final int[] colors = mColors; if ( colors != null ) { RectF r = mRect; float x0, x1, y0, y1; final float level = 1.0f; switch ( mOrientation ) { case TOP_BOTTOM: x0 = r.left; y0 = r.top; x1 = x0; y1 = level * r.bottom; break; case TR_BL: x0 = r.right; y0 = r.top; x1 = level * r.left; y1 = level * r.bottom; break; case RIGHT_LEFT: x0 = r.right; y0 = r.top; x1 = level * r.left; y1 = y0; break; case BR_TL: x0 = r.right; y0 = r.bottom; x1 = level * r.left; y1 = level * r.top; break; case BOTTOM_TOP: x0 = r.left; y0 = r.bottom; x1 = x0; y1 = level * r.top; break; case BL_TR: x0 = r.left; y0 = r.bottom; x1 = level * r.right; y1 = level * r.top; break; case LEFT_RIGHT: x0 = r.left; y0 = r.top; x1 = level * r.right; y1 = y0; break; default:/* TL_BR */ x0 = r.left; y0 = r.top; x1 = level * r.right; y1 = level * r.bottom; break; } mFillPaint.setShader( new LinearGradient( x0, y0, x1, y1, colors, mPositions, Shader.TileMode.CLAMP ) ); } } return !mRect.isEmpty(); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#onBoundsChange(android.graphics.Rect) */ @Override protected void onBoundsChange( Rect r ) { super.onBoundsChange( r ); mRectIsDirty = true; } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#getOpacity() */ @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#setAlpha(int) */ @Override public void setAlpha( int alpha ) { if ( alpha != mAlpha ) { mAlpha = alpha; invalidateSelf(); } } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#setDither(boolean) */ @Override public void setDither( boolean dither ) { if ( dither != mDither ) { mDither = dither; invalidateSelf(); } } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#setColorFilter(android.graphics.ColorFilter) */ @Override public void setColorFilter( ColorFilter cf ) { if ( cf != mColorFilter ) { mColorFilter = cf; invalidateSelf(); } } /** * Sets the corner radius. * * @param radius * the new corner radius */ public void setCornerRadius( float radius ) { mCornerRadius = radius; invalidateSelf(); } }
Java
package com.aviary.android.feather.graphics; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable.Callback; import com.aviary.android.feather.widget.Gallery; /** * Default {@link Gallery} drawable which accept a {@link Drawable} as overlay. * * @author alessandro * @see DefaultGalleryCheckboxDrawable */ public class OverlayGalleryCheckboxDrawable extends DefaultGalleryCheckboxDrawable implements Callback { protected Drawable mOverlayDrawable; protected float mBottomOffset; protected float mPaddingW; protected float mPaddingH; /** * Instantiates a new overlay gallery checkbox drawable. * * @param res * {@link Context} resource manager * @param pressed * pressed state * @param drawable * drawable used as overlay * @param bottomOffset * value from 0.0 to 1.0. It's the maximum height of the overlay. According to this value the size and the center of * the overlay drawable will change. * @param padding * padding of the overlay drawable */ public OverlayGalleryCheckboxDrawable( Resources res, boolean pressed, Drawable drawable, float bottomOffset, float padding ) { this( res, pressed, drawable, bottomOffset, padding, padding ); } public OverlayGalleryCheckboxDrawable( Resources res, boolean pressed, Drawable drawable, float bottomOffset, float paddingW, float paddingH ) { super( res, pressed ); mOverlayDrawable = drawable; mBottomOffset = bottomOffset; mPaddingW = paddingW; mPaddingH = paddingH; if ( mOverlayDrawable != null ) mOverlayDrawable.setCallback( this ); } @Override protected void onBoundsChange( Rect bounds ) { super.onBoundsChange( bounds ); if ( mOverlayDrawable != null ) { final float maxHeight = bounds.height() * mBottomOffset; final int paddingW = (int) ( mPaddingW * bounds.width() ); final int paddingH = (int) ( mPaddingH * maxHeight ); Rect mBoundsRect = new Rect( paddingW, paddingH, bounds.width() - paddingW, (int) maxHeight - paddingH ); mOverlayDrawable.setBounds( mBoundsRect ); } } @Override public void draw( Canvas canvas ) { super.draw( canvas ); if ( mOverlayDrawable != null ) { mOverlayDrawable.draw( canvas ); } } @Override public void invalidateDrawable( Drawable arg0 ) { invalidateSelf(); } @Override public void scheduleDrawable( Drawable arg0, Runnable arg1, long arg2 ) { } @Override public void unscheduleDrawable( Drawable arg0, Runnable arg1 ) {} }
Java
package com.aviary.android.feather.graphics; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; import com.outsourcing.bottle.R; import com.aviary.android.feather.widget.Gallery; /** * Default checkbox drawable for {@link Gallery} views.<br /> * Draw a checkbox drawable in order to simulate a checkbox component.<br/> * * @author alessandro * */ public class CropCheckboxDrawable extends OverlayGalleryCheckboxDrawable { /** The default drawable. */ protected Drawable mCropDrawable; /** * Instantiates a new crop checkbox drawable. * * @param res * the res * @param pressed * the pressed * @param resId * the res id * @param bottomOffset * the bottom offset * @param padding * the padding */ public CropCheckboxDrawable( Resources res, boolean pressed, int resId, float bottomOffset, float paddingW, float paddingH ) { this( res, pressed, res.getDrawable( resId ), bottomOffset, paddingW, paddingH ); } /** * Instantiates a new crop checkbox drawable. * * @param res * the res * @param pressed * the pressed * @param drawable * the drawable * @param bottomOffset * the bottom offset * @param padding * the padding */ public CropCheckboxDrawable( Resources res, boolean pressed, Drawable drawable, float bottomOffset, float paddingW, float paddingH ) { super( res, pressed, drawable, bottomOffset, paddingW, paddingH ); mCropDrawable = res.getDrawable( pressed ? R.drawable.feather_crop_checkbox_selected : R.drawable.feather_crop_checkbox_unselected ); } /* * (non-Javadoc) * * @see com.aviary.android.feather.graphics.OverlayGalleryCheckboxDrawable#draw(android.graphics.Canvas) */ @Override public void draw( Canvas canvas ) { super.draw( canvas ); mCropDrawable.draw( canvas ); } /* * (non-Javadoc) * * @see com.aviary.android.feather.graphics.OverlayGalleryCheckboxDrawable#onBoundsChange(android.graphics.Rect) */ @Override protected void onBoundsChange( Rect rect ) { super.onBoundsChange( rect ); int left = (int) ( rect.width() * 0.2831 ); int top = (int) ( rect.height() * 0.6708 ); int right = (int) ( rect.width() * 0.7433 ); int bottom = (int) ( rect.height() * 0.8037 ); mCropDrawable.setBounds( left, top, right, bottom ); } /* * (non-Javadoc) * * @see com.aviary.android.feather.graphics.DefaultGalleryCheckboxDrawable#getOpacity() */ @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } /* * (non-Javadoc) * * @see com.aviary.android.feather.graphics.DefaultGalleryCheckboxDrawable#setAlpha(int) */ @Override public void setAlpha( int alpha ) {} /* * (non-Javadoc) * * @see com.aviary.android.feather.graphics.DefaultGalleryCheckboxDrawable#setColorFilter(android.graphics.ColorFilter) */ @Override public void setColorFilter( ColorFilter cf ) {} }
Java
package com.aviary.android.feather.graphics; import java.lang.ref.WeakReference; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.util.Log; public class ExternalFilterPackDrawable extends Drawable { Paint mPaint; Matrix mMatrix; Matrix mDrawMatrix = new Matrix(); Paint mDrawPaint = new Paint(); static final int defaultWidth = 161; static final int defaultHeight = 250; final int bitmapWidth; final int bitmapHeight; float xRatio; float yRatio; private String mTitle, mShortTitle; private int mNumEffects; private int mColor; private WeakReference<Bitmap> mShadowBitmap; private WeakReference<Bitmap> mEffectBitmap; public ExternalFilterPackDrawable( String title, String shortTitle, int numEffects, int color, Typeface typeFace, Bitmap shadow, Bitmap effect ) { super(); mMatrix = new Matrix(); mPaint = new Paint( Paint.ANTI_ALIAS_FLAG ); mPaint.setSubpixelText( true ); mPaint.setAntiAlias( true ); mPaint.setDither( true ); mPaint.setFilterBitmap( true ); bitmapWidth = effect.getWidth(); bitmapHeight = effect.getHeight(); Log.d( "xxx", "size: " + bitmapWidth + "x" + bitmapHeight ); xRatio = (float) defaultWidth / bitmapWidth; yRatio = (float) defaultHeight / bitmapHeight; mShadowBitmap = new WeakReference<Bitmap>( shadow ); mEffectBitmap = new WeakReference<Bitmap>( effect ); mTitle = title; mShortTitle = shortTitle; mNumEffects = numEffects < 0 ? 6 : numEffects; mColor = color; if ( null != typeFace ) { mPaint.setTypeface( typeFace ); } } @Override protected void finalize() throws Throwable { super.finalize(); } @Override protected void onBoundsChange( Rect bounds ) { super.onBoundsChange( bounds ); } @Override public void draw( Canvas canvas ) { drawInternal( canvas ); } @Override public int getIntrinsicWidth() { return bitmapWidth; } @Override public int getIntrinsicHeight() { return bitmapHeight; } private void drawInternal( Canvas canvas ) { final int leftTextSize = (int) ( 32 / xRatio ); final int titleTextSize = (int) ( 26 / yRatio ); Bitmap bmp; // SHADOW mMatrix.reset(); if ( null != mShadowBitmap ) { bmp = mShadowBitmap.get(); if ( null != bmp ) { canvas.drawBitmap( bmp, mMatrix, mPaint ); } } // colored background mPaint.setColor( mColor ); canvas.drawRect( 17 / xRatio, 37 / yRatio, 145 / xRatio, 225 / yRatio, mPaint ); int saveCount = canvas.save( Canvas.MATRIX_SAVE_FLAG ); canvas.rotate( 90 ); // SHORT TITLE mPaint.setColor( Color.BLACK ); mPaint.setTextSize( leftTextSize ); canvas.drawText( mShortTitle, 66 / xRatio, -26 / yRatio, mPaint ); // TITLE mPaint.setTextSize( titleTextSize ); canvas.drawText( mTitle, 69 / xRatio, -88 / yRatio, mPaint ); // NUM EFFECTS mPaint.setARGB( 255, 35, 31, 42 ); canvas.drawRect( 135 / yRatio, -16 / xRatio, 216 / yRatio, -57 / xRatio, mPaint ); mPaint.setColor( Color.WHITE ); mPaint.setTextSize( leftTextSize ); String text = mNumEffects + "fx"; int numEffectsLength = String.valueOf( mNumEffects ).length(); canvas.drawText( text, ( 160 - ( numEffectsLength * 10 ) ) / xRatio, -26 / yRatio, mPaint ); // restore canvas canvas.restoreToCount( saveCount ); // cannister if ( null != mEffectBitmap ) { bmp = mEffectBitmap.get(); if ( null != bmp ) { canvas.drawBitmap( bmp, mMatrix, mPaint ); } } } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } @Override public void setAlpha( int alpha ) {} @Override public void setColorFilter( ColorFilter cf ) {} @Override public void setBounds( int left, int top, int right, int bottom ) { Log.d( "xxx", "setBounds: " + left + ", " + top + ", " + right + ", " + bottom ); super.setBounds( left, top, right, bottom ); } }
Java
package com.aviary.android.feather.graphics; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.Shader; import android.graphics.Shader.TileMode; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.view.View; /** * Draw a bitmap repeated horizontally and scaled vertically. * * @author alessandro */ public class RepeatableHorizontalDrawable extends Drawable { private Paint mPaint = new Paint(); private Rect mRect = new Rect(); private Matrix mMatrix = new Matrix(); private Bitmap mBitmap = null; private Shader mShader; /** * Construct a new {@link RepeatableHorizontalDrawable} instance. * * @param resources * the current Context {@link Resources} used to extract the resource * @param resId * the {@link BitmapDrawable} resource used to draw */ public RepeatableHorizontalDrawable( Resources resources, int resId ) { try { Bitmap bitmap = ( (BitmapDrawable) resources.getDrawable( resId ) ).getBitmap(); init( bitmap ); } catch ( Exception e ) {} } public static Drawable createFromView( View view ) { Drawable drawable = view.getBackground(); if ( null != drawable ) { if ( drawable instanceof BitmapDrawable ) { Bitmap bitmap = ( (BitmapDrawable) drawable ).getBitmap(); return new RepeatableHorizontalDrawable( bitmap ); } } return drawable; } public RepeatableHorizontalDrawable( Bitmap bitmap ) { init( bitmap ); } private void init( Bitmap bitmap ) { mBitmap = bitmap; if ( mBitmap != null ) { mShader = new BitmapShader( mBitmap, TileMode.REPEAT, TileMode.CLAMP ); mPaint.setShader( mShader ); } } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#draw(android.graphics.Canvas) */ @Override public void draw( Canvas canvas ) { if ( null != mBitmap ) { copyBounds( mRect ); canvas.drawPaint( mPaint ); } } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#onBoundsChange(android.graphics.Rect) */ @Override protected void onBoundsChange( Rect bounds ) { super.onBoundsChange( bounds ); if ( null != mBitmap ) { mMatrix.setScale( 1, (float) bounds.height() / mBitmap.getHeight() ); mShader.setLocalMatrix( mMatrix ); } } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#getOpacity() */ @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#setAlpha(int) */ @Override public void setAlpha( int alpha ) { mPaint.setAlpha( alpha ); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#setColorFilter(android.graphics.ColorFilter) */ @Override public void setColorFilter( ColorFilter cf ) { mPaint.setColorFilter( cf ); } }
Java
package com.aviary.android.feather.graphics; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; import com.aviary.android.feather.library.graphics.drawable.IBitmapDrawable; /** * The Class StickerBitmapDrawable. */ public class StickerBitmapDrawable extends Drawable implements IBitmapDrawable { protected Bitmap mBitmap; protected Paint mPaint; protected Paint mShadowPaint; protected Rect srcRect; protected Rect dstRect; protected ColorFilter blackColorFilter, whiteColorFilter; protected int mInset; /** * Instantiates a new sticker bitmap drawable. * * @param b * the b * @param inset * the inset */ public StickerBitmapDrawable( Bitmap b, int inset ) { mBitmap = b; mPaint = new Paint(); mPaint.setAntiAlias( true ); mPaint.setDither( true ); mPaint.setFilterBitmap( false ); mInset = inset; mShadowPaint = new Paint( mPaint ); mShadowPaint.setAntiAlias( true ); srcRect = new Rect( 0, 0, b.getWidth(), b.getHeight() ); dstRect = new Rect(); blackColorFilter = new ColorMatrixColorFilter( new float[] { 1, 0, 0, -255, 0, 0, 1, 0, -255, 0, 0, 0, 1, -255, 0, 0, 0, 0, 0.3f, 0, } ); whiteColorFilter = new ColorMatrixColorFilter( new float[] { 1, 0, 0, 0, 255, 0, 1, 0, 0, 255, 0, 0, 1, 0, 255, 0, 0, 0, 1, 0, } ); mShadowPaint.setColorFilter( blackColorFilter ); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#draw(android.graphics.Canvas) */ @Override public void draw( Canvas canvas ) { dstRect.set( srcRect ); dstRect.inset( -mInset / 2, -mInset / 2 ); dstRect.offset( mInset / 2 + 1, mInset / 2 + 1 ); canvas.drawBitmap( mBitmap, srcRect, dstRect, mShadowPaint ); mPaint.setColorFilter( whiteColorFilter ); dstRect.offset( -1, -1 ); canvas.drawBitmap( mBitmap, srcRect, dstRect, mPaint ); mPaint.setColorFilter( null ); canvas.drawBitmap( mBitmap, mInset / 2, mInset / 2, mPaint ); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#getOpacity() */ @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#setAlpha(int) */ @Override public void setAlpha( int alpha ) {} /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#setColorFilter(android.graphics.ColorFilter) */ @Override public void setColorFilter( ColorFilter cf ) { mPaint.setColorFilter( cf ); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#getIntrinsicWidth() */ @Override public int getIntrinsicWidth() { return mBitmap.getWidth() + ( mInset * 2 ); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#getIntrinsicHeight() */ @Override public int getIntrinsicHeight() { return mBitmap.getHeight() + ( mInset * 2 ); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#getMinimumWidth() */ @Override public int getMinimumWidth() { return mBitmap.getWidth() + ( mInset * 2 ); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#getMinimumHeight() */ @Override public int getMinimumHeight() { return mBitmap.getHeight() + ( mInset * 2 ); } /* * (non-Javadoc) * * @see com.aviary.android.feather.library.graphics.drawable.IBitmapDrawable#getBitmap() */ @Override public Bitmap getBitmap() { return mBitmap; } }
Java
package com.aviary.android.feather.graphics; import android.graphics.BlurMaskFilter; import android.graphics.BlurMaskFilter.Blur; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.widget.Toast; /** * Default drawable used to display the {@link Toast} preview for panels like the RedEye panel, Whiten, etc.. * * @author alessandro * */ public class PreviewCircleDrawable extends Drawable { Paint mPaint; float mRadius; /** * Instantiates a new preview circle drawable. * * @param radius * the radius */ public PreviewCircleDrawable( final float radius ) { mPaint = new Paint( Paint.ANTI_ALIAS_FLAG ); mPaint.setFilterBitmap( false ); mPaint.setDither( true ); mPaint.setStrokeWidth( 10.0f ); mPaint.setStyle( Paint.Style.STROKE ); mPaint.setColor( Color.WHITE ); mRadius = radius; } /** * Sets the paint. * * @param value * the new paint */ public void setPaint( Paint value ) { mPaint.set( value ); } /** * Sets the Paint style. * * @param value * the new style */ public void setStyle( Paint.Style value ) { mPaint.setStyle( value ); } /** * Sets the radius. * * @param value * the new radius */ public void setRadius( float value ) { mRadius = value; invalidateSelf(); } /** * Sets the color. * * @param color * the new color */ public void setColor( int color ) { mPaint.setColor( color ); } /** * Sets the blur. * * @param value * the new blur */ public void setBlur( int value ) { if ( value > 0 ) { mPaint.setMaskFilter( new BlurMaskFilter( value, Blur.NORMAL ) ); } else { mPaint.setMaskFilter( null ); } } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#draw(android.graphics.Canvas) */ @Override public void draw( final Canvas canvas ) { final RectF rect = new RectF( getBounds() ); canvas.drawCircle( rect.centerX(), rect.centerY(), mRadius, mPaint ); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#getOpacity() */ @Override public int getOpacity() { return PixelFormat.OPAQUE; } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#setAlpha(int) */ @Override public void setAlpha( final int alpha ) {} /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#setColorFilter(android.graphics.ColorFilter) */ @Override public void setColorFilter( final ColorFilter cf ) {} };
Java
package com.aviary.android.feather.graphics; import android.graphics.BlurMaskFilter; import android.graphics.BlurMaskFilter.Blur; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; /** * Drawable used as overlay {@link Drawable} in conjunction with {@link OverlayGalleryCheckboxDrawable}.<br /> * Create a circle drawable using radius and blur_size. * * @author alessandro * */ public class GalleryCircleDrawable extends Drawable { private Paint mPaint; private Paint mShadowPaint; final int mShadowOffset = 3; float mStrokeWidth = 5.0f; float mRadius, mOriginalRadius; float centerX, centerY; /** * Instantiates a new gallery circle drawable. * * @param radius * Radius of the circle * @param blur_size * blur size, if &gt; 0 create a blur mask around the circle */ public GalleryCircleDrawable( float radius, int blur_size ) { super(); mPaint = new Paint( Paint.ANTI_ALIAS_FLAG ); mPaint.setStrokeWidth( mStrokeWidth ); mPaint.setStyle( Paint.Style.STROKE ); mPaint.setColor( Color.WHITE ); mShadowPaint = new Paint( mPaint ); mShadowPaint.setColor( Color.BLACK ); update( radius, blur_size ); } /** * Sets the stroke width. * * @param value * the new stroke width */ public void setStrokeWidth( float value ) { mStrokeWidth = value; mPaint.setStrokeWidth( mStrokeWidth ); invalidateSelf(); } /** * Update. * * @param radius * the radius * @param blur_size * the blur_size */ public void update( float radius, int blur_size ) { mOriginalRadius = radius; if ( blur_size > 0 ) mPaint.setMaskFilter( new BlurMaskFilter( blur_size, Blur.NORMAL ) ); else mPaint.setMaskFilter( null ); invalidateSelf(); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#draw(android.graphics.Canvas) */ @Override public void draw( Canvas canvas ) { canvas.drawCircle( centerX, centerY + mShadowOffset, mRadius, mShadowPaint ); canvas.drawCircle( centerX, centerY, mRadius, mPaint ); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#onBoundsChange(android.graphics.Rect) */ @Override protected void onBoundsChange( Rect rect ) { super.onBoundsChange( rect ); invalidateSelf(); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#invalidateSelf() */ @Override public void invalidateSelf() { super.invalidateSelf(); invalidate(); } /** * Invalidate. */ protected void invalidate() { Rect rect = getBounds(); int minSize = Math.max( 1, Math.min( rect.width(), rect.height() ) ); mRadius = ( (float) minSize * mOriginalRadius ) / 2; centerX = rect.centerX(); centerY = rect.centerY(); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#getOpacity() */ @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#setAlpha(int) */ @Override public void setAlpha( int alpha ) {} /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#setColorFilter(android.graphics.ColorFilter) */ @Override public void setColorFilter( ColorFilter cf ) {} }
Java
package com.aviary.android.feather.graphics; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.StateListDrawable; import com.outsourcing.bottle.R; import com.aviary.android.feather.widget.Gallery; /** * Default Drawable used for all the Views created inside a {@link Gallery}.<br/ > * This drawable will only draw the default background based on the pressed state.<br /> * Note that this {@link Drawable} should be used inside a {@link StateListDrawable} instance. * * @author alessandro * */ public class DefaultGalleryCheckboxDrawable extends Drawable { private Paint mPaint; protected Rect mRect; private int backgroundColor; // 0xFF2e2e2e - 0xFF404040 private int borderColor; // 0xff535353 - 0xFF626262 /** * Instantiates a new default gallery checkbox drawable. * * @param res * {@link Context} resource manager * @param pressed * pressed state. it will affect the background colors */ public DefaultGalleryCheckboxDrawable( Resources res, boolean pressed ) { super(); mPaint = new Paint( Paint.ANTI_ALIAS_FLAG ); mRect = new Rect(); if ( pressed ) { backgroundColor = res.getColor( R.color.feather_crop_adapter_background_selected ); borderColor = res.getColor( R.color.feather_crop_adapter_border_selected ); } else { backgroundColor = res.getColor( R.color.feather_crop_adapter_background_normal ); borderColor = res.getColor( R.color.feather_crop_adapter_border_normal ); } } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#draw(android.graphics.Canvas) */ @Override public void draw( Canvas canvas ) { copyBounds( mRect ); mPaint.setColor( backgroundColor ); canvas.drawPaint( mPaint ); mPaint.setColor( Color.BLACK ); canvas.drawRect( 0, 0, 1, mRect.bottom, mPaint ); canvas.drawRect( mRect.right - 1, 0, mRect.right, mRect.bottom, mPaint ); mPaint.setColor( borderColor ); canvas.drawRect( 1, 0, 3, mRect.bottom, mPaint ); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#getOpacity() */ @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#setAlpha(int) */ @Override public void setAlpha( int alpha ) {} /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#setColorFilter(android.graphics.ColorFilter) */ @Override public void setColorFilter( ColorFilter cf ) {} }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aviary.android.feather.graphics; import java.io.IOException; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Rect; import android.graphics.drawable.Animatable; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.SystemClock; import android.util.AttributeSet; import com.aviary.android.feather.Constants; import com.aviary.android.feather.library.utils.ReflectionUtils; import com.aviary.android.feather.library.utils.ReflectionUtils.ReflectionException; /** * Rotate Drawable. */ public class AnimatedRotateDrawable extends Drawable implements Drawable.Callback, Runnable, Animatable { private AnimatedRotateState mState; private boolean mMutated; private float mCurrentDegrees; private float mIncrement; private boolean mRunning; /** * Instantiates a new animated rotate drawable. */ public AnimatedRotateDrawable() { this( null, null ); } /** * Instantiates a new animated rotate drawable. * * @param res * the res * @param resId * the res id */ public AnimatedRotateDrawable( Resources res, int resId ) { this( res, resId, 8, 100 ); } public AnimatedRotateDrawable( Resources res, int resId, int frames, int duration ) { this( null, null ); final float pivotX = 0.5f; final float pivotY = 0.5f; final boolean pivotXRel = true; final boolean pivotYRel = true; setFramesCount( frames ); setFramesDuration( duration ); Drawable drawable = null; if ( resId > 0 ) { drawable = res.getDrawable( resId ); } final AnimatedRotateState rotateState = mState; rotateState.mDrawable = drawable; rotateState.mPivotXRel = pivotXRel; rotateState.mPivotX = pivotX; rotateState.mPivotYRel = pivotYRel; rotateState.mPivotY = pivotY; init(); if ( drawable != null ) { drawable.setCallback( this ); } } /** * Instantiates a new animated rotate drawable. * * @param rotateState * the rotate state * @param res * the res */ private AnimatedRotateDrawable( AnimatedRotateState rotateState, Resources res ) { mState = new AnimatedRotateState( rotateState, this, res ); init(); } /** * Initialize */ private void init() { final AnimatedRotateState state = mState; mIncrement = 360.0f / state.mFramesCount; final Drawable drawable = state.mDrawable; if ( drawable != null ) { drawable.setFilterBitmap( true ); if ( drawable instanceof BitmapDrawable ) { ( (BitmapDrawable) drawable ).setAntiAlias( true ); } } } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#draw(android.graphics.Canvas) */ @Override public void draw( Canvas canvas ) { int saveCount = canvas.save(); final AnimatedRotateState st = mState; final Drawable drawable = st.mDrawable; final Rect bounds = drawable.getBounds(); int w = bounds.right - bounds.left; int h = bounds.bottom - bounds.top; float px = st.mPivotXRel ? ( w * st.mPivotX ) : st.mPivotX; float py = st.mPivotYRel ? ( h * st.mPivotY ) : st.mPivotY; canvas.rotate( mCurrentDegrees, px + bounds.left, py + bounds.top ); drawable.draw( canvas ); canvas.restoreToCount( saveCount ); } /* * (non-Javadoc) * * @see android.graphics.drawable.Animatable#start() */ @Override public void start() { if ( !mRunning ) { mRunning = true; nextFrame(); } } /* * (non-Javadoc) * * @see android.graphics.drawable.Animatable#stop() */ @Override public void stop() { mRunning = false; unscheduleSelf( this ); } /* * (non-Javadoc) * * @see android.graphics.drawable.Animatable#isRunning() */ @Override public boolean isRunning() { return mRunning; } /** * Next frame. */ private void nextFrame() { unscheduleSelf( this ); scheduleSelf( this, SystemClock.uptimeMillis() + mState.mFrameDuration ); } /* * (non-Javadoc) * * @see java.lang.Runnable#run() */ @Override public void run() { mCurrentDegrees += mIncrement; if ( mCurrentDegrees > ( 360.0f - mIncrement ) ) { mCurrentDegrees = 0.0f; } invalidateSelf(); nextFrame(); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#setVisible(boolean, boolean) */ @Override public boolean setVisible( boolean visible, boolean restart ) { mState.mDrawable.setVisible( visible, restart ); boolean changed = super.setVisible( visible, restart ); if ( visible ) { if ( changed || restart ) { mCurrentDegrees = 0.0f; nextFrame(); } } else { unscheduleSelf( this ); } return changed; } /** * Returns the drawable rotated by this RotateDrawable. * * @return the drawable */ public Drawable getDrawable() { return mState.mDrawable; } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#getChangingConfigurations() */ @Override public int getChangingConfigurations() { return super.getChangingConfigurations() | mState.mChangingConfigurations | mState.mDrawable.getChangingConfigurations(); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#setAlpha(int) */ @Override public void setAlpha( int alpha ) { mState.mDrawable.setAlpha( alpha ); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#setColorFilter(android.graphics.ColorFilter) */ @Override public void setColorFilter( ColorFilter cf ) { mState.mDrawable.setColorFilter( cf ); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#getOpacity() */ @Override public int getOpacity() { return mState.mDrawable.getOpacity(); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable.Callback#invalidateDrawable(android.graphics.drawable.Drawable) */ @Override public void invalidateDrawable( Drawable who ) { if ( Constants.ANDROID_SDK > 10 ) { Callback callback; try { callback = (Callback) ReflectionUtils.invokeMethod( this, "getCallback" ); } catch ( ReflectionException e ) { return; } if ( callback != null ) { callback.invalidateDrawable( this ); } } } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable.Callback#scheduleDrawable(android.graphics.drawable.Drawable, java.lang.Runnable, * long) */ @Override public void scheduleDrawable( Drawable who, Runnable what, long when ) { if ( Constants.ANDROID_SDK > 10 ) { Callback callback; try { callback = (Callback) ReflectionUtils.invokeMethod( this, "getCallback" ); } catch ( ReflectionException e ) { return; } if ( callback != null ) { callback.scheduleDrawable( this, what, when ); } } } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable.Callback#unscheduleDrawable(android.graphics.drawable.Drawable, java.lang.Runnable) */ @Override public void unscheduleDrawable( Drawable who, Runnable what ) { if ( Constants.ANDROID_SDK > 10 ) { Callback callback; try { callback = (Callback) ReflectionUtils.invokeMethod( this, "getCallback" ); } catch ( ReflectionException e ) { return; } if ( callback != null ) { callback.unscheduleDrawable( this, what ); } } } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#getPadding(android.graphics.Rect) */ @Override public boolean getPadding( Rect padding ) { return mState.mDrawable.getPadding( padding ); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#isStateful() */ @Override public boolean isStateful() { return mState.mDrawable.isStateful(); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#onBoundsChange(android.graphics.Rect) */ @Override protected void onBoundsChange( Rect bounds ) { mState.mDrawable.setBounds( bounds.left, bounds.top, bounds.right, bounds.bottom ); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#getIntrinsicWidth() */ @Override public int getIntrinsicWidth() { return mState.mDrawable.getIntrinsicWidth(); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#getIntrinsicHeight() */ @Override public int getIntrinsicHeight() { return mState.mDrawable.getIntrinsicHeight(); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#getConstantState() */ @Override public ConstantState getConstantState() { if ( mState.canConstantState() ) { mState.mChangingConfigurations = getChangingConfigurations(); return mState; } return null; } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#inflate(android.content.res.Resources, org.xmlpull.v1.XmlPullParser, * android.util.AttributeSet) */ @Override public void inflate( Resources r, XmlPullParser parser, AttributeSet attrs ) throws XmlPullParserException, IOException {} /** * Sets the frames count. * * @param framesCount * the new frames count */ public void setFramesCount( int framesCount ) { mState.mFramesCount = framesCount; mIncrement = 360.0f / mState.mFramesCount; } /** * Sets the frames duration. * * @param framesDuration * the new frames duration */ public void setFramesDuration( int framesDuration ) { mState.mFrameDuration = framesDuration; } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable#mutate() */ @Override public Drawable mutate() { if ( !mMutated && super.mutate() == this ) { mState.mDrawable.mutate(); mMutated = true; } return this; } final static class AnimatedRotateState extends Drawable.ConstantState { Drawable mDrawable; int mChangingConfigurations; boolean mPivotXRel; float mPivotX; boolean mPivotYRel; float mPivotY; int mFrameDuration; int mFramesCount; private boolean mCanConstantState; private boolean mCheckedConstantState; /** * Instantiates a new animated rotate state. * * @param source * the source * @param owner * the owner * @param res * the res */ public AnimatedRotateState( AnimatedRotateState source, AnimatedRotateDrawable owner, Resources res ) { if ( source != null ) { if ( res != null ) { mDrawable = source.mDrawable.getConstantState().newDrawable( res ); } else { mDrawable = source.mDrawable.getConstantState().newDrawable(); } mDrawable.setCallback( owner ); mPivotXRel = source.mPivotXRel; mPivotX = source.mPivotX; mPivotYRel = source.mPivotYRel; mPivotY = source.mPivotY; mFramesCount = source.mFramesCount; mFrameDuration = source.mFrameDuration; mCanConstantState = mCheckedConstantState = true; } } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable.ConstantState#newDrawable() */ @Override public Drawable newDrawable() { return new AnimatedRotateDrawable( this, null ); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable.ConstantState#newDrawable(android.content.res.Resources) */ @Override public Drawable newDrawable( Resources res ) { return new AnimatedRotateDrawable( this, res ); } /* * (non-Javadoc) * * @see android.graphics.drawable.Drawable.ConstantState#getChangingConfigurations() */ @Override public int getChangingConfigurations() { return mChangingConfigurations; } /** * Can constant state. * * @return true, if successful */ public boolean canConstantState() { if ( !mCheckedConstantState ) { mCanConstantState = mDrawable.getConstantState() != null; mCheckedConstantState = true; } return mCanConstantState; } } }
Java
package oauth.signpost.basic; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.util.HashMap; import java.util.List; import java.util.Map; import oauth.signpost.http.HttpRequest; public class HttpURLConnectionRequestAdapter implements HttpRequest { protected HttpURLConnection connection; public HttpURLConnectionRequestAdapter(HttpURLConnection connection) { this.connection = connection; } public String getMethod() { return connection.getRequestMethod(); } public String getRequestUrl() { return connection.getURL().toExternalForm(); } public void setRequestUrl(String url) { // can't do } public void setHeader(String name, String value) { connection.setRequestProperty(name, value); } public String getHeader(String name) { return connection.getRequestProperty(name); } public Map<String, String> getAllHeaders() { Map<String, List<String>> origHeaders = connection.getRequestProperties(); Map<String, String> headers = new HashMap<String, String>(origHeaders.size()); for (String name : origHeaders.keySet()) { List<String> values = origHeaders.get(name); if (!values.isEmpty()) { headers.put(name, values.get(0)); } } return headers; } public InputStream getMessagePayload() throws IOException { return null; } public String getContentType() { return connection.getRequestProperty("Content-Type"); } public HttpURLConnection unwrap() { return connection; } }
Java
package oauth.signpost.basic; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import oauth.signpost.http.HttpResponse; public class HttpURLConnectionResponseAdapter implements HttpResponse { private HttpURLConnection connection; public HttpURLConnectionResponseAdapter(HttpURLConnection connection) { this.connection = connection; } public InputStream getContent() throws IOException { return connection.getInputStream(); } public int getStatusCode() throws IOException { return connection.getResponseCode(); } public String getReasonPhrase() throws Exception { return connection.getResponseMessage(); } public Object unwrap() { return connection; } }
Java
/* * Copyright (c) 2009 Matthias Kaeppler Licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law * or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package oauth.signpost.basic; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import oauth.commons.http.HttpRequestAdapter; import oauth.signpost.AbstractOAuthProvider; import oauth.signpost.http.HttpRequest; import oauth.signpost.http.HttpResponse; import org.apache.http.client.methods.HttpPost; /** * This default implementation uses {@link java.net.HttpURLConnection} type GET * requests to receive tokens from a service provider. * * @author Matthias Kaeppler */ public class DefaultOAuthProvider extends AbstractOAuthProvider { private static final long serialVersionUID = 1L; public DefaultOAuthProvider(String requestTokenEndpointUrl, String accessTokenEndpointUrl, String authorizationWebsiteUrl) { super(requestTokenEndpointUrl, accessTokenEndpointUrl, authorizationWebsiteUrl); } protected HttpRequest createRequest(String endpointUrl) throws MalformedURLException, IOException { HttpURLConnection connection = (HttpURLConnection) new URL(endpointUrl).openConnection(); connection.setRequestMethod("POST"); connection.setAllowUserInteraction(false); connection.setRequestProperty("Content-Length", "0"); return new HttpURLConnectionRequestAdapter(connection); } protected HttpResponse sendRequest(HttpRequest request) throws IOException { HttpURLConnection connection = (HttpURLConnection) request.unwrap(); connection.connect(); return new HttpURLConnectionResponseAdapter(connection); } @Override protected void closeConnection(HttpRequest request, HttpResponse response) { HttpURLConnection connection = (HttpURLConnection) request.unwrap(); if (connection != null) { connection.disconnect(); } } @Override protected HttpResponse sendRequestForTencent(HttpRequest request) throws Exception { return null; } @Override protected HttpRequest createRequestForTencent(String endpointUrl) throws Exception { HttpPost request = new HttpPost(endpointUrl); request.addHeader("Content-Type", "application/x-www-form-urlencoded"); return new HttpRequestAdapter(request); } }
Java
/* Copyright (c) 2009 Matthias Kaeppler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.signpost.basic; import java.net.HttpURLConnection; import oauth.signpost.AbstractOAuthConsumer; import oauth.signpost.http.HttpRequest; /** * The default implementation for an OAuth consumer. Only supports signing * {@link java.net.HttpURLConnection} type requests. * * @author Matthias Kaeppler */ public class DefaultOAuthConsumer extends AbstractOAuthConsumer { private static final long serialVersionUID = 1L; public DefaultOAuthConsumer(String consumerKey, String consumerSecret) { super(consumerKey, consumerSecret); } @Override protected HttpRequest wrap(Object request) { if (!(request instanceof HttpURLConnection)) { throw new IllegalArgumentException( "The default consumer expects requests of type java.net.HttpURLConnection"); } return new HttpURLConnectionRequestAdapter((HttpURLConnection) request); } }
Java
package oauth.signpost.basic; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.Map; import oauth.signpost.http.HttpRequest; public class UrlStringRequestAdapter implements HttpRequest { private String url; public UrlStringRequestAdapter(String url) { this.url = url; } public String getMethod() { return "GET"; } public String getRequestUrl() { return url; } public void setRequestUrl(String url) { this.url = url; } public void setHeader(String name, String value) { } public String getHeader(String name) { return null; } public Map<String, String> getAllHeaders() { return Collections.emptyMap(); } public InputStream getMessagePayload() throws IOException { return null; } public String getContentType() { return null; } public Object unwrap() { return url; } }
Java
package oauth.signpost.exception; @SuppressWarnings("serial") public abstract class OAuthException extends Exception { public OAuthException(String message) { super(message); } public OAuthException(Throwable cause) { super(cause); } public OAuthException(String message, Throwable cause) { super(message, cause); } }
Java
/* Copyright (c) 2009 Matthias Kaeppler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.signpost.exception; @SuppressWarnings("serial") public class OAuthMessageSignerException extends OAuthException { public OAuthMessageSignerException(String message) { super(message); } public OAuthMessageSignerException(Exception cause) { super(cause); } }
Java
/* Copyright (c) 2009 Matthias Kaeppler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.signpost.exception; @SuppressWarnings("serial") public class OAuthNotAuthorizedException extends OAuthException { private static final String ERROR = "Authorization failed (server replied with a 401). " + "This can happen if the consumer key was not correct or " + "the signatures did not match."; private String responseBody; public OAuthNotAuthorizedException() { super(ERROR); } public OAuthNotAuthorizedException(String responseBody) { super(ERROR); this.responseBody = responseBody; } public String getResponseBody() { return responseBody; } }
Java
/* Copyright (c) 2009 Matthias Kaeppler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.signpost.exception; @SuppressWarnings("serial") public class OAuthExpectationFailedException extends OAuthException { public OAuthExpectationFailedException(String message) { super(message); } }
Java
/* Copyright (c) 2009 Matthias Kaeppler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.signpost.exception; @SuppressWarnings("serial") public class OAuthCommunicationException extends OAuthException { private String responseBody; public OAuthCommunicationException(Exception cause) { super("Communication with the service provider failed: " + cause.getLocalizedMessage(), cause); } public OAuthCommunicationException(String message, String responseBody) { super(message); this.responseBody = responseBody; } public String getResponseBody() { return responseBody; } }
Java
/* Copyright (c) 2009 Matthias Kaeppler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.signpost; import java.io.IOException; import java.io.InputStream; import java.util.Random; import oauth.signpost.basic.UrlStringRequestAdapter; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.http.HttpParameters; import oauth.signpost.http.HttpRequest; import oauth.signpost.signature.AuthorizationHeaderSigningStrategy; import oauth.signpost.signature.HmacSha1MessageSigner; import oauth.signpost.signature.OAuthMessageSigner; import oauth.signpost.signature.QueryStringSigningStrategy; import oauth.signpost.signature.SigningStrategy; /** * ABC for consumer implementations. If you're developing a custom consumer you * will probably inherit from this class to save you a lot of work. * * @author Matthias Kaeppler */ public abstract class AbstractOAuthConsumer implements OAuthConsumer { private static final long serialVersionUID = 1L; private String consumerKey, consumerSecret; private String token; private OAuthMessageSigner messageSigner; private SigningStrategy signingStrategy; // these are params that may be passed to the consumer directly (i.e. // without going through the request object) private HttpParameters additionalParameters; // these are the params which will be passed to the message signer private HttpParameters requestParameters; private boolean sendEmptyTokens; public AbstractOAuthConsumer(String consumerKey, String consumerSecret) { this.consumerKey = consumerKey; this.consumerSecret = consumerSecret; setMessageSigner(new HmacSha1MessageSigner()); setSigningStrategy(new AuthorizationHeaderSigningStrategy()); } public void setMessageSigner(OAuthMessageSigner messageSigner) { this.messageSigner = messageSigner; messageSigner.setConsumerSecret(consumerSecret); } public void setSigningStrategy(SigningStrategy signingStrategy) { this.signingStrategy = signingStrategy; } public void setAdditionalParameters(HttpParameters additionalParameters) { this.additionalParameters = additionalParameters; } public HttpRequest sign(HttpRequest request) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException { if (consumerKey == null) { throw new OAuthExpectationFailedException("consumer key not set"); } if (consumerSecret == null) { throw new OAuthExpectationFailedException("consumer secret not set"); } requestParameters = new HttpParameters(); try { if (additionalParameters != null) { requestParameters.putAll(additionalParameters, false); } collectHeaderParameters(request, requestParameters); collectQueryParameters(request, requestParameters); collectBodyParameters(request, requestParameters); // add any OAuth params that haven't already been set completeOAuthParameters(requestParameters); requestParameters.remove(OAuth.OAUTH_SIGNATURE); } catch (IOException e) { throw new OAuthCommunicationException(e); } String signature = messageSigner.sign(request, requestParameters); OAuth.debugOut("signature", signature); signingStrategy.writeSignature(signature, request, requestParameters); OAuth.debugOut("Auth header", request.getHeader("Authorization")); OAuth.debugOut("Request URL", request.getRequestUrl()); return request; } public HttpRequest sign(Object request) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException { return sign(wrap(request)); } public String sign(String url) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException { HttpRequest request = new UrlStringRequestAdapter(url); // switch to URL signing SigningStrategy oldStrategy = this.signingStrategy; this.signingStrategy = new QueryStringSigningStrategy(); sign(request); // revert to old strategy this.signingStrategy = oldStrategy; return request.getRequestUrl(); } /** * Adapts the given request object to a Signpost {@link HttpRequest}. How * this is done depends on the consumer implementation. * * @param request * the native HTTP request instance * @return the adapted request */ protected abstract HttpRequest wrap(Object request); public void setTokenWithSecret(String token, String tokenSecret) { this.token = token; messageSigner.setTokenSecret(tokenSecret); } public String getToken() { return token; } public String getTokenSecret() { return messageSigner.getTokenSecret(); } public String getConsumerKey() { return this.consumerKey; } public String getConsumerSecret() { return this.consumerSecret; } /** * <p> * Helper method that adds any OAuth parameters to the given request * parameters which are missing from the current request but required for * signing. A good example is the oauth_nonce parameter, which is typically * not provided by the client in advance. * </p> * <p> * It's probably not a very good idea to override this method. If you want * to generate different nonces or timestamps, override * {@link #generateNonce()} or {@link #generateTimestamp()} instead. * </p> * * @param out * the request parameter which should be completed */ protected void completeOAuthParameters(HttpParameters out) { if (!out.containsKey(OAuth.OAUTH_CONSUMER_KEY)) { out.put(OAuth.OAUTH_CONSUMER_KEY, consumerKey, true); } if (!out.containsKey(OAuth.OAUTH_SIGNATURE_METHOD)) { out.put(OAuth.OAUTH_SIGNATURE_METHOD, messageSigner.getSignatureMethod(), true); } if (!out.containsKey(OAuth.OAUTH_TIMESTAMP)) { out.put(OAuth.OAUTH_TIMESTAMP, generateTimestamp(), true); } if (!out.containsKey(OAuth.OAUTH_NONCE)) { out.put(OAuth.OAUTH_NONCE, generateNonce(), true); } if (!out.containsKey(OAuth.OAUTH_VERSION)) { out.put(OAuth.OAUTH_VERSION, OAuth.VERSION_1_0, true); } if (!out.containsKey(OAuth.OAUTH_TOKEN)) { if (token != null && !token.equals("") || sendEmptyTokens) { out.put(OAuth.OAUTH_TOKEN, token, true); } } } public HttpParameters getRequestParameters() { return requestParameters; } public void setSendEmptyTokens(boolean enable) { this.sendEmptyTokens = enable; } /** * Collects OAuth Authorization header parameters as per OAuth Core 1.0 spec * section 9.1.1 */ protected void collectHeaderParameters(HttpRequest request, HttpParameters out) { HttpParameters headerParams = OAuth.oauthHeaderToParamsMap(request.getHeader(OAuth.HTTP_AUTHORIZATION_HEADER)); out.putAll(headerParams, false); } /** * Collects x-www-form-urlencoded body parameters as per OAuth Core 1.0 spec * section 9.1.1 */ protected void collectBodyParameters(HttpRequest request, HttpParameters out) throws IOException { // collect x-www-form-urlencoded body params String contentType = request.getContentType(); if (contentType != null && contentType.startsWith(OAuth.FORM_ENCODED)) { InputStream payload = request.getMessagePayload(); out.putAll(OAuth.decodeForm(payload), true); } } /** * Collects HTTP GET query string parameters as per OAuth Core 1.0 spec * section 9.1.1 */ protected void collectQueryParameters(HttpRequest request, HttpParameters out) { String url = request.getRequestUrl(); int q = url.indexOf('?'); if (q >= 0) { // Combine the URL query string with the other parameters: out.putAll(OAuth.decodeForm(url.substring(q + 1)), true); } } protected String generateTimestamp() { return Long.toString(System.currentTimeMillis() / 1000L); } protected String generateNonce() { return Long.toString(new Random().nextLong()); } }
Java
package oauth.signpost; import oauth.signpost.http.HttpRequest; import oauth.signpost.http.HttpResponse; /** * Provides hooks into the token request handling procedure executed by * {@link OAuthProvider}. * * @author Matthias Kaeppler */ public interface OAuthProviderListener { /** * Called after the request has been created and default headers added, but * before the request has been signed. * * @param request * the request to be sent * @throws Exception */ void prepareRequest(HttpRequest request) throws Exception; /** * Called after the request has been signed, but before it's being sent. * * @param request * the request to be sent * @throws Exception */ void prepareSubmission(HttpRequest request) throws Exception; /** * Called when the server response has been received. You can implement this * to manually handle the response data. * * @param request * the request that was sent * @param response * the response that was received * @return returning true means you have handled the response, and the * provider will return immediately. Return false to let the event * propagate and let the provider execute its default response * handling. * @throws Exception */ boolean onResponseReceived(HttpRequest request, HttpResponse response) throws Exception; }
Java
/* Copyright (c) 2008, 2009 Netflix, Matthias Kaeppler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.signpost; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.URLDecoder; import java.util.Collection; import java.util.HashMap; import java.util.Map; import oauth.signpost.http.HttpParameters; import com.google.gdata.util.common.base.PercentEscaper; public class OAuth { public static final String VERSION_1_0 = "1.0"; public static final String ENCODING = "UTF-8"; public static final String FORM_ENCODED = "application/x-www-form-urlencoded"; public static final String HTTP_AUTHORIZATION_HEADER = "Authorization"; public static final String OAUTH_CONSUMER_KEY = "oauth_consumer_key"; public static final String OAUTH_TOKEN = "oauth_token"; public static final String OAUTH_TOKEN_SECRET = "oauth_token_secret"; public static final String OAUTH_SIGNATURE_METHOD = "oauth_signature_method"; public static final String OAUTH_SIGNATURE = "oauth_signature"; public static final String OAUTH_TIMESTAMP = "oauth_timestamp"; public static final String OAUTH_NONCE = "oauth_nonce"; public static final String OAUTH_VERSION = "oauth_version"; public static final String OAUTH_CALLBACK = "oauth_callback"; public static final String OAUTH_CALLBACK_CONFIRMED = "oauth_callback_confirmed"; public static final String OAUTH_VERIFIER = "oauth_verifier"; /** * Pass this value as the callback "url" upon retrieving a request token if * your application cannot receive callbacks (e.g. because it's a desktop * app). This will tell the service provider that verification happens * out-of-band, which basically means that it will generate a PIN code (the * OAuth verifier) and display that to your user. You must obtain this code * from your user and pass it to * {@link OAuthProvider#retrieveAccessToken(OAuthConsumer, String)} in order * to complete the token handshake. */ public static final String OUT_OF_BAND = "oob"; private static final PercentEscaper percentEncoder = new PercentEscaper( "-._~", false); public static String percentEncode(String s) { if (s == null) { return ""; } return percentEncoder.escape(s); } public static String percentDecode(String s) { try { if (s == null) { return ""; } return URLDecoder.decode(s, ENCODING); // This implements http://oauth.pbwiki.com/FlexibleDecoding } catch (java.io.UnsupportedEncodingException wow) { throw new RuntimeException(wow.getMessage(), wow); } } /** * Construct a x-www-form-urlencoded document containing the given sequence * of name/value pairs. Use OAuth percent encoding (not exactly the encoding * mandated by x-www-form-urlencoded). */ public static <T extends Map.Entry<String, String>> void formEncode(Collection<T> parameters, OutputStream into) throws IOException { if (parameters != null) { boolean first = true; for (Map.Entry<String, String> entry : parameters) { if (first) { first = false; } else { into.write('&'); } into.write(percentEncode(safeToString(entry.getKey())).getBytes()); into.write('='); into.write(percentEncode(safeToString(entry.getValue())).getBytes()); } } } /** * Construct a x-www-form-urlencoded document containing the given sequence * of name/value pairs. Use OAuth percent encoding (not exactly the encoding * mandated by x-www-form-urlencoded). */ public static <T extends Map.Entry<String, String>> String formEncode(Collection<T> parameters) throws IOException { ByteArrayOutputStream b = new ByteArrayOutputStream(); formEncode(parameters, b); return new String(b.toByteArray()); } /** Parse a form-urlencoded document. */ public static HttpParameters decodeForm(String form) { HttpParameters params = new HttpParameters(); if (isEmpty(form)) { return params; } for (String nvp : form.split("\\&")) { int equals = nvp.indexOf('='); String name; String value; if (equals < 0) { name = percentDecode(nvp); value = null; } else { name = percentDecode(nvp.substring(0, equals)); value = percentDecode(nvp.substring(equals + 1)); } params.put(name, value); } return params; } public static HttpParameters decodeForm(InputStream content) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader( content)); StringBuilder sb = new StringBuilder(); String line = reader.readLine(); while (line != null) { sb.append(line); line = reader.readLine(); } return decodeForm(sb.toString()); } /** * Construct a Map containing a copy of the given parameters. If several * parameters have the same name, the Map will contain the first value, * only. */ public static <T extends Map.Entry<String, String>> Map<String, String> toMap(Collection<T> from) { HashMap<String, String> map = new HashMap<String, String>(); if (from != null) { for (Map.Entry<String, String> entry : from) { String key = entry.getKey(); if (!map.containsKey(key)) { map.put(key, entry.getValue()); } } } return map; } public static final String safeToString(Object from) { return (from == null) ? null : from.toString(); } public static boolean isEmpty(String str) { return (str == null) || (str.length() == 0); } /** * Appends a list of key/value pairs to the given URL, e.g.: * * <pre> * String url = OAuth.addQueryParameters(&quot;http://example.com?a=1&quot;, b, 2, c, 3); * </pre> * * which yields: * * <pre> * http://example.com?a=1&b=2&c=3 * </pre> * * All parameters will be encoded according to OAuth's percent encoding * rules. * * @param url * the URL * @param kvPairs * the list of key/value pairs * @return */ public static String addQueryParameters(String url, String... kvPairs) { String queryDelim = url.contains("?") ? "&" : "?"; StringBuilder sb = new StringBuilder(url + queryDelim); for (int i = 0; i < kvPairs.length; i += 2) { if (i > 0) { sb.append("&"); } sb.append(OAuth.percentEncode(kvPairs[i]) + "=" + OAuth.percentEncode(kvPairs[i + 1])); } return sb.toString(); } public static String addQueryParameters(String url, Map<String, String> params) { String[] kvPairs = new String[params.size() * 2]; int idx = 0; for (String key : params.keySet()) { kvPairs[idx] = key; kvPairs[idx + 1] = params.get(key); idx += 2; } return addQueryParameters(url, kvPairs); } /** * Builds an OAuth header from the given list of header fields. All * parameters starting in 'oauth_*' will be percent encoded. * * <pre> * String authHeader = OAuth.prepareOAuthHeader(&quot;realm&quot;, &quot;http://example.com&quot;, &quot;oauth_token&quot;, &quot;x%y&quot;); * </pre> * * which yields: * * <pre> * OAuth realm="http://example.com", oauth_token="x%25y" * </pre> * * @param kvPairs * the list of key/value pairs * @return a string eligible to be used as an OAuth HTTP Authorization * header. */ public static String prepareOAuthHeader(String... kvPairs) { StringBuilder sb = new StringBuilder("OAuth "); for (int i = 0; i < kvPairs.length; i += 2) { if (i > 0) { sb.append(", "); } String value = kvPairs[i].startsWith("oauth_") ? OAuth .percentEncode(kvPairs[i + 1]) : kvPairs[i + 1]; sb.append(OAuth.percentEncode(kvPairs[i]) + "=\"" + value + "\""); } return sb.toString(); } public static HttpParameters oauthHeaderToParamsMap(String oauthHeader) { HttpParameters params = new HttpParameters(); if (oauthHeader == null || !oauthHeader.startsWith("OAuth ")) { return params; } oauthHeader = oauthHeader.substring("OAuth ".length()); String[] elements = oauthHeader.split(","); for (String keyValuePair : elements) { String[] keyValue = keyValuePair.split("="); params.put(keyValue[0].trim(), keyValue[1].replace("\"", "").trim()); } return params; } /** * Helper method to concatenate a parameter and its value to a pair that can * be used in an HTTP header. This method percent encodes both parts before * joining them. * * @param name * the OAuth parameter name, e.g. oauth_token * @param value * the OAuth parameter value, e.g. 'hello oauth' * @return a name/value pair, e.g. oauth_token="hello%20oauth" */ public static String toHeaderElement(String name, String value) { return OAuth.percentEncode(name) + "=\"" + OAuth.percentEncode(value) + "\""; } public static void debugOut(String key, String value) { if (System.getProperty("debug") != null) { System.out.println("[SIGNPOST] " + key + ": " + value); } } }
Java
/* * Copyright (c) 2009 Matthias Kaeppler Licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law * or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package oauth.signpost; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.exception.OAuthNotAuthorizedException; import oauth.signpost.http.HttpParameters; import oauth.signpost.http.HttpRequest; import oauth.signpost.http.HttpResponse; /** * ABC for all provider implementations. If you're writing a custom provider, * you will probably inherit from this class, since it takes a lot of work from * you. * * @author Matthias Kaeppler */ public abstract class AbstractOAuthProvider implements OAuthProvider { private static final long serialVersionUID = 1L; private String requestTokenEndpointUrl; private String accessTokenEndpointUrl; private String authorizationWebsiteUrl; private HttpParameters responseParameters; private Map<String, String> defaultHeaders; private boolean isOAuth10a; private transient OAuthProviderListener listener; public AbstractOAuthProvider(String requestTokenEndpointUrl, String accessTokenEndpointUrl, String authorizationWebsiteUrl) { this.requestTokenEndpointUrl = requestTokenEndpointUrl; this.accessTokenEndpointUrl = accessTokenEndpointUrl; this.authorizationWebsiteUrl = authorizationWebsiteUrl; this.responseParameters = new HttpParameters(); this.defaultHeaders = new HashMap<String, String>(); } public String retrieveRequestToken(OAuthConsumer consumer, String callbackUrl) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException { // invalidate current credentials, if any consumer.setTokenWithSecret(null, null); // 1.0a expects the callback to be sent while getting the request token. // 1.0 service providers would simply ignore this parameter. retrieveToken(consumer, requestTokenEndpointUrl, OAuth.OAUTH_CALLBACK, callbackUrl); String callbackConfirmed = responseParameters.getFirst(OAuth.OAUTH_CALLBACK_CONFIRMED); responseParameters.remove(OAuth.OAUTH_CALLBACK_CONFIRMED); isOAuth10a = Boolean.TRUE.toString().equals(callbackConfirmed); // 1.0 service providers expect the callback as part of the auth URL, // Do not send when 1.0a. if (isOAuth10a) { return OAuth.addQueryParameters(authorizationWebsiteUrl, OAuth.OAUTH_TOKEN, consumer.getToken()); } else { return OAuth.addQueryParameters(authorizationWebsiteUrl, OAuth.OAUTH_TOKEN, consumer.getToken(), OAuth.OAUTH_CALLBACK, callbackUrl); } } public String retrieveRequestTokenForTencent(OAuthConsumer consumer, String callbackUrl) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException { consumer.setTokenWithSecret(null, null); retrieveTokenForTencent(consumer, requestTokenEndpointUrl, OAuth.OAUTH_CALLBACK, callbackUrl); String callbackConfirmed = responseParameters.getFirst(OAuth.OAUTH_CALLBACK_CONFIRMED); responseParameters.remove(OAuth.OAUTH_CALLBACK_CONFIRMED); isOAuth10a = Boolean.TRUE.toString().equals(callbackConfirmed); if (isOAuth10a) { return OAuth.addQueryParameters(authorizationWebsiteUrl, OAuth.OAUTH_TOKEN, consumer.getToken()); } else { return OAuth.addQueryParameters(authorizationWebsiteUrl, OAuth.OAUTH_TOKEN, consumer.getToken(), OAuth.OAUTH_CALLBACK, callbackUrl); } } public void retrieveAccessToken(OAuthConsumer consumer, String oauthVerifier) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException { if (consumer.getToken() == null || consumer.getTokenSecret() == null) { throw new OAuthExpectationFailedException( "Authorized request token or token secret not set. " + "Did you retrieve an authorized request token before?"); } if (isOAuth10a && oauthVerifier != null) { retrieveToken(consumer, accessTokenEndpointUrl, OAuth.OAUTH_VERIFIER, oauthVerifier); } else { retrieveToken(consumer, accessTokenEndpointUrl); } } public void retrieveAccessTokenForTencent(OAuthConsumer consumer, String oauthVerifier) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException { if (consumer.getToken() == null || consumer.getTokenSecret() == null) { throw new OAuthExpectationFailedException( "Authorized request token or token secret not set. " + "Did you retrieve an authorized request token before?"); } if (isOAuth10a && oauthVerifier != null) { retrieveTokenForTencent(consumer, accessTokenEndpointUrl, OAuth.OAUTH_VERIFIER, oauthVerifier); } else { retrieveTokenForTencent(consumer, accessTokenEndpointUrl); } } /** * <p> * Implemented by subclasses. The responsibility of this method is to * contact the service provider at the given endpoint URL and fetch a * request or access token. What kind of token is retrieved solely depends * on the URL being used. * </p> * <p> * Correct implementations of this method must guarantee the following * post-conditions: * <ul> * <li>the {@link OAuthConsumer} passed to this method must have a valid * {@link OAuth#OAUTH_TOKEN} and {@link OAuth#OAUTH_TOKEN_SECRET} set by * calling {@link OAuthConsumer#setTokenWithSecret(String, String)}</li> * <li>{@link #getResponseParameters()} must return the set of query * parameters served by the service provider in the token response, with all * OAuth specific parameters being removed</li> * </ul> * </p> * * @param consumer * the {@link OAuthConsumer} that should be used to sign the request * @param endpointUrl * the URL at which the service provider serves the OAuth token that * is to be fetched * @param additionalParameters * you can pass parameters here (typically OAuth parameters such as * oauth_callback or oauth_verifier) which will go directly into the * signer, i.e. you don't have to put them into the request first, * just so the consumer pull them out again. Pass them sequentially * in key/value order. * @throws OAuthMessageSignerException * if signing the token request fails * @throws OAuthCommunicationException * if a network communication error occurs * @throws OAuthNotAuthorizedException * if the server replies 401 - Unauthorized * @throws OAuthExpectationFailedException * if an expectation has failed, e.g. because the server didn't * reply in the expected format */ protected void retrieveToken(OAuthConsumer consumer, String endpointUrl, String... additionalParameters) throws OAuthMessageSignerException, OAuthCommunicationException, OAuthNotAuthorizedException, OAuthExpectationFailedException { Map<String, String> defaultHeaders = getRequestHeaders(); if (consumer.getConsumerKey() == null || consumer.getConsumerSecret() == null) { throw new OAuthExpectationFailedException("Consumer key or secret not set"); } HttpRequest request = null; HttpResponse response = null; try { request = createRequest(endpointUrl); for (String header : defaultHeaders.keySet()) { request.setHeader(header, defaultHeaders.get(header)); } if (additionalParameters != null) { HttpParameters httpParams = new HttpParameters(); httpParams.putAll(additionalParameters, true); consumer.setAdditionalParameters(httpParams); } if (this.listener != null) { this.listener.prepareRequest(request); } consumer.sign(request); if (this.listener != null) { this.listener.prepareSubmission(request); } response = sendRequest(request); int statusCode = response.getStatusCode(); boolean requestHandled = false; if (this.listener != null) { requestHandled = this.listener.onResponseReceived(request, response); } if (requestHandled) { return; } if (statusCode >= 300) { handleUnexpectedResponse(statusCode, response); } HttpParameters responseParams = OAuth.decodeForm(response.getContent()); String token = responseParams.getFirst(OAuth.OAUTH_TOKEN); String secret = responseParams.getFirst(OAuth.OAUTH_TOKEN_SECRET); responseParams.remove(OAuth.OAUTH_TOKEN); responseParams.remove(OAuth.OAUTH_TOKEN_SECRET); setResponseParameters(responseParams); if (token == null || secret == null) { throw new OAuthExpectationFailedException( "Request token or token secret not set in server reply. " + "The service provider you use is probably buggy."); } consumer.setTokenWithSecret(token, secret); } catch (OAuthNotAuthorizedException e) { throw e; } catch (OAuthExpectationFailedException e) { throw e; } catch (Exception e) { throw new OAuthCommunicationException(e); } finally { try { closeConnection(request, response); } catch (Exception e) { throw new OAuthCommunicationException(e); } } } protected void retrieveTokenForTencent(OAuthConsumer consumer, String endpointUrl, String... additionalParameters) throws OAuthMessageSignerException, OAuthCommunicationException, OAuthNotAuthorizedException, OAuthExpectationFailedException { Map<String, String> defaultHeaders = getRequestHeaders(); if (consumer.getConsumerKey() == null || consumer.getConsumerSecret() == null) { throw new OAuthExpectationFailedException("Consumer key or secret not set"); } HttpRequest request = null; HttpResponse response = null; try { request = createRequestForTencent(endpointUrl); for (String header : defaultHeaders.keySet()) { request.setHeader(header, defaultHeaders.get(header)); } if (additionalParameters != null) { HttpParameters httpParams = new HttpParameters(); httpParams.putAll(additionalParameters, true); consumer.setAdditionalParameters(httpParams); } if (this.listener != null) { this.listener.prepareRequest(request); } consumer.sign(request); if (this.listener != null) { this.listener.prepareSubmission(request); } response = sendRequestForTencent(request); int statusCode = response.getStatusCode(); boolean requestHandled = false; if (this.listener != null) { requestHandled = this.listener.onResponseReceived(request, response); } if (requestHandled) { return; } if (statusCode >= 300) { handleUnexpectedResponse(statusCode, response); } HttpParameters responseParams = OAuth.decodeForm(response.getContent()); String token = responseParams.getFirst(OAuth.OAUTH_TOKEN); String secret = responseParams.getFirst(OAuth.OAUTH_TOKEN_SECRET); responseParams.remove(OAuth.OAUTH_TOKEN); responseParams.remove(OAuth.OAUTH_TOKEN_SECRET); setResponseParameters(responseParams); if (token == null || secret == null) { throw new OAuthExpectationFailedException( "Request token or token secret not set in server reply. " + "The service provider you use is probably buggy."); } consumer.setTokenWithSecret(token, secret); } catch (OAuthNotAuthorizedException e) { throw e; } catch (OAuthExpectationFailedException e) { throw e; } catch (Exception e) { throw new OAuthCommunicationException(e); } finally { try { closeConnection(request, response); } catch (Exception e) { throw new OAuthCommunicationException(e); } } } protected void handleUnexpectedResponse(int statusCode, HttpResponse response) throws Exception { if (response == null) { return; } BufferedReader reader = new BufferedReader(new InputStreamReader(response.getContent())); StringBuilder responseBody = new StringBuilder(); String line = reader.readLine(); while (line != null) { responseBody.append(line); line = reader.readLine(); } switch (statusCode) { case 401: throw new OAuthNotAuthorizedException(responseBody.toString()); default: throw new OAuthCommunicationException("Service provider responded in error: " + statusCode + " (" + response.getReasonPhrase() + ")", responseBody.toString()); } } /** * Overrride this method if you want to customize the logic for building a * request object for the given endpoint URL. * * @param endpointUrl * the URL to which the request will go * @return the request object * @throws Exception * if something breaks */ protected abstract HttpRequest createRequest(String endpointUrl) throws Exception; protected abstract HttpRequest createRequestForTencent(String endpointUrl) throws Exception; /** * Override this method if you want to customize the logic for how the given * request is sent to the server. * * @param request * the request to send * @return the response to the request * @throws Exception * if something breaks */ protected abstract HttpResponse sendRequest(HttpRequest request) throws Exception; protected abstract HttpResponse sendRequestForTencent(HttpRequest request) throws Exception; /** * Called when the connection is being finalized after receiving the * response. Use this to do any cleanup / resource freeing. * * @param request * the request that has been sent * @param response * the response that has been received * @throws Exception * if something breaks */ protected void closeConnection(HttpRequest request, HttpResponse response) throws Exception { // NOP } public HttpParameters getResponseParameters() { return responseParameters; } /** * Returns a single query parameter as served by the service provider in a * token reply. You must call {@link #setResponseParameters} with the set of * parameters before using this method. * * @param key * the parameter name * @return the parameter value */ protected String getResponseParameter(String key) { return responseParameters.getFirst(key); } public void setResponseParameters(HttpParameters parameters) { this.responseParameters = parameters; } public void setOAuth10a(boolean isOAuth10aProvider) { this.isOAuth10a = isOAuth10aProvider; } public boolean isOAuth10a() { return isOAuth10a; } public String getRequestTokenEndpointUrl() { return this.requestTokenEndpointUrl; } public String getAccessTokenEndpointUrl() { return this.accessTokenEndpointUrl; } public String getAuthorizationWebsiteUrl() { return this.authorizationWebsiteUrl; } public void setRequestHeader(String header, String value) { defaultHeaders.put(header, value); } public Map<String, String> getRequestHeaders() { return defaultHeaders; } public void setListener(OAuthProviderListener listener) { this.listener = listener; } public void removeListener(OAuthProviderListener listener) { this.listener = null; } }
Java
/* Copyright (c) 2009 Matthias Kaeppler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.signpost; import java.io.Serializable; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.http.HttpParameters; import oauth.signpost.http.HttpRequest; import oauth.signpost.signature.AuthorizationHeaderSigningStrategy; import oauth.signpost.signature.HmacSha1MessageSigner; import oauth.signpost.signature.OAuthMessageSigner; import oauth.signpost.signature.PlainTextMessageSigner; import oauth.signpost.signature.QueryStringSigningStrategy; import oauth.signpost.signature.SigningStrategy; /** * <p> * Exposes a simple interface to sign HTTP requests using a given OAuth token * and secret. Refer to {@link OAuthProvider} how to retrieve a valid token and * token secret. * </p> * <p> * HTTP messages are signed as follows: * <p> * * <pre> * // exchange the arguments with the actual token/secret pair * OAuthConsumer consumer = new DefaultOAuthConsumer(&quot;1234&quot;, &quot;5678&quot;); * * URL url = new URL(&quot;http://example.com/protected.xml&quot;); * HttpURLConnection request = (HttpURLConnection) url.openConnection(); * * consumer.sign(request); * * request.connect(); * </pre> * * </p> * </p> * * @author Matthias Kaeppler */ public interface OAuthConsumer extends Serializable { /** * Sets the message signer that should be used to generate the OAuth * signature. * * @param messageSigner * the signer * @see HmacSha1MessageSigner * @see PlainTextMessageSigner */ public void setMessageSigner(OAuthMessageSigner messageSigner); /** * Allows you to add parameters (typically OAuth parameters such as * oauth_callback or oauth_verifier) which will go directly into the signer, * i.e. you don't have to put them into the request first. The consumer's * {@link SigningStrategy} will then take care of writing them to the * correct part of the request before it is sent. Note that these parameters * are expected to already be percent encoded -- they will be simply merged * as-is. * * @param additionalParameters * the parameters */ public void setAdditionalParameters(HttpParameters additionalParameters); /** * Defines which strategy should be used to write a signature to an HTTP * request. * * @param signingStrategy * the strategy * @see AuthorizationHeaderSigningStrategy * @see QueryStringSigningStrategy */ public void setSigningStrategy(SigningStrategy signingStrategy); /** * <p> * Causes the consumer to always include the oauth_token parameter to be * sent, even if blank. If you're seeing 401s during calls to * {@link OAuthProvider#retrieveRequestToken}, try setting this to true. * </p> * * @param enable * true or false */ public void setSendEmptyTokens(boolean enable); /** * Signs the given HTTP request by writing an OAuth signature (and other * required OAuth parameters) to it. Where these parameters are written * depends on the current {@link SigningStrategy}. * * @param request * the request to sign * @return the request object passed as an argument * @throws OAuthMessageSignerException * @throws OAuthExpectationFailedException * @throws OAuthCommunicationException */ public HttpRequest sign(HttpRequest request) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException; /** * <p> * Signs the given HTTP request by writing an OAuth signature (and other * required OAuth parameters) to it. Where these parameters are written * depends on the current {@link SigningStrategy}. * </p> * This method accepts HTTP library specific request objects; the consumer * implementation must ensure that only those request types are passed which * it supports. * * @param request * the request to sign * @return the request object passed as an argument * @throws OAuthMessageSignerException * @throws OAuthExpectationFailedException * @throws OAuthCommunicationException */ public HttpRequest sign(Object request) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException; /** * <p> * "Signs" the given URL by appending all OAuth parameters to it which are * required for message signing. The assumed HTTP method is GET. * Essentially, this is equivalent to signing an HTTP GET request, but it * can be useful if your application requires clickable links to protected * resources, i.e. when your application does not have access to the actual * request that is being sent. * </p> * * @param url * the input URL. May have query parameters. * @return the input URL, with all necessary OAuth parameters attached as a * query string. Existing query parameters are preserved. * @throws OAuthMessageSignerException * @throws OAuthExpectationFailedException * @throws OAuthCommunicationException */ public String sign(String url) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException; /** * Sets the OAuth token and token secret used for message signing. * * @param token * the token * @param tokenSecret * the token secret */ public void setTokenWithSecret(String token, String tokenSecret); public String getToken(); public String getTokenSecret(); public String getConsumerKey(); public String getConsumerSecret(); /** * Returns all parameters collected from the HTTP request during message * signing (this means the return value may be NULL before a call to * {@link #sign}), plus all required OAuth parameters that were added * because the request didn't contain them beforehand. In other words, this * is the exact set of parameters that were used for creating the message * signature. * * @return the request parameters used for message signing */ public HttpParameters getRequestParameters(); }
Java
/* Copyright (c) 2008, 2009 Netflix, Matthias Kaeppler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.signpost.http; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import oauth.signpost.OAuth; /** * A multi-map of HTTP request parameters. Each key references a * {@link SortedSet} of parameters collected from the request during message * signing. Parameter values are sorted as per {@linkplain http * ://oauth.net/core/1.0a/#anchor13}. Every key/value pair will be * percent-encoded upon insertion. This class has special semantics tailored to * being useful for message signing; it's not a general purpose collection class * to handle request parameters. * * @author Matthias Kaeppler */ @SuppressWarnings("serial") public class HttpParameters implements Map<String, SortedSet<String>>, Serializable { private TreeMap<String, SortedSet<String>> wrappedMap = new TreeMap<String, SortedSet<String>>(); public SortedSet<String> put(String key, SortedSet<String> value) { return wrappedMap.put(key, value); } public SortedSet<String> put(String key, SortedSet<String> values, boolean percentEncode) { if (percentEncode) { remove(key); for (String v : values) { put(key, v, true); } return get(key); } else { return wrappedMap.put(key, values); } } /** * Convenience method to add a single value for the parameter specified by * 'key'. * * @param key * the parameter name * @param value * the parameter value * @return the value */ public String put(String key, String value) { return put(key, value, false); } /** * Convenience method to add a single value for the parameter specified by * 'key'. * * @param key * the parameter name * @param value * the parameter value * @param percentEncode * whether key and value should be percent encoded before being * inserted into the map * @return the value */ public String put(String key, String value, boolean percentEncode) { SortedSet<String> values = wrappedMap.get(key); if (values == null) { values = new TreeSet<String>(); wrappedMap.put(percentEncode ? OAuth.percentEncode(key) : key, values); } if (value != null) { value = percentEncode ? OAuth.percentEncode(value) : value; values.add(value); } return value; } /** * Convenience method to allow for storing null values. {@link #put} doesn't * allow null values, because that would be ambiguous. * * @param key * the parameter name * @param nullString * can be anything, but probably... null? * @return null */ public String putNull(String key, String nullString) { return put(key, nullString); } public void putAll(Map<? extends String, ? extends SortedSet<String>> m) { wrappedMap.putAll(m); } public void putAll(Map<? extends String, ? extends SortedSet<String>> m, boolean percentEncode) { if (percentEncode) { for (String key : m.keySet()) { put(key, m.get(key), true); } } else { wrappedMap.putAll(m); } } public void putAll(String[] keyValuePairs, boolean percentEncode) { for (int i = 0; i < keyValuePairs.length - 1; i += 2) { this.put(keyValuePairs[i], keyValuePairs[i + 1], percentEncode); } } /** * Convenience method to merge a Map<String, List<String>>. * * @param m * the map */ public void putMap(Map<String, List<String>> m) { for (String key : m.keySet()) { SortedSet<String> vals = get(key); if (vals == null) { vals = new TreeSet<String>(); put(key, vals); } vals.addAll(m.get(key)); } } public SortedSet<String> get(Object key) { return wrappedMap.get(key); } /** * Convenience method for {@link #getFirst(key, false)}. * * @param key * the parameter name (must be percent encoded if it contains unsafe * characters!) * @return the first value found for this parameter */ public String getFirst(Object key) { return getFirst(key, false); } /** * Returns the first value from the set of all values for the given * parameter name. If the key passed to this method contains special * characters, you MUST first percent encode it using * {@link OAuth#percentEncode(String)}, otherwise the lookup will fail * (that's because upon storing values in this map, keys get * percent-encoded). * * @param key * the parameter name (must be percent encoded if it contains unsafe * characters!) * @param percentDecode * whether the value being retrieved should be percent decoded * @return the first value found for this parameter */ public String getFirst(Object key, boolean percentDecode) { SortedSet<String> values = wrappedMap.get(key); if (values == null || values.isEmpty()) { return null; } String value = values.first(); return percentDecode ? OAuth.percentDecode(value) : value; } /** * Concatenates all values for the given key to a list of key/value pairs * suitable for use in a URL query string. * * @param key * the parameter name * @return the query string */ public String getAsQueryString(Object key) { StringBuilder sb = new StringBuilder(); key = OAuth.percentEncode((String) key); Set<String> values = wrappedMap.get(key); if (values == null) { return key + "="; } Iterator<String> iter = values.iterator(); while (iter.hasNext()) { sb.append(key + "=" + iter.next()); if (iter.hasNext()) { sb.append("&"); } } return sb.toString(); } public String getAsHeaderElement(String key) { String value = getFirst(key); if (value == null) { return null; } return key + "=\"" + value + "\""; } public boolean containsKey(Object key) { return wrappedMap.containsKey(key); } public boolean containsValue(Object value) { for (Set<String> values : wrappedMap.values()) { if (values.contains(value)) { return true; } } return false; } public int size() { int count = 0; for (String key : wrappedMap.keySet()) { count += wrappedMap.get(key).size(); } return count; } public boolean isEmpty() { return wrappedMap.isEmpty(); } public void clear() { wrappedMap.clear(); } public SortedSet<String> remove(Object key) { return wrappedMap.remove(key); } public Set<String> keySet() { return wrappedMap.keySet(); } public Collection<SortedSet<String>> values() { return wrappedMap.values(); } public Set<java.util.Map.Entry<String, SortedSet<String>>> entrySet() { return wrappedMap.entrySet(); } }
Java
package oauth.signpost.http; import java.io.IOException; import java.io.InputStream; public interface HttpResponse { int getStatusCode() throws IOException; String getReasonPhrase() throws Exception; InputStream getContent() throws IOException; /** * Returns the underlying response object, in case you need to work on it * directly. * * @return the wrapped response object */ Object unwrap(); }
Java
package oauth.signpost.http; import java.io.IOException; import java.io.InputStream; import java.util.Map; import oauth.signpost.OAuthConsumer; import oauth.signpost.basic.HttpURLConnectionRequestAdapter; /** * A concise description of an HTTP request. Contains methods to access all * those parts of an HTTP request which Signpost needs to sign a message. If you * want to extend Signpost to sign a different kind of HTTP request than those * currently supported, you'll have to write an adapter which implements this * interface and a custom {@link OAuthConsumer} which performs the wrapping. * * @see HttpURLConnectionRequestAdapter * @author Matthias Kaeppler */ public interface HttpRequest { String getMethod(); String getRequestUrl(); void setRequestUrl(String url); void setHeader(String name, String value); String getHeader(String name); Map<String, String> getAllHeaders(); InputStream getMessagePayload() throws IOException; String getContentType(); /** * Returns the wrapped request object, in case you must work directly on it. * * @return the wrapped request object */ Object unwrap(); }
Java
/* Copyright (c) 2009 Matthias Kaeppler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.signpost.signature; import java.io.IOException; import java.io.Serializable; import java.io.UnsupportedEncodingException; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.http.HttpParameters; import oauth.signpost.http.HttpRequest; import com.outsourcing.bottle.oauth.Base64; public abstract class OAuthMessageSigner implements Serializable { private static final long serialVersionUID = 4445779788786131202L; private transient Base64 base64; private String consumerSecret; private String tokenSecret; public OAuthMessageSigner() { this.base64 = new Base64(); } public abstract String sign(HttpRequest request, HttpParameters requestParameters) throws OAuthMessageSignerException; public abstract String getSignatureMethod(); public String getConsumerSecret() { return consumerSecret; } public String getTokenSecret() { return tokenSecret; } public void setConsumerSecret(String consumerSecret) { this.consumerSecret = consumerSecret; } public void setTokenSecret(String tokenSecret) { this.tokenSecret = tokenSecret; } @SuppressWarnings("static-access") protected byte[] decodeBase64(String s) { try { return base64.decode(s); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } @SuppressWarnings("static-access") protected String base64Encode(byte[] b) { return new String(base64.encode(b)); } private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.base64 = new Base64(); } }
Java
/* Copyright (c) 2009 Matthias Kaeppler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.signpost.signature; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import oauth.signpost.OAuth; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.http.HttpParameters; import oauth.signpost.http.HttpRequest; @SuppressWarnings("serial") public class HmacSha1MessageSigner extends OAuthMessageSigner { private static final String MAC_NAME = "HmacSHA1"; @Override public String getSignatureMethod() { return "HMAC-SHA1"; } @Override public String sign(HttpRequest request, HttpParameters requestParams) throws OAuthMessageSignerException { try { String keyString = OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret()); byte[] keyBytes = keyString.getBytes(OAuth.ENCODING); SecretKey key = new SecretKeySpec(keyBytes, MAC_NAME); Mac mac = Mac.getInstance(MAC_NAME); mac.init(key); String sbs = new SignatureBaseString(request, requestParams).generate(); OAuth.debugOut("SBS", sbs); byte[] text = sbs.getBytes(OAuth.ENCODING); return base64Encode(mac.doFinal(text)).trim(); } catch (GeneralSecurityException e) { throw new OAuthMessageSignerException(e); } catch (UnsupportedEncodingException e) { throw new OAuthMessageSignerException(e); } } }
Java
package oauth.signpost.signature; import java.io.Serializable; import oauth.signpost.http.HttpParameters; import oauth.signpost.http.HttpRequest; /** * <p> * Defines how an OAuth signature string is written to a request. * </p> * <p> * Unlike {@link OAuthMessageSigner}, which is concerned with <i>how</i> to * generate a signature, this class is concered with <i>where</i> to write it * (e.g. HTTP header or query string). * </p> * * @author Matthias Kaeppler */ public interface SigningStrategy extends Serializable { /** * Writes an OAuth signature and all remaining required parameters to an * HTTP message. * * @param signature * the signature to write * @param request * the request to sign * @param requestParameters * the request parameters * @return whatever has been written to the request, e.g. an Authorization * header field */ String writeSignature(String signature, HttpRequest request, HttpParameters requestParameters); }
Java
/* Copyright (c) 2009 Matthias Kaeppler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.signpost.signature; import oauth.signpost.OAuth; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.http.HttpParameters; import oauth.signpost.http.HttpRequest; @SuppressWarnings("serial") public class PlainTextMessageSigner extends OAuthMessageSigner { @Override public String getSignatureMethod() { return "PLAINTEXT"; } @Override public String sign(HttpRequest request, HttpParameters requestParams) throws OAuthMessageSignerException { return OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret()); } }
Java
/* * Copyright (c) 2009 Matthias Kaeppler Licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law * or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package oauth.signpost.signature; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Iterator; import oauth.signpost.OAuth; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.http.HttpParameters; import oauth.signpost.http.HttpRequest; public class SignatureBaseString { private HttpRequest request; private HttpParameters requestParameters; /** * Constructs a new SBS instance that will operate on the given request * object and parameter set. * * @param request * the HTTP request * @param requestParameters * the set of request parameters from the Authorization header, query * string and form body */ public SignatureBaseString(HttpRequest request, HttpParameters requestParameters) { this.request = request; this.requestParameters = requestParameters; } /** * Builds the signature base string from the data this instance was * configured with. * * @return the signature base string * @throws OAuthMessageSignerException */ public String generate() throws OAuthMessageSignerException { try { String normalizedUrl = normalizeRequestUrl(); String normalizedParams = normalizeRequestParameters(); return request.getMethod() + '&' + OAuth.percentEncode(normalizedUrl) + '&' + OAuth.percentEncode(normalizedParams); } catch (Exception e) { throw new OAuthMessageSignerException(e); } } public String normalizeRequestUrl() throws URISyntaxException { URI uri = new URI(request.getRequestUrl()); String scheme = uri.getScheme().toLowerCase(); String authority = uri.getAuthority().toLowerCase(); boolean dropPort = (scheme.equals("http") && uri.getPort() == 80) || (scheme.equals("https") && uri.getPort() == 443); if (dropPort) { // find the last : in the authority int index = authority.lastIndexOf(":"); if (index >= 0) { authority = authority.substring(0, index); } } String path = uri.getRawPath(); if (path == null || path.length() <= 0) { path = "/"; // conforms to RFC 2616 section 3.2.2 } // we know that there is no query and no fragment here. return scheme + "://" + authority + path; } /** * Normalizes the set of request parameters this instance was configured * with, as per OAuth spec section 9.1.1. * * @param parameters * the set of request parameters * @return the normalized params string * @throws IOException */ public String normalizeRequestParameters() throws IOException { if (requestParameters == null) { return ""; } StringBuilder sb = new StringBuilder(); Iterator<String> iter = requestParameters.keySet().iterator(); for (int i = 0; iter.hasNext(); i++) { String param = iter.next(); if (OAuth.OAUTH_SIGNATURE.equals(param) || "realm".equals(param)) { continue; } if (i > 0) { sb.append("&"); } sb.append(requestParameters.getAsQueryString(param)); } return sb.toString(); } }
Java
package oauth.signpost.signature; import oauth.signpost.OAuth; import oauth.signpost.http.HttpParameters; import oauth.signpost.http.HttpRequest; /** * Writes to the HTTP Authorization header field. * * @author Matthias Kaeppler */ public class AuthorizationHeaderSigningStrategy implements SigningStrategy { private static final long serialVersionUID = 1L; public String writeSignature(String signature, HttpRequest request, HttpParameters requestParameters) { StringBuilder sb = new StringBuilder(); sb.append("OAuth "); if (requestParameters.containsKey("realm")) { sb.append(requestParameters.getAsHeaderElement("realm")); sb.append(", "); } if (requestParameters.containsKey(OAuth.OAUTH_TOKEN)) { sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_TOKEN)); sb.append(", "); } if (requestParameters.containsKey(OAuth.OAUTH_CALLBACK)) { sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_CALLBACK)); sb.append(", "); } if (requestParameters.containsKey(OAuth.OAUTH_VERIFIER)) { sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_VERIFIER)); sb.append(", "); } sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_CONSUMER_KEY)); sb.append(", "); sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_VERSION)); sb.append(", "); sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_SIGNATURE_METHOD)); sb.append(", "); sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_TIMESTAMP)); sb.append(", "); sb.append(requestParameters.getAsHeaderElement(OAuth.OAUTH_NONCE)); sb.append(", "); sb.append(OAuth.toHeaderElement(OAuth.OAUTH_SIGNATURE, signature)); String header = sb.toString(); request.setHeader(OAuth.HTTP_AUTHORIZATION_HEADER, header); return header; } }
Java
package oauth.signpost.signature; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.conn.ssl.SSLSocketFactory; /** * SSL认证 * @author mzba * */ public class SSLSocketFactoryEx extends SSLSocketFactory { SSLContext sslContext = SSLContext.getInstance("TLS"); public SSLSocketFactoryEx(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); TrustManager tm = new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted( java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } @Override public void checkServerTrusted( java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } }; sslContext.init(null, new TrustManager[] { tm }, null); } @Override public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); } @Override public Socket createSocket() throws IOException { return sslContext.getSocketFactory().createSocket(); } }
Java
package oauth.signpost.signature; import oauth.signpost.OAuth; import oauth.signpost.http.HttpParameters; import oauth.signpost.http.HttpRequest; /** * Writes to a URL query string. <strong>Note that this currently ONLY works * when signing a URL directly, not with HTTP request objects.</strong> That's * because most HTTP request implementations do not allow the client to change * the URL once the request has been instantiated, so there is no way to append * parameters to it. * * @author Matthias Kaeppler */ public class QueryStringSigningStrategy implements SigningStrategy { private static final long serialVersionUID = 1L; public String writeSignature(String signature, HttpRequest request, HttpParameters requestParameters) { // add the signature StringBuilder sb = new StringBuilder(OAuth.addQueryParameters(request.getRequestUrl(), OAuth.OAUTH_SIGNATURE, signature)); // add the optional OAuth parameters if (requestParameters.containsKey(OAuth.OAUTH_TOKEN)) { sb.append("&"); sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_TOKEN)); } if (requestParameters.containsKey(OAuth.OAUTH_CALLBACK)) { sb.append("&"); sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_CALLBACK)); } if (requestParameters.containsKey(OAuth.OAUTH_VERIFIER)) { sb.append("&"); sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_VERIFIER)); } // add the remaining OAuth params sb.append("&"); sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_CONSUMER_KEY)); sb.append("&"); sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_VERSION)); sb.append("&"); sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_SIGNATURE_METHOD)); sb.append("&"); sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_TIMESTAMP)); sb.append("&"); sb.append(requestParameters.getAsQueryString(OAuth.OAUTH_NONCE)); String signedUrl = sb.toString(); request.setRequestUrl(signedUrl); return signedUrl; } }
Java
/* * Copyright (c) 2009 Matthias Kaeppler Licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law * or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package oauth.signpost; import java.io.Serializable; import java.util.Map; import oauth.signpost.basic.DefaultOAuthConsumer; import oauth.signpost.basic.DefaultOAuthProvider; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.exception.OAuthNotAuthorizedException; import oauth.signpost.http.HttpParameters; /** * <p> * Supplies an interface that can be used to retrieve request and access tokens * from an OAuth 1.0(a) service provider. A provider object requires an * {@link OAuthConsumer} to sign the token request message; after a token has * been retrieved, the consumer is automatically updated with the token and the * corresponding secret. * </p> * <p> * To initiate the token exchange, create a new provider instance and configure * it with the URLs the service provider exposes for requesting tokens and * resource authorization, e.g.: * </p> * * <pre> * OAuthProvider provider = new DefaultOAuthProvider(&quot;http://twitter.com/oauth/request_token&quot;, * &quot;http://twitter.com/oauth/access_token&quot;, &quot;http://twitter.com/oauth/authorize&quot;); * </pre> * <p> * Depending on the HTTP library you use, you may need a different provider * type, refer to the website documentation for how to do that. * </p> * <p> * To receive a request token which the user must authorize, you invoke it using * a consumer instance and a callback URL: * </p> * <p> * * <pre> * String url = provider.retrieveRequestToken(consumer, &quot;http://www.example.com/callback&quot;); * </pre> * * </p> * <p> * That url must be opened in a Web browser, where the user can grant access to * the resources in question. If that succeeds, the service provider will * redirect to the callback URL and append the blessed request token. * </p> * <p> * That token must now be exchanged for an access token, as such: * </p> * <p> * * <pre> * provider.retrieveAccessToken(consumer, nullOrVerifierCode); * </pre> * * </p> * <p> * where nullOrVerifierCode is either null if your provided a callback URL in * the previous step, or the pin code issued by the service provider to the user * if the request was out-of-band (cf. {@link OAuth#OUT_OF_BAND}. * </p> * <p> * The consumer used during token handshakes is now ready for signing. * </p> * * @see DefaultOAuthProvider * @see DefaultOAuthConsumer * @see OAuthProviderListener */ public interface OAuthProvider extends Serializable { /** * Queries the service provider for a request token. * <p> * <b>Pre-conditions:</b> the given {@link OAuthConsumer} must have a valid * consumer key and consumer secret already set. * </p> * <p> * <b>Post-conditions:</b> the given {@link OAuthConsumer} will have an * unauthorized request token and token secret set. * </p> * * @param consumer * the {@link OAuthConsumer} that should be used to sign the request * @param callbackUrl * Pass an actual URL if your app can receive callbacks and you want * to get informed about the result of the authorization process. * Pass {@link OAuth.OUT_OF_BAND} if the service provider implements * OAuth 1.0a and your app cannot receive callbacks. Pass null if the * service provider implements OAuth 1.0 and your app cannot receive * callbacks. Please note that some services (among them Twitter) * will fail authorization if you pass a callback URL but register * your application as a desktop app (which would only be able to * handle OOB requests). * @return The URL to which the user must be sent in order to authorize the * consumer. It includes the unauthorized request token (and in the * case of OAuth 1.0, the callback URL -- 1.0a clients send along * with the token request). * @throws OAuthMessageSignerException * if signing the request failed * @throws OAuthNotAuthorizedException * if the service provider rejected the consumer * @throws OAuthExpectationFailedException * if required parameters were not correctly set by the consumer or * service provider * @throws OAuthCommunicationException * if server communication failed */ public String retrieveRequestToken(OAuthConsumer consumer, String callbackUrl) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException; /** * * @param consumer * @param callbackUrl * @return * @throws OAuthMessageSignerException * @throws OAuthNotAuthorizedException * @throws OAuthExpectationFailedException * @throws OAuthCommunicationException */ public String retrieveRequestTokenForTencent(OAuthConsumer consumer, String callbackUrl) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException; /** * Queries the service provider for an access token. * <p> * <b>Pre-conditions:</b> the given {@link OAuthConsumer} must have a valid * consumer key, consumer secret, authorized request token and token secret * already set. * </p> * <p> * <b>Post-conditions:</b> the given {@link OAuthConsumer} will have an * access token and token secret set. * </p> * * @param consumer * the {@link OAuthConsumer} that should be used to sign the request * @param oauthVerifier * <b>NOTE: Only applies to service providers implementing OAuth * 1.0a. Set to null if the service provider is still using OAuth * 1.0.</b> The verification code issued by the service provider * after the the user has granted the consumer authorization. If the * callback method provided in the previous step was * {@link OAuth.OUT_OF_BAND}, then you must ask the user for this * value. If your app has received a callback, the verfication code * was passed as part of that request instead. * @throws OAuthMessageSignerException * if signing the request failed * @throws OAuthNotAuthorizedException * if the service provider rejected the consumer * @throws OAuthExpectationFailedException * if required parameters were not correctly set by the consumer or * service provider * @throws OAuthCommunicationException * if server communication failed */ public void retrieveAccessToken(OAuthConsumer consumer, String oauthVerifier) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException; public void retrieveAccessTokenForTencent(OAuthConsumer consumer, String oauthVerifier) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException; /** * Any additional non-OAuth parameters returned in the response body of a * token request can be obtained through this method. These parameters will * be preserved until the next token request is issued. The return value is * never null. */ public HttpParameters getResponseParameters(); /** * Subclasses must use this setter to preserve any non-OAuth query * parameters contained in the server response. It's the caller's * responsibility that any OAuth parameters be removed beforehand. * * @param parameters * the map of query parameters served by the service provider in the * token response */ public void setResponseParameters(HttpParameters parameters); /** * Use this method to set custom HTTP headers to be used for the requests * which are sent to retrieve tokens. @deprecated THIS METHOD HAS BEEN * DEPRECATED. Use {@link OAuthProviderListener} to customize requests. * * @param header * The header name (e.g. 'WWW-Authenticate') * @param value * The header value (e.g. 'realm=www.example.com') */ @Deprecated public void setRequestHeader(String header, String value); /** * @deprecated THIS METHOD HAS BEEN DEPRECATED. Use * {@link OAuthProviderListener} to customize requests. * @return all request headers set via {@link #setRequestHeader} */ @Deprecated public Map<String, String> getRequestHeaders(); /** * @param isOAuth10aProvider * set to true if the service provider supports OAuth 1.0a. Note that * you need only call this method if you reconstruct a provider * object in between calls to retrieveRequestToken() and * retrieveAccessToken() (i.e. if the object state isn't preserved). * If instead those two methods are called on the same provider * instance, this flag will be deducted automatically based on the * server response during retrieveRequestToken(), so you can simply * ignore this method. */ public void setOAuth10a(boolean isOAuth10aProvider); /** * @return true if the service provider supports OAuth 1.0a. Note that the * value returned here is only meaningful after you have already * performed the token handshake, otherwise there is no way to * determine what version of the OAuth protocol the service provider * implements. */ public boolean isOAuth10a(); public String getRequestTokenEndpointUrl(); public String getAccessTokenEndpointUrl(); public String getAuthorizationWebsiteUrl(); public void setListener(OAuthProviderListener listener); public void removeListener(OAuthProviderListener listener); }
Java
/* Copyright (c) 2009 Matthias Kaeppler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.commons.http; import oauth.signpost.AbstractOAuthConsumer; import oauth.signpost.http.HttpRequest; /** * Supports signing HTTP requests of type {@link org.apache.http.HttpRequest}. * * @author Matthias Kaeppler */ public class CommonsHttpOAuthConsumer extends AbstractOAuthConsumer { private static final long serialVersionUID = 1L; public CommonsHttpOAuthConsumer(String consumerKey, String consumerSecret) { super(consumerKey, consumerSecret); } @Override protected HttpRequest wrap(Object request) { if (!(request instanceof org.apache.http.HttpRequest)) { throw new IllegalArgumentException( "This consumer expects requests of type " + org.apache.http.HttpRequest.class.getCanonicalName()); } return new HttpRequestAdapter((org.apache.http.client.methods.HttpUriRequest) request); } }
Java
package oauth.commons.http; import java.io.IOException; import java.io.InputStream; import oauth.signpost.http.HttpResponse; public class HttpResponseAdapter implements HttpResponse { private org.apache.http.HttpResponse response; public HttpResponseAdapter(org.apache.http.HttpResponse response) { this.response = response; } public InputStream getContent() throws IOException { return response.getEntity().getContent(); } public int getStatusCode() throws IOException { return response.getStatusLine().getStatusCode(); } public String getReasonPhrase() throws Exception { return response.getStatusLine().getReasonPhrase(); } public Object unwrap() { return response; } }
Java
/* * Copyright (c) 2009 Matthias Kaeppler Licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law * or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package oauth.commons.http; import java.io.IOException; import java.net.URLDecoder; import java.security.KeyStore; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import oauth.signpost.AbstractOAuthProvider; import oauth.signpost.OAuth; import oauth.signpost.http.HttpParameters; import oauth.signpost.http.HttpRequest; import oauth.signpost.signature.SSLSocketFactoryEx; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.HTTP; /** * This implementation uses the Apache Commons {@link HttpClient} 4.x HTTP * implementation to fetch OAuth tokens from a service provider. Android users * should use this provider implementation in favor of the default one, since * the latter is known to cause problems with Android's Apache Harmony * underpinnings. * * @author Matthias Kaeppler */ public class CommonsHttpOAuthProvider extends AbstractOAuthProvider { private static final long serialVersionUID = 1L; private transient HttpClient httpClient; public CommonsHttpOAuthProvider(String requestTokenEndpointUrl, String accessTokenEndpointUrl, String authorizationWebsiteUrl) { super(requestTokenEndpointUrl, accessTokenEndpointUrl, authorizationWebsiteUrl); this.httpClient = new DefaultHttpClient(); } public CommonsHttpOAuthProvider(String requestTokenEndpointUrl, String accessTokenEndpointUrl, String authorizationWebsiteUrl, HttpClient httpClient) { super(requestTokenEndpointUrl, accessTokenEndpointUrl, authorizationWebsiteUrl); this.httpClient = httpClient; } public void setHttpClient(HttpClient httpClient) { this.httpClient = httpClient; } @Override protected HttpRequest createRequest(String endpointUrl) throws Exception { HttpPost request = new HttpPost(endpointUrl); return new HttpRequestAdapter(request); } @Override protected HttpRequest createRequestForTencent(String endpointUrl) throws Exception { HttpPost request = new HttpPost(endpointUrl); request.addHeader("Content-Type", "application/x-www-form-urlencoded"); return new HttpRequestAdapter(request); } @Override protected oauth.signpost.http.HttpResponse sendRequest(HttpRequest request) throws Exception { HttpResponse response = httpClient.execute((HttpUriRequest) request.unwrap()); return new HttpResponseAdapter(response); } @Override protected oauth.signpost.http.HttpResponse sendRequestForTencent( HttpRequest request) throws Exception { Map<String, String> headers = request.getAllHeaders(); String oauthHeader = (String) headers.get("Authorization"); HttpParameters httpParams = OAuth.oauthHeaderToParamsMap(oauthHeader); List<NameValuePair> formParams = new ArrayList<NameValuePair>(); Set<String> keys = httpParams.keySet(); for (Iterator<String> iterator = keys.iterator(); iterator.hasNext();) { String key = (String) iterator.next(); String value = httpParams.getFirst(key); formParams.add(new BasicNameValuePair(key, URLDecoder.decode(value, "UTF-8"))); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8"); HttpPost postRequest = (HttpPost) request.unwrap(); postRequest.setEntity(entity); org.apache.http.HttpResponse response = getNewHttpClient().execute(postRequest); return new HttpResponseAdapter(response); } public HttpClient getNewHttpClient() { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } } @Override protected void closeConnection(HttpRequest request, oauth.signpost.http.HttpResponse response) throws Exception { if (response != null) { HttpEntity entity = ((HttpResponse) response.unwrap()).getEntity(); if (entity != null) { try { // free the connection entity.consumeContent(); } catch (IOException e) { // this means HTTP keep-alive is not possible e.printStackTrace(); } } } } }
Java
package oauth.commons.http; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.client.methods.HttpUriRequest; public class HttpRequestAdapter implements oauth.signpost.http.HttpRequest { private HttpUriRequest request; private HttpEntity entity; public HttpRequestAdapter(HttpUriRequest request) { this.request = request; if (request instanceof HttpEntityEnclosingRequest) { entity = ((HttpEntityEnclosingRequest) request).getEntity(); } } public String getMethod() { return request.getRequestLine().getMethod(); } public String getRequestUrl() { return request.getURI().toString(); } public void setRequestUrl(String url) { throw new RuntimeException(new UnsupportedOperationException()); } public String getHeader(String name) { Header header = request.getFirstHeader(name); if (header == null) { return null; } return header.getValue(); } public void setHeader(String name, String value) { request.setHeader(name, value); } public Map<String, String> getAllHeaders() { Header[] origHeaders = request.getAllHeaders(); HashMap<String, String> headers = new HashMap<String, String>(); for (Header h : origHeaders) { headers.put(h.getName(), h.getValue()); } return headers; } public String getContentType() { if (entity == null) { return null; } Header header = entity.getContentType(); if (header == null) { return null; } return header.getValue(); } public InputStream getMessagePayload() throws IOException { if (entity == null) { return null; } return entity.getContent(); } public Object unwrap() { return request; } }
Java
package oauth.facebook; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import oauth.facebook.AsyncFacebookRunner.RequestListener; import android.util.Log; /** * Skeleton base class for RequestListeners, providing default error * handling. Applications should handle these error conditions. * */ public abstract class BaseRequestListener implements RequestListener { public void onFacebookError(FacebookError e, final Object state) { Log.e("Facebook", e.getMessage()); e.printStackTrace(); } public void onFileNotFoundException(FileNotFoundException e, final Object state) { Log.e("Facebook", e.getMessage()); e.printStackTrace(); } public void onIOException(IOException e, final Object state) { Log.e("Facebook", e.getMessage()); e.printStackTrace(); } public void onMalformedURLException(MalformedURLException e, final Object state) { Log.e("Facebook", e.getMessage()); e.printStackTrace(); } }
Java
/* * Copyright 2010 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.facebook; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import android.Manifest; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.content.pm.Signature; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.text.TextUtils; import android.webkit.CookieSyncManager; import com.outsourcing.bottle.util.AppContext; /** * Main Facebook object for interacting with the Facebook developer API. * Provides methods to log in and log out a user, make requests using the REST * and Graph APIs, and start user interface interactions with the API (such as * pop-ups promoting for credentials, permissions, stream posts, etc.) * * @author Jim Brusstar (jimbru@facebook.com), * Yariv Sadan (yariv@facebook.com), * Luke Shepard (lshepard@facebook.com) */ public class Facebook { // Strings used in the authorization flow public static final String REDIRECT_URI = "fbconnect://success"; public static final String CANCEL_URI = "fbconnect://cancel"; public static final String TOKEN = "access_token"; public static final String EXPIRES = "expires_in"; public static final String SINGLE_SIGN_ON_DISABLED = "service_disabled"; public static final int FORCE_DIALOG_AUTH = -1; private static final String LOGIN = "oauth"; // Used as default activityCode by authorize(). See authorize() below. private static final int DEFAULT_AUTH_ACTIVITY_CODE = 32665; // Facebook server endpoints: may be modified in a subclass for testing protected static String DIALOG_BASE_URL = "https://m.facebook.com/dialog/"; protected static String GRAPH_BASE_URL = "https://graph.facebook.com/"; protected static String RESTSERVER_URL = "https://api.facebook.com/restserver.php"; private String mAccessToken = null; private long mLastAccessUpdate = 0; private long mAccessExpires = 0; private String mAppId; private Activity mAuthActivity; private String[] mAuthPermissions; private int mAuthActivityCode; private DialogListener mAuthDialogListener; // If the last time we extended the access token was more than 24 hours ago // we try to refresh the access token again. final private long REFRESH_TOKEN_BARRIER = 24L * 60L * 60L * 1000L; /** * Constructor for Facebook object. * * @param appId * Your Facebook application ID. Found at * www.facebook.com/developers/apps.php. */ public Facebook(String appId) { if (appId == null) { throw new IllegalArgumentException( "You must specify your application ID when instantiating " + "a Facebook object. See README for details."); } mAppId = appId; } /** * Default authorize method. Grants only basic permissions. * * See authorize() below for @params. */ public void authorize(Activity activity, final DialogListener listener) { authorize(activity, new String[] {}, DEFAULT_AUTH_ACTIVITY_CODE, listener); } /** * Authorize method that grants custom permissions. * * See authorize() below for @params. */ public void authorize(Activity activity, String[] permissions, final DialogListener listener) { authorize(activity, permissions, DEFAULT_AUTH_ACTIVITY_CODE, listener); } /** * Full authorize method. * * Starts either an Activity or a dialog which prompts the user to log in to * Facebook and grant the requested permissions to the given application. * * This method will, when possible, use Facebook's single sign-on for * Android to obtain an access token. This involves proxying a call through * the Facebook for Android stand-alone application, which will handle the * authentication flow, and return an OAuth access token for making API * calls. * * Because this process will not be available for all users, if single * sign-on is not possible, this method will automatically fall back to the * OAuth 2.0 User-Agent flow. In this flow, the user credentials are handled * by Facebook in an embedded WebView, not by the client application. As * such, the dialog makes a network request and renders HTML content rather * than a native UI. The access token is retrieved from a redirect to a * special URL that the WebView handles. * * Note that User credentials could be handled natively using the OAuth 2.0 * Username and Password Flow, but this is not supported by this SDK. * * See http://developers.facebook.com/docs/authentication/ and * http://wiki.oauth.net/OAuth-2 for more details. * * Note that this method is asynchronous and the callback will be invoked in * the original calling thread (not in a background thread). * * Also note that requests may be made to the API without calling authorize * first, in which case only public information is returned. * * IMPORTANT: Note that single sign-on authentication will not function * correctly if you do not include a call to the authorizeCallback() method * in your onActivityResult() function! Please see below for more * information. single sign-on may be disabled by passing FORCE_DIALOG_AUTH * as the activityCode parameter in your call to authorize(). * * @param activity * The Android activity in which we want to display the * authorization dialog. * @param applicationId * The Facebook application identifier e.g. "350685531728" * @param permissions * A list of permissions required for this application: e.g. * "read_stream", "publish_stream", "offline_access", etc. see * http://developers.facebook.com/docs/authentication/permissions * This parameter should not be null -- if you do not require any * permissions, then pass in an empty String array. * @param activityCode * Single sign-on requires an activity result to be called back * to the client application -- if you are waiting on other * activities to return data, pass a custom activity code here to * avoid collisions. If you would like to force the use of legacy * dialog-based authorization, pass FORCE_DIALOG_AUTH for this * parameter. Otherwise just omit this parameter and Facebook * will use a suitable default. See * http://developer.android.com/reference/android/ * app/Activity.html for more information. * @param listener * Callback interface for notifying the calling application when * the authentication dialog has completed, failed, or been * canceled. */ public void authorize(Activity activity, String[] permissions, int activityCode, final DialogListener listener) { boolean singleSignOnStarted = false; mAuthDialogListener = listener; // Prefer single sign-on, where available. if (activityCode >= 0) { singleSignOnStarted = startSingleSignOn(activity, mAppId, permissions, activityCode); } // Otherwise fall back to traditional dialog. if (!singleSignOnStarted) { startDialogAuth(activity, permissions); } } /** * Internal method to handle single sign-on backend for authorize(). * * @param activity * The Android Activity that will parent the ProxyAuth Activity. * @param applicationId * The Facebook application identifier. * @param permissions * A list of permissions required for this application. If you do * not require any permissions, pass an empty String array. * @param activityCode * Activity code to uniquely identify the result Intent in the * callback. */ private boolean startSingleSignOn(Activity activity, String applicationId, String[] permissions, int activityCode) { boolean didSucceed = true; Intent intent = new Intent(); intent.setClassName("com.facebook.katana", "com.facebook.katana.ProxyAuth"); intent.putExtra("client_id", applicationId); if (permissions.length > 0) { intent.putExtra("scope", TextUtils.join(",", permissions)); } // Verify that the application whose package name is // com.facebook.katana.ProxyAuth // has the expected FB app signature. if (!validateActivityIntent(activity, intent)) { return false; } mAuthActivity = activity; mAuthPermissions = permissions; mAuthActivityCode = activityCode; try { activity.startActivityForResult(intent, activityCode); } catch (ActivityNotFoundException e) { didSucceed = false; } return didSucceed; } /** * Helper to validate an activity intent by resolving and checking the * provider's package signature. * * @param context * @param intent * @return true if the service intent resolution happens successfully and the * signatures match. */ private boolean validateActivityIntent(Context context, Intent intent) { ResolveInfo resolveInfo = context.getPackageManager().resolveActivity(intent, 0); if (resolveInfo == null) { return false; } return validateAppSignatureForPackage( context, resolveInfo.activityInfo.packageName); } /** * Helper to validate a service intent by resolving and checking the * provider's package signature. * * @param context * @param intent * @return true if the service intent resolution happens successfully and the * signatures match. */ private boolean validateServiceIntent(Context context, Intent intent) { ResolveInfo resolveInfo = context.getPackageManager().resolveService(intent, 0); if (resolveInfo == null) { return false; } return validateAppSignatureForPackage( context, resolveInfo.serviceInfo.packageName); } /** * Query the signature for the application that would be invoked by the * given intent and verify that it matches the FB application's signature. * * @param context * @param packageName * @return true if the app's signature matches the expected signature. */ private boolean validateAppSignatureForPackage(Context context, String packageName) { PackageInfo packageInfo; try { packageInfo = context.getPackageManager().getPackageInfo( packageName, PackageManager.GET_SIGNATURES); } catch (NameNotFoundException e) { return false; } for (Signature signature : packageInfo.signatures) { if (signature.toCharsString().equals(FB_APP_SIGNATURE)) { return true; } } return false; } /** * Internal method to handle dialog-based authentication backend for * authorize(). * * @param activity * The Android Activity that will parent the auth dialog. * @param applicationId * The Facebook application identifier. * @param permissions * A list of permissions required for this application. If you do * not require any permissions, pass an empty String array. */ private void startDialogAuth(Activity activity, String[] permissions) { Bundle params = new Bundle(); if (permissions.length > 0) { params.putString("scope", TextUtils.join(",", permissions)); } CookieSyncManager.createInstance(activity); dialog(activity, LOGIN, params, new DialogListener() { public void onComplete(Bundle values) { // ensure any cookies set by the dialog are saved CookieSyncManager.getInstance().sync(); setAccessToken(values.getString(TOKEN)); setAccessExpiresIn(values.getString(EXPIRES)); if (isSessionValid()) { Util.logd("Facebook-authorize", "Login Success! access_token=" + getAccessToken() + " expires=" + getAccessExpires()); mAuthDialogListener.onComplete(values); } else { mAuthDialogListener.onFacebookError(new FacebookError( "Failed to receive access token.")); } } public void onError(DialogError error) { Util.logd("Facebook-authorize", "Login failed: " + error); mAuthDialogListener.onError(error); } public void onFacebookError(FacebookError error) { Util.logd("Facebook-authorize", "Login failed: " + error); mAuthDialogListener.onFacebookError(error); } public void onCancel() { Util.logd("Facebook-authorize", "Login canceled"); mAuthDialogListener.onCancel(); } }); } /** * IMPORTANT: This method must be invoked at the top of the calling * activity's onActivityResult() function or Facebook authentication will * not function properly! * * If your calling activity does not currently implement onActivityResult(), * you must implement it and include a call to this method if you intend to * use the authorize() method in this SDK. * * For more information, see * http://developer.android.com/reference/android/app/ * Activity.html#onActivityResult(int, int, android.content.Intent) */ public void authorizeCallback(int requestCode, int resultCode, Intent data) { if (requestCode == mAuthActivityCode) { // Successfully redirected. if (resultCode == Activity.RESULT_OK) { // Check OAuth 2.0/2.10 error code. String error = data.getStringExtra("error"); if (error == null) { error = data.getStringExtra("error_type"); } // A Facebook error occurred. if (error != null) { if (error.equals(SINGLE_SIGN_ON_DISABLED) || error.equals("AndroidAuthKillSwitchException")) { Util.logd("Facebook-authorize", "Hosted auth currently " + "disabled. Retrying dialog auth..."); startDialogAuth(mAuthActivity, mAuthPermissions); } else if (error.equals("access_denied") || error.equals("OAuthAccessDeniedException")) { Util.logd("Facebook-authorize", "Login canceled by user."); mAuthDialogListener.onCancel(); } else { String description = data.getStringExtra("error_description"); if (description != null) { error = error + ":" + description; } Util.logd("Facebook-authorize", "Login failed: " + error); mAuthDialogListener.onFacebookError( new FacebookError(error)); } // No errors. } else { setAccessToken(data.getStringExtra(TOKEN)); setAccessExpiresIn(data.getStringExtra(EXPIRES)); if (isSessionValid()) { Util.logd("Facebook-authorize", "Login Success! access_token=" + getAccessToken() + " expires=" + getAccessExpires()); mAuthDialogListener.onComplete(data.getExtras()); } else { mAuthDialogListener.onFacebookError(new FacebookError( "Failed to receive access token.")); } } // An error occurred before we could be redirected. } else if (resultCode == Activity.RESULT_CANCELED) { // An Android error occured. if (data != null) { Util.logd("Facebook-authorize", "Login failed: " + data.getStringExtra("error")); mAuthDialogListener.onError( new DialogError( data.getStringExtra("error"), data.getIntExtra("error_code", -1), data.getStringExtra("failing_url"))); // User pressed the 'back' button. } else { Util.logd("Facebook-authorize", "Login canceled by user."); mAuthDialogListener.onCancel(); } } } } /** * Refresh OAuth access token method. Binds to Facebook for Android * stand-alone application application to refresh the access token. This * method tries to connect to the Facebook App which will handle the * authentication flow, and return a new OAuth access token. This method * will automatically replace the old token with a new one. Note that this * method is asynchronous and the callback will be invoked in the original * calling thread (not in a background thread). * * @param context * The Android Context that will be used to bind to the Facebook * RefreshToken Service * @param serviceListener * Callback interface for notifying the calling application when * the refresh request has completed or failed (can be null). In * case of a success a new token can be found inside the result * Bundle under Facebook.ACCESS_TOKEN key. * @return true if the binding to the RefreshToken Service was created */ public boolean extendAccessToken(Context context, ServiceListener serviceListener) { Intent intent = new Intent(); intent.setClassName("com.facebook.katana", "com.facebook.katana.platform.TokenRefreshService"); // Verify that the application whose package name is // com.facebook.katana // has the expected FB app signature. if (!validateServiceIntent(context, intent)) { return false; } return context.bindService(intent, new TokenRefreshServiceConnection(context, serviceListener), Context.BIND_AUTO_CREATE); } /** * Calls extendAccessToken if shouldExtendAccessToken returns true. * * @return the same value as extendAccessToken if the the token requires * refreshing, true otherwise */ public boolean extendAccessTokenIfNeeded(Context context, ServiceListener serviceListener) { if (shouldExtendAccessToken()) { return extendAccessToken(context, serviceListener); } return true; } /** * Check if the access token requires refreshing. * * @return true if the last time a new token was obtained was over 24 hours ago. */ public boolean shouldExtendAccessToken() { return isSessionValid() && (System.currentTimeMillis() - mLastAccessUpdate >= REFRESH_TOKEN_BARRIER); } /** * Handles connection to the token refresh service (this service is a part * of Facebook App). */ private class TokenRefreshServiceConnection implements ServiceConnection { final Messenger messageReceiver = new Messenger(new Handler() { @Override public void handleMessage(Message msg) { String token = msg.getData().getString(TOKEN); long expiresAt = msg.getData().getLong(EXPIRES) * 1000L; // To avoid confusion we should return the expiration time in // the same format as the getAccessExpires() function - that // is in milliseconds. Bundle resultBundle = (Bundle) msg.getData().clone(); resultBundle.putLong(EXPIRES, expiresAt); if (token != null) { setAccessToken(token); setAccessExpires(expiresAt); if (serviceListener != null) { serviceListener.onComplete(resultBundle); } } else if (serviceListener != null) { // extract errors only if client wants them String error = msg.getData().getString("error"); if (msg.getData().containsKey("error_code")) { int errorCode = msg.getData().getInt("error_code"); serviceListener.onFacebookError(new FacebookError(error, null, errorCode)); } else { serviceListener.onError(new Error(error != null ? error : "Unknown service error")); } } // The refreshToken function should be called rarely, // so there is no point in keeping the binding open. applicationsContext.unbindService(TokenRefreshServiceConnection.this); } }); final ServiceListener serviceListener; final Context applicationsContext; Messenger messageSender = null; public TokenRefreshServiceConnection(Context applicationsContext, ServiceListener serviceListener) { this.applicationsContext = applicationsContext; this.serviceListener = serviceListener; } @Override public void onServiceConnected(ComponentName className, IBinder service) { messageSender = new Messenger(service); refreshToken(); } @Override public void onServiceDisconnected(ComponentName arg) { serviceListener.onError(new Error("Service disconnected")); // We returned an error so there's no point in // keeping the binding open. applicationsContext.unbindService(TokenRefreshServiceConnection.this); } private void refreshToken() { Bundle requestData = new Bundle(); requestData.putString(TOKEN, mAccessToken); Message request = Message.obtain(); request.setData(requestData); request.replyTo = messageReceiver; try { messageSender.send(request); } catch (RemoteException e) { serviceListener.onError(new Error("Service connection error")); } } }; /** * Invalidate the current user session by removing the access token in * memory, clearing the browser cookie, and calling auth.expireSession * through the API. * * Note that this method blocks waiting for a network response, so do not * call it in a UI thread. * * @param context * The Android context in which the logout should be called: it * should be the same context in which the login occurred in * order to clear any stored cookies * @throws IOException * @throws MalformedURLException * @return JSON string representation of the auth.expireSession response * ("true" if successful) */ public String logout(Context context) throws MalformedURLException, IOException { Util.clearCookies(context); Bundle b = new Bundle(); b.putString("method", "auth.expireSession"); String response = request(b); setAccessToken(null); setAccessExpires(0); return response; } /** * Make a request to Facebook's old (pre-graph) API with the given * parameters. One of the parameter keys must be "method" and its value * should be a valid REST server API method. * * See http://developers.facebook.com/docs/reference/rest/ * * Note that this method blocks waiting for a network response, so do not * call it in a UI thread. * * Example: * <code> * Bundle parameters = new Bundle(); * parameters.putString("method", "auth.expireSession"); * String response = request(parameters); * </code> * * @param parameters * Key-value pairs of parameters to the request. Refer to the * documentation: one of the parameters must be "method". * @throws IOException * if a network error occurs * @throws MalformedURLException * if accessing an invalid endpoint * @throws IllegalArgumentException * if one of the parameters is not "method" * @return JSON string representation of the response */ public String request(Bundle parameters) throws MalformedURLException, IOException { if (!parameters.containsKey("method")) { throw new IllegalArgumentException("API method must be specified. " + "(parameters must contain key \"method\" and value). See" + " http://developers.facebook.com/docs/reference/rest/"); } return request(null, parameters, "GET"); } /** * Make a request to the Facebook Graph API without any parameters. * * See http://developers.facebook.com/docs/api * * Note that this method blocks waiting for a network response, so do not * call it in a UI thread. * * @param graphPath * Path to resource in the Facebook graph, e.g., to fetch data * about the currently logged authenticated user, provide "me", * which will fetch http://graph.facebook.com/me * @throws IOException * @throws MalformedURLException * @return JSON string representation of the response */ public String request(String graphPath) throws MalformedURLException, IOException { return request(graphPath, new Bundle(), "GET"); } /** * Make a request to the Facebook Graph API with the given string parameters * using an HTTP GET (default method). * * See http://developers.facebook.com/docs/api * * Note that this method blocks waiting for a network response, so do not * call it in a UI thread. * * @param graphPath * Path to resource in the Facebook graph, e.g., to fetch data * about the currently logged authenticated user, provide "me", * which will fetch http://graph.facebook.com/me * @param parameters * key-value string parameters, e.g. the path "search" with * parameters "q" : "facebook" would produce a query for the * following graph resource: * https://graph.facebook.com/search?q=facebook * @throws IOException * @throws MalformedURLException * @return JSON string representation of the response */ public String request(String graphPath, Bundle parameters) throws MalformedURLException, IOException { return request(graphPath, parameters, "GET"); } /** * Synchronously make a request to the Facebook Graph API with the given * HTTP method and string parameters. Note that binary data parameters * (e.g. pictures) are not yet supported by this helper function. * * See http://developers.facebook.com/docs/api * * Note that this method blocks waiting for a network response, so do not * call it in a UI thread. * * @param graphPath * Path to resource in the Facebook graph, e.g., to fetch data * about the currently logged authenticated user, provide "me", * which will fetch http://graph.facebook.com/me * @param params * Key-value string parameters, e.g. the path "search" with * parameters {"q" : "facebook"} would produce a query for the * following graph resource: * https://graph.facebook.com/search?q=facebook * @param httpMethod * http verb, e.g. "GET", "POST", "DELETE" * @throws IOException * @throws MalformedURLException * @return JSON string representation of the response */ public String request(String graphPath, Bundle params, String httpMethod) throws FileNotFoundException, MalformedURLException, IOException { params.putString("format", "json"); if (isSessionValid()) { params.putString(TOKEN, getAccessToken()); } String url = (graphPath != null) ? GRAPH_BASE_URL + graphPath : RESTSERVER_URL; return Util.openUrl(url, httpMethod, params); } /** * Generate a UI dialog for the request action in the given Android context. * * Note that this method is asynchronous and the callback will be invoked in * the original calling thread (not in a background thread). * * @param context * The Android context in which we will generate this dialog. * @param action * String representation of the desired method: e.g. "login", * "stream.publish", ... * @param listener * Callback interface to notify the application when the dialog * has completed. */ public void dialog(Context context, String action, DialogListener listener) { dialog(context, action, new Bundle(), listener); } /** * Generate a UI dialog for the request action in the given Android context * with the provided parameters. * * Note that this method is asynchronous and the callback will be invoked in * the original calling thread (not in a background thread). * * @param context * The Android context in which we will generate this dialog. * @param action * String representation of the desired method: e.g. "feed" ... * @param parameters * String key-value pairs to be passed as URL parameters. * @param listener * Callback interface to notify the application when the dialog * has completed. */ public static DialogListener listener; public void dialog(Context context, String action, Bundle parameters, final DialogListener listener) { Facebook.listener = listener; String endpoint = DIALOG_BASE_URL + action; parameters.putString("display", "touch"); parameters.putString("redirect_uri", REDIRECT_URI); if (action.equals(LOGIN)) { parameters.putString("type", "user_agent"); parameters.putString("client_id", mAppId); } else { parameters.putString("app_id", mAppId); } if (isSessionValid()) { parameters.putString(TOKEN, getAccessToken()); } String url = endpoint + "?" + Util.encodeUrl(parameters); if (context.checkCallingOrSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) { Util.showAlert(context, "Error", "Application requires permission to access the Internet"); } else { Intent intent = new Intent(AppContext.getContext(), FacebookActivity.class); intent.putExtra("url", url); AppContext.getContext().startActivity(intent); // new FbDialog(context, url, listener).show(); } } /** * @return boolean - whether this object has an non-expired session token */ public boolean isSessionValid() { return (getAccessToken() != null) && ((getAccessExpires() == 0) || (System.currentTimeMillis() < getAccessExpires())); } /** * Retrieve the OAuth 2.0 access token for API access: treat with care. * Returns null if no session exists. * * @return String - access token */ public String getAccessToken() { return mAccessToken; } /** * Retrieve the current session's expiration time (in milliseconds since * Unix epoch), or 0 if the session doesn't expire or doesn't exist. * * @return long - session expiration time */ public long getAccessExpires() { return mAccessExpires; } /** * Set the OAuth 2.0 access token for API access. * * @param token - access token */ public void setAccessToken(String token) { mAccessToken = token; mLastAccessUpdate = System.currentTimeMillis(); } /** * Set the current session's expiration time (in milliseconds since Unix * epoch), or 0 if the session doesn't expire. * * @param time - timestamp in milliseconds */ public void setAccessExpires(long time) { mAccessExpires = time; } /** * Set the current session's duration (in seconds since Unix epoch), or "0" * if session doesn't expire. * * @param expiresIn * - duration in seconds (or 0 if the session doesn't expire) */ public void setAccessExpiresIn(String expiresIn) { if (expiresIn != null) { long expires = expiresIn.equals("0") ? 0 : System.currentTimeMillis() + Long.parseLong(expiresIn) * 1000L; setAccessExpires(expires); } } public String getAppId() { return mAppId; } public void setAppId(String appId) { mAppId = appId; } /** * Callback interface for dialog requests. * */ public static interface DialogListener { /** * Called when a dialog completes. * * Executed by the thread that initiated the dialog. * * @param values * Key-value string pairs extracted from the response. */ public void onComplete(Bundle values); /** * Called when a Facebook responds to a dialog with an error. * * Executed by the thread that initiated the dialog. * */ public void onFacebookError(FacebookError e); /** * Called when a dialog has an error. * * Executed by the thread that initiated the dialog. * */ public void onError(DialogError e); /** * Called when a dialog is canceled by the user. * * Executed by the thread that initiated the dialog. * */ public void onCancel(); } /** * Callback interface for service requests. */ public static interface ServiceListener { /** * Called when a service request completes. * * @param values * Key-value string pairs extracted from the response. */ public void onComplete(Bundle values); /** * Called when a Facebook server responds to the request with an error. */ public void onFacebookError(FacebookError e); /** * Called when a Facebook Service responds to the request with an error. */ public void onError(Error e); } public static final String FB_APP_SIGNATURE = "30820268308201d102044a9c4610300d06092a864886f70d0101040500307a310" + "b3009060355040613025553310b30090603550408130243413112301006035504" + "07130950616c6f20416c746f31183016060355040a130f46616365626f6f6b204" + "d6f62696c653111300f060355040b130846616365626f6f6b311d301b06035504" + "03131446616365626f6f6b20436f72706f726174696f6e3020170d30393038333" + "13231353231365a180f32303530303932353231353231365a307a310b30090603" + "55040613025553310b30090603550408130243413112301006035504071309506" + "16c6f20416c746f31183016060355040a130f46616365626f6f6b204d6f62696c" + "653111300f060355040b130846616365626f6f6b311d301b06035504031314466" + "16365626f6f6b20436f72706f726174696f6e30819f300d06092a864886f70d01" + "0101050003818d0030818902818100c207d51df8eb8c97d93ba0c8c1002c928fa" + "b00dc1b42fca5e66e99cc3023ed2d214d822bc59e8e35ddcf5f44c7ae8ade50d7" + "e0c434f500e6c131f4a2834f987fc46406115de2018ebbb0d5a3c261bd97581cc" + "fef76afc7135a6d59e8855ecd7eacc8f8737e794c60a761c536b72b11fac8e603" + "f5da1a2d54aa103b8a13c0dbc10203010001300d06092a864886f70d010104050" + "0038181005ee9be8bcbb250648d3b741290a82a1c9dc2e76a0af2f2228f1d9f9c" + "4007529c446a70175c5a900d5141812866db46be6559e2141616483998211f4a6" + "73149fb2232a10d247663b26a9031e15f84bc1c74d141ff98a02d76f85b2c8ab2" + "571b6469b232d8e768a7f7ca04f7abe4a775615916c07940656b58717457b42bd" + "928a2"; }
Java
package oauth.facebook; import oauth.facebook.Facebook.DialogListener; /** * Skeleton base class for RequestListeners, providing default error * handling. Applications should handle these error conditions. * */ public abstract class BaseDialogListener implements DialogListener { public void onFacebookError(FacebookError e) { e.printStackTrace(); } public void onError(DialogError e) { e.printStackTrace(); } public void onCancel() { } }
Java
/* * Copyright 2010 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.facebook; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; import org.json.JSONException; import org.json.JSONObject; import android.app.AlertDialog.Builder; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; /** * Utility class supporting the Facebook Object. * * @author ssoneff@facebook.com * */ public final class Util { /** * Set this to true to enable log output. Remember to turn this back off * before releasing. Sending sensitive data to log is a security risk. */ private static boolean ENABLE_LOG = false; /** * Generate the multi-part post body providing the parameters and boundary * string * * @param parameters the parameters need to be posted * @param boundary the random string as boundary * @return a string of the post body */ public static String encodePostBody(Bundle parameters, String boundary) { if (parameters == null) return ""; StringBuilder sb = new StringBuilder(); for (String key : parameters.keySet()) { Object parameter = parameters.get(key); if (!(parameter instanceof String)) { continue; } sb.append("Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n" + (String)parameter); sb.append("\r\n" + "--" + boundary + "\r\n"); } return sb.toString(); } @SuppressWarnings("deprecation") public static String encodeUrl(Bundle parameters) { if (parameters == null) { return ""; } StringBuilder sb = new StringBuilder(); boolean first = true; for (String key : parameters.keySet()) { Object parameter = parameters.get(key); if (!(parameter instanceof String)) { continue; } if (first) first = false; else sb.append("&"); sb.append(URLEncoder.encode(key) + "=" + URLEncoder.encode(parameters.getString(key))); } return sb.toString(); } @SuppressWarnings("deprecation") public static Bundle decodeUrl(String s) { Bundle params = new Bundle(); if (s != null) { String array[] = s.split("&"); for (String parameter : array) { String v[] = parameter.split("="); if (v.length == 2) { params.putString(URLDecoder.decode(v[0]), URLDecoder.decode(v[1])); } } } return params; } /** * Parse a URL query and fragment parameters into a key-value bundle. * * @param url the URL to parse * @return a dictionary bundle of keys and values */ public static Bundle parseUrl(String url) { // hack to prevent MalformedURLException url = url.replace("fbconnect", "http"); try { URL u = new URL(url); Bundle b = decodeUrl(u.getQuery()); b.putAll(decodeUrl(u.getRef())); return b; } catch (MalformedURLException e) { return new Bundle(); } } /** * Connect to an HTTP URL and return the response as a string. * * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url - the resource to open: must be a welformed URL * @param method - the HTTP method to use ("GET", "POST", etc.) * @param params - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ @SuppressWarnings("deprecation") public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Util.logd("Facebook-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties(). getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { Object parameter = params.get(key); if (parameter instanceof byte[]) { dataparams.putByteArray(key, (byte[])parameter); } } // use method override if (!params.containsKey("method")) { params.putString("method", method); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(params.getString("access_token")); params.putString("access_token", decoded_token); } conn.setRequestMethod("POST"); conn.setRequestProperty( "Content-Type", "multipart/form-data;boundary="+strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + strBoundary +endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key: dataparams.keySet()){ os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; } private static String read(InputStream in) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000); for (String line = r.readLine(); line != null; line = r.readLine()) { sb.append(line); } in.close(); return sb.toString(); } public static void clearCookies(Context context) { // Edge case: an illegal state exception is thrown if an instance of // CookieSyncManager has not be created. CookieSyncManager is normally // created by a WebKit view, but this might happen if you start the // app, restore saved state, and click logout before running a UI // dialog in a WebView -- in which case the app crashes @SuppressWarnings("unused") CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.removeAllCookie(); } /** * Parse a server response into a JSON Object. This is a basic * implementation using org.json.JSONObject representation. More * sophisticated applications may wish to do their own parsing. * * The parsed JSON is checked for a variety of error fields and * a FacebookException is thrown if an error condition is set, * populated with the error message and error type or code if * available. * * @param response - string representation of the response * @return the response as a JSON Object * @throws JSONException - if the response is not valid JSON * @throws FacebookError - if an error condition is set */ public static JSONObject parseJson(String response) throws JSONException, FacebookError { // Edge case: when sending a POST request to /[post_id]/likes // the return value is 'true' or 'false'. Unfortunately // these values cause the JSONObject constructor to throw // an exception. if (response.equals("false")) { throw new FacebookError("request failed"); } if (response.equals("true")) { response = "{value : true}"; } JSONObject json = new JSONObject(response); // errors set by the server are not consistent // they depend on the method and endpoint if (json.has("error")) { JSONObject error = json.getJSONObject("error"); throw new FacebookError( error.getString("message"), error.getString("type"), 0); } if (json.has("error_code") && json.has("error_msg")) { throw new FacebookError(json.getString("error_msg"), "", Integer.parseInt(json.getString("error_code"))); } if (json.has("error_code")) { throw new FacebookError("request failed", "", Integer.parseInt(json.getString("error_code"))); } if (json.has("error_msg")) { throw new FacebookError(json.getString("error_msg")); } if (json.has("error_reason")) { throw new FacebookError(json.getString("error_reason")); } return json; } /** * Display a simple alert dialog with the given text and title. * * @param context * Android context in which the dialog should be displayed * @param title * Alert dialog title * @param text * Alert dialog message */ public static void showAlert(Context context, String title, String text) { Builder alertBuilder = new Builder(context); alertBuilder.setTitle(title); alertBuilder.setMessage(text); alertBuilder.create().show(); } /** * A proxy for Log.d api that kills log messages in release build. It * not recommended to send sensitive information to log output in * shipping apps. * * @param tag * @param msg */ public static void logd(String tag, String msg) { if (ENABLE_LOG) { Log.d(tag, msg); } } }
Java
/* * Copyright 2010 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.facebook; /** * Encapsulation of Dialog Error. * * @author ssoneff@facebook.com */ public class DialogError extends Throwable { private static final long serialVersionUID = 1L; /** * The ErrorCode received by the WebView: see * http://developer.android.com/reference/android/webkit/WebViewClient.html */ private int mErrorCode; /** The URL that the dialog was trying to load */ private String mFailingUrl; public DialogError(String message, int errorCode, String failingUrl) { super(message); mErrorCode = errorCode; mFailingUrl = failingUrl; } int getErrorCode() { return mErrorCode; } String getFailingUrl() { return mFailingUrl; } }
Java
/* * Copyright 2010 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.facebook; /** * Encapsulation of a Facebook Error: a Facebook request that could not be * fulfilled. * * @author ssoneff@facebook.com */ public class FacebookError extends RuntimeException { private static final long serialVersionUID = 1L; private int mErrorCode = 0; private String mErrorType; public FacebookError(String message) { super(message); } public FacebookError(String message, String type, int code) { super(message); mErrorType = type; mErrorCode = code; } public int getErrorCode() { return mErrorCode; } public String getErrorType() { return mErrorType; } }
Java
/* * Copyright 2010 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.facebook; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class SessionStore { private static final String TOKEN = "access_token"; private static final String EXPIRES = "expires_in"; private static final String KEY = "facebook-session"; public static boolean save(Facebook session, Context context) { Editor editor = context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit(); editor.putString(TOKEN, session.getAccessToken()); editor.putLong(EXPIRES, session.getAccessExpires()); return editor.commit(); } public static boolean restore(Facebook session, Context context) { SharedPreferences savedSession = context.getSharedPreferences(KEY, Context.MODE_PRIVATE); session.setAccessToken(savedSession.getString(TOKEN, null)); session.setAccessExpires(savedSession.getLong(EXPIRES, 0)); return session.isSessionValid(); } public static void clear(Context context) { Editor editor = context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit(); editor.clear(); editor.commit(); } }
Java
/* * Copyright 2010 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.facebook; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import android.content.Context; import android.os.Bundle; /** * A sample implementation of asynchronous API requests. This class provides * the ability to execute API methods and have the call return immediately, * without blocking the calling thread. This is necessary when accessing the * API in the UI thread, for instance. The request response is returned to * the caller via a callback interface, which the developer must implement. * * This sample implementation simply spawns a new thread for each request, * and makes the API call immediately. This may work in many applications, * but more sophisticated users may re-implement this behavior using a thread * pool, a network thread, a request queue, or other mechanism. Advanced * functionality could be built, such as rate-limiting of requests, as per * a specific application's needs. * * @see RequestListener * The callback interface. * * @author Jim Brusstar (jimbru@fb.com), * Yariv Sadan (yariv@fb.com), * Luke Shepard (lshepard@fb.com) */ public class AsyncFacebookRunner { Facebook fb; public AsyncFacebookRunner(Facebook fb) { this.fb = fb; } /** * Invalidate the current user session by removing the access token in * memory, clearing the browser cookies, and calling auth.expireSession * through the API. The application will be notified when logout is * complete via the callback interface. * * Note that this method is asynchronous and the callback will be invoked * in a background thread; operations that affect the UI will need to be * posted to the UI thread or an appropriate handler. * * @param context * The Android context in which the logout should be called: it * should be the same context in which the login occurred in * order to clear any stored cookies * @param listener * Callback interface to notify the application when the request * has completed. * @param state * An arbitrary object used to identify the request when it * returns to the callback. This has no effect on the request * itself. */ public void logout(final Context context, final RequestListener listener, final Object state) { new Thread() { @Override public void run() { try { String response = fb.logout(context); if (response.length() == 0 || response.equals("false")){ listener.onFacebookError(new FacebookError( "auth.expireSession failed"), state); return; } listener.onComplete(response, state); } catch (FileNotFoundException e) { listener.onFileNotFoundException(e, state); } catch (MalformedURLException e) { listener.onMalformedURLException(e, state); } catch (IOException e) { listener.onIOException(e, state); } } }.start(); } public void logout(final Context context, final RequestListener listener) { logout(context, listener, /* state */ null); } /** * Make a request to Facebook's old (pre-graph) API with the given * parameters. One of the parameter keys must be "method" and its value * should be a valid REST server API method. * * See http://developers.facebook.com/docs/reference/rest/ * * Note that this method is asynchronous and the callback will be invoked * in a background thread; operations that affect the UI will need to be * posted to the UI thread or an appropriate handler. * * Example: * <code> * Bundle parameters = new Bundle(); * parameters.putString("method", "auth.expireSession", new Listener()); * String response = request(parameters); * </code> * * @param parameters * Key-value pairs of parameters to the request. Refer to the * documentation: one of the parameters must be "method". * @param listener * Callback interface to notify the application when the request * has completed. * @param state * An arbitrary object used to identify the request when it * returns to the callback. This has no effect on the request * itself. */ public void request(Bundle parameters, RequestListener listener, final Object state) { request(null, parameters, "GET", listener, state); } public void request(Bundle parameters, RequestListener listener) { request(null, parameters, "GET", listener, /* state */ null); } /** * Make a request to the Facebook Graph API without any parameters. * * See http://developers.facebook.com/docs/api * * Note that this method is asynchronous and the callback will be invoked * in a background thread; operations that affect the UI will need to be * posted to the UI thread or an appropriate handler. * * @param graphPath * Path to resource in the Facebook graph, e.g., to fetch data * about the currently logged authenticated user, provide "me", * which will fetch http://graph.facebook.com/me * @param listener * Callback interface to notify the application when the request * has completed. * @param state * An arbitrary object used to identify the request when it * returns to the callback. This has no effect on the request * itself. */ public void request(String graphPath, RequestListener listener, final Object state) { request(graphPath, new Bundle(), "GET", listener, state); } public void request(String graphPath, RequestListener listener) { request(graphPath, new Bundle(), "GET", listener, /* state */ null); } /** * Make a request to the Facebook Graph API with the given string parameters * using an HTTP GET (default method). * * See http://developers.facebook.com/docs/api * * Note that this method is asynchronous and the callback will be invoked * in a background thread; operations that affect the UI will need to be * posted to the UI thread or an appropriate handler. * * @param graphPath * Path to resource in the Facebook graph, e.g., to fetch data * about the currently logged authenticated user, provide "me", * which will fetch http://graph.facebook.com/me * @param parameters * key-value string parameters, e.g. the path "search" with * parameters "q" : "facebook" would produce a query for the * following graph resource: * https://graph.facebook.com/search?q=facebook * @param listener * Callback interface to notify the application when the request * has completed. * @param state * An arbitrary object used to identify the request when it * returns to the callback. This has no effect on the request * itself. */ public void request(String graphPath, Bundle parameters, RequestListener listener, final Object state) { request(graphPath, parameters, "GET", listener, state); } public void request(String graphPath, Bundle parameters, RequestListener listener) { request(graphPath, parameters, "GET", listener, /* state */ null); } /** * Make a request to the Facebook Graph API with the given HTTP method and * string parameters. Note that binary data parameters (e.g. pictures) are * not yet supported by this helper function. * * See http://developers.facebook.com/docs/api * * Note that this method is asynchronous and the callback will be invoked * in a background thread; operations that affect the UI will need to be * posted to the UI thread or an appropriate handler. * * @param graphPath * Path to resource in the Facebook graph, e.g., to fetch data * about the currently logged authenticated user, provide "me", * which will fetch http://graph.facebook.com/me * @param parameters * key-value string parameters, e.g. the path "search" with * parameters {"q" : "facebook"} would produce a query for the * following graph resource: * https://graph.facebook.com/search?q=facebook * @param httpMethod * http verb, e.g. "POST", "DELETE" * @param listener * Callback interface to notify the application when the request * has completed. * @param state * An arbitrary object used to identify the request when it * returns to the callback. This has no effect on the request * itself. */ public void request(final String graphPath, final Bundle parameters, final String httpMethod, final RequestListener listener, final Object state) { new Thread() { @Override public void run() { try { String resp = fb.request(graphPath, parameters, httpMethod); listener.onComplete(resp, state); } catch (FileNotFoundException e) { listener.onFileNotFoundException(e, state); } catch (MalformedURLException e) { listener.onMalformedURLException(e, state); } catch (IOException e) { listener.onIOException(e, state); } } }.start(); } /** * Callback interface for API requests. * * Each method includes a 'state' parameter that identifies the calling * request. It will be set to the value passed when originally calling the * request method, or null if none was passed. */ public static interface RequestListener { /** * Called when a request completes with the given response. * * Executed by a background thread: do not update the UI in this method. */ public void onComplete(String response, Object state); /** * Called when a request has a network or request error. * * Executed by a background thread: do not update the UI in this method. */ public void onIOException(IOException e, Object state); /** * Called when a request fails because the requested resource is * invalid or does not exist. * * Executed by a background thread: do not update the UI in this method. */ public void onFileNotFoundException(FileNotFoundException e, Object state); /** * Called if an invalid graph path is provided (which may result in a * malformed URL). * * Executed by a background thread: do not update the UI in this method. */ public void onMalformedURLException(MalformedURLException e, Object state); /** * Called when the server-side Facebook method fails. * * Executed by a background thread: do not update the UI in this method. */ public void onFacebookError(FacebookError e, Object state); } }
Java
/* * Copyright 2010 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.facebook; import java.util.LinkedList; public class SessionEvents { private static LinkedList<AuthListener> mAuthListeners = new LinkedList<AuthListener>(); private static LinkedList<LogoutListener> mLogoutListeners = new LinkedList<LogoutListener>(); /** * Associate the given listener with this Facebook object. The listener's * callback interface will be invoked when authentication events occur. * * @param listener * The callback object for notifying the application when auth * events happen. */ public static void addAuthListener(AuthListener listener) { mAuthListeners.add(listener); } /** * Remove the given listener from the list of those that will be notified * when authentication events occur. * * @param listener * The callback object for notifying the application when auth * events happen. */ public static void removeAuthListener(AuthListener listener) { mAuthListeners.remove(listener); } /** * Associate the given listener with this Facebook object. The listener's * callback interface will be invoked when logout occurs. * * @param listener * The callback object for notifying the application when log out * starts and finishes. */ public static void addLogoutListener(LogoutListener listener) { mLogoutListeners.add(listener); } /** * Remove the given listener from the list of those that will be notified * when logout occurs. * * @param listener * The callback object for notifying the application when log out * starts and finishes. */ public static void removeLogoutListener(LogoutListener listener) { mLogoutListeners.remove(listener); } public static void onLoginSuccess() { for (AuthListener listener : mAuthListeners) { listener.onAuthSucceed(); } } public static void onLoginError(String error) { for (AuthListener listener : mAuthListeners) { listener.onAuthFail(error); } } public static void onLogoutBegin() { for (LogoutListener l : mLogoutListeners) { l.onLogoutBegin(); } } public static void onLogoutFinish() { for (LogoutListener l : mLogoutListeners) { l.onLogoutFinish(); } } /** * Callback interface for authorization events. * */ public static interface AuthListener { /** * Called when a auth flow completes successfully and a valid OAuth * Token was received. * * Executed by the thread that initiated the authentication. * * API requests can now be made. */ public void onAuthSucceed(); /** * Called when a login completes unsuccessfully with an error. * * Executed by the thread that initiated the authentication. */ public void onAuthFail(String error); } /** * Callback interface for logout events. * */ public static interface LogoutListener { /** * Called when logout begins, before session is invalidated. * Last chance to make an API call. * * Executed by the thread that initiated the logout. */ public void onLogoutBegin(); /** * Called when the session information has been cleared. * UI should be updated to reflect logged-out state. * * Executed by the thread that initiated the logout. */ public void onLogoutFinish(); } }
Java
/* * Copyright 2010 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package oauth.facebook; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import android.widget.LinearLayout; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.widget.CustomDialog; public class FacebookActivity extends BasicActivity { static final int FB_BLUE = 0xFF6D84B4; static final float[] DIMENSIONS_DIFF_LANDSCAPE = {20, 60}; static final float[] DIMENSIONS_DIFF_PORTRAIT = {40, 60}; static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); static final int MARGIN = 4; static final int PADDING = 2; static final String DISPLAY_STRING = "touch"; static final String FB_ICON = "icon.png"; private String mUrl; private CustomDialog mSpinner; private WebView mWebView; private FrameLayout mContent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mUrl = getIntent().getStringExtra("url"); mSpinner = new CustomDialog(this); View progressview = LayoutInflater.from(this).inflate(R.layout.progress_dialog, null); CustomDialog.Builder progressBuilder = new CustomDialog.Builder(this); progressBuilder.setContentView(progressview); mSpinner = progressBuilder.create(); mContent = new FrameLayout(this); mContent.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); /* Create the 'x' image, but don't add to the mContent 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 webivew and add it the mContent layout */ // int crossWidth = mCrossImage.getDrawable().getIntrinsicWidth(); setUpWebView(); /* Finally add the 'x' image to the mContent layout and * add mContent to the Dialog view */ // mContent.addView(mCrossImage, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); setContentView(mContent); } // private void createCrossImage() { // mCrossImage = new ImageView(this); // // Dismiss the dialog when user click on the 'x' // mCrossImage.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // Facebook.listener.onCancel(); // finish(); // } // }); // Drawable crossDrawable = getResources().getDrawable(R.drawable.close); // mCrossImage.setImageDrawable(crossDrawable); // /* 'x' should not be visible while webview is loading // * make it visible only after webview has fully loaded // */ // mCrossImage.setVisibility(View.INVISIBLE); // } private void setUpWebView() { LinearLayout webViewContainer = new LinearLayout(this); mWebView = new WebView(this); mWebView.setVerticalScrollBarEnabled(false); mWebView.setHorizontalScrollBarEnabled(false); mWebView.setWebViewClient(new FacebookActivity.FbWebViewClient()); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.loadUrl(mUrl); mWebView.setLayoutParams(FILL); mWebView.setVisibility(View.INVISIBLE); mWebView.getSettings().setSavePassword(false); // webViewContainer.setPadding(margin, margin, margin, margin); webViewContainer.addView(mWebView); mContent.addView(webViewContainer); } private class FbWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Util.logd("Facebook-WebView", "Redirect URL: " + url); if (url.startsWith(Facebook.REDIRECT_URI)) { Bundle values = Util.parseUrl(url); String error = values.getString("error"); if (error == null) { error = values.getString("error_type"); } if (error == null) { Facebook.listener.onComplete(values); } else if (error.equals("access_denied") || error.equals("OAuthAccessDeniedException")) { Facebook.listener.onCancel(); } else { Facebook.listener.onFacebookError(new FacebookError(error)); } finish(); return true; } else if (url.startsWith(Facebook.CANCEL_URI)) { Facebook.listener.onCancel(); finish(); return true; } else if (url.contains(DISPLAY_STRING)) { return false; } // launch non-dialog URLs in a full browser startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); return true; } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); Facebook.listener.onError( new DialogError(description, errorCode, failingUrl)); finish(); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { Util.logd("Facebook-WebView", "Webview loading URL: " + url); super.onPageStarted(view, url, favicon); if (mSpinner != null || !mSpinner.isShowing()) { mSpinner.show(); } } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); mSpinner.dismiss(); /* * Once webview is fully loaded, set the mContent background to be transparent * and make visible the 'x' image. */ mContent.setBackgroundColor(Color.TRANSPARENT); mWebView.setVisibility(View.VISIBLE); } } }
Java
/** Automatically generated file. DO NOT MODIFY */ package com.outsourcing.bottle; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.javanet; import com.google.api.client.googleapis.GoogleUtils; import com.google.api.client.http.javanet.NetHttpTransport; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyStore; /** * Utilities for Google APIs based on {@link NetHttpTransport}. * * @since 1.14 * @author Yaniv Inbar */ public class GoogleNetHttpTransport { /** * Returns a new instance of {@link NetHttpTransport} that uses * {@link GoogleUtils#getCertificateTrustStore()} for the trusted certificates using * {@link com.google.api.client.http.javanet.NetHttpTransport.Builder#trustCertificates(KeyStore)} * . * * <p> * This helper method doesn't provide for customization of the {@link NetHttpTransport}, such as * the ability to specify a proxy. To do use, use * {@link com.google.api.client.http.javanet.NetHttpTransport.Builder}, for example: * </p> * * <pre> static HttpTransport newProxyTransport() throws GeneralSecurityException, IOException { NetHttpTransport.Builder builder = new NetHttpTransport.Builder(); builder.trustCertificates(GoogleUtils.getCertificateTrustStore()); builder.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 3128))); return builder.build(); } * </pre> */ public static NetHttpTransport newTrustedTransport() throws GeneralSecurityException, IOException { return new NetHttpTransport.Builder().trustCertificates(GoogleUtils.getCertificateTrustStore()) .build(); } private GoogleNetHttpTransport() { } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * Google API's support based on the {@code java.net} package. * * @since 1.14 * @author Yaniv Inbar */ package com.google.api.client.googleapis.javanet;
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.apache; import com.google.api.client.googleapis.GoogleUtils; import com.google.api.client.http.apache.ApacheHttpTransport; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyStore; /** * Utilities for Google APIs based on {@link ApacheHttpTransport}. * * @since 1.14 * @author Yaniv Inbar */ public final class GoogleApacheHttpTransport { /** * Returns a new instance of {@link ApacheHttpTransport} that uses * {@link GoogleUtils#getCertificateTrustStore()} for the trusted certificates using * {@link com.google.api.client.http.apache.ApacheHttpTransport.Builder#trustCertificates(KeyStore)}. */ public static ApacheHttpTransport newTrustedTransport() throws GeneralSecurityException, IOException { return new ApacheHttpTransport.Builder().trustCertificates( GoogleUtils.getCertificateTrustStore()).build(); } private GoogleApacheHttpTransport() { } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * Google API's support based on the Apache HTTP Client. * * @since 1.14 * @author Yaniv Inbar */ package com.google.api.client.googleapis.apache;
Java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.services; import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.util.ObjectParser; import com.google.api.client.util.Preconditions; import com.google.api.client.util.Strings; import java.io.IOException; import java.util.logging.Logger; /** * Abstract thread-safe Google client. * * @since 1.12 * @author Yaniv Inbar */ public abstract class AbstractGoogleClient { static final Logger LOGGER = Logger.getLogger(AbstractGoogleClient.class.getName()); /** The request factory for connections to the server. */ private final HttpRequestFactory requestFactory; /** * Initializer to use when creating an {@link AbstractGoogleClientRequest} or {@code null} for * none. */ private final GoogleClientRequestInitializer googleClientRequestInitializer; /** * Root URL of the service, for example {@code "https://www.googleapis.com/"}. Must be URL-encoded * and must end with a "/". */ private final String rootUrl; /** * Service path, for example {@code "tasks/v1/"}. Must be URL-encoded and must end with a "/". */ private final String servicePath; /** * Application name to be sent in the User-Agent header of each request or {@code null} for none. */ private final String applicationName; /** Object parser or {@code null} for none. */ private final ObjectParser objectParser; /** Whether discovery pattern checks should be suppressed on required parameters. */ private boolean suppressPatternChecks; /** Whether discovery required parameter checks should be suppressed. */ private boolean suppressRequiredParameterChecks; /** * @param builder builder * * @since 1.14 */ protected AbstractGoogleClient(Builder builder) { googleClientRequestInitializer = builder.googleClientRequestInitializer; rootUrl = normalizeRootUrl(builder.rootUrl); servicePath = normalizeServicePath(builder.servicePath); if (Strings.isNullOrEmpty(builder.applicationName)) { LOGGER.warning("Application name is not set. Call Builder#setApplicationName."); } applicationName = builder.applicationName; requestFactory = builder.httpRequestInitializer == null ? builder.transport.createRequestFactory() : builder.transport.createRequestFactory(builder.httpRequestInitializer); objectParser = builder.objectParser; suppressPatternChecks = builder.suppressPatternChecks; suppressRequiredParameterChecks = builder.suppressRequiredParameterChecks; } /** * Returns the URL-encoded root URL of the service, for example * {@code "https://www.googleapis.com/"}. * * <p> * Must end with a "/". * </p> */ public final String getRootUrl() { return rootUrl; } /** * Returns the URL-encoded service path of the service, for example {@code "tasks/v1/"}. * * <p> * Must end with a "/" and not begin with a "/". It is allowed to be an empty string {@code ""} or * a forward slash {@code "/"}, if it is a forward slash then it is treated as an empty string * </p> */ public final String getServicePath() { return servicePath; } /** * Returns the URL-encoded base URL of the service, for example * {@code "https://www.googleapis.com/tasks/v1/"}. * * <p> * Must end with a "/". It is guaranteed to be equal to {@code getRootUrl() + getServicePath()}. * </p> */ public final String getBaseUrl() { return rootUrl + servicePath; } /** * Returns the application name to be sent in the User-Agent header of each request or * {@code null} for none. */ public final String getApplicationName() { return applicationName; } /** Returns the HTTP request factory. */ public final HttpRequestFactory getRequestFactory() { return requestFactory; } /** Returns the Google client request initializer or {@code null} for none. */ public final GoogleClientRequestInitializer getGoogleClientRequestInitializer() { return googleClientRequestInitializer; } /** * Returns the object parser or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public ObjectParser getObjectParser() { return objectParser; } /** * Initializes a {@link AbstractGoogleClientRequest} using a * {@link GoogleClientRequestInitializer}. * * <p> * Must be called before the Google client request is executed, preferably right after the request * is instantiated. Sample usage: * </p> * * <pre> public class Get extends HttpClientRequest { ... } public Get get(String userId) throws IOException { Get result = new Get(userId); initialize(result); return result; } * </pre> * * <p> * Subclasses may override by calling the super implementation. * </p> * * @param httpClientRequest Google client request type */ protected void initialize(AbstractGoogleClientRequest<?> httpClientRequest) throws IOException { if (getGoogleClientRequestInitializer() != null) { getGoogleClientRequestInitializer().initialize(httpClientRequest); } } /** * Create an {@link BatchRequest} object from this Google API client instance. * * <p> * Sample usage: * </p> * * <pre> client.batch() .queue(...) .queue(...) .execute(); * </pre> * * @return newly created Batch request */ public final BatchRequest batch() { return batch(null); } /** * Create an {@link BatchRequest} object from this Google API client instance. * * <p> * Sample usage: * </p> * * <pre> client.batch(httpRequestInitializer) .queue(...) .queue(...) .execute(); * </pre> * * @param httpRequestInitializer The initializer to use when creating the top-level batch HTTP * request or {@code null} for none * @return newly created Batch request */ public final BatchRequest batch(HttpRequestInitializer httpRequestInitializer) { BatchRequest batch = new BatchRequest(getRequestFactory().getTransport(), httpRequestInitializer); batch.setBatchUrl(new GenericUrl(getRootUrl() + "batch")); return batch; } /** Returns whether discovery pattern checks should be suppressed on required parameters. */ public final boolean getSuppressPatternChecks() { return suppressPatternChecks; } /** * Returns whether discovery required parameter checks should be suppressed. * * @since 1.14 */ public final boolean getSuppressRequiredParameterChecks() { return suppressRequiredParameterChecks; } /** If the specified root URL does not end with a "/" then a "/" is added to the end. */ static String normalizeRootUrl(String rootUrl) { Preconditions.checkNotNull(rootUrl, "root URL cannot be null."); if (!rootUrl.endsWith("/")) { rootUrl += "/"; } return rootUrl; } /** * If the specified service path does not end with a "/" then a "/" is added to the end. If the * specified service path begins with a "/" then the "/" is removed. */ static String normalizeServicePath(String servicePath) { Preconditions.checkNotNull(servicePath, "service path cannot be null"); if (servicePath.length() == 1) { Preconditions.checkArgument( "/".equals(servicePath), "service path must equal \"/\" if it is of length 1."); servicePath = ""; } else if (servicePath.length() > 0) { if (!servicePath.endsWith("/")) { servicePath += "/"; } if (servicePath.startsWith("/")) { servicePath = servicePath.substring(1); } } return servicePath; } /** * Builder for {@link AbstractGoogleClient}. * * <p> * Implementation is not thread-safe. * </p> */ public abstract static class Builder { /** HTTP transport. */ final HttpTransport transport; /** * Initializer to use when creating an {@link AbstractGoogleClientRequest} or {@code null} for * none. */ GoogleClientRequestInitializer googleClientRequestInitializer; /** HTTP request initializer or {@code null} for none. */ HttpRequestInitializer httpRequestInitializer; /** Object parser to use for parsing responses. */ final ObjectParser objectParser; /** The root URL of the service, for example {@code "https://www.googleapis.com/"}. */ String rootUrl; /** The service path of the service, for example {@code "tasks/v1/"}. */ String servicePath; /** * Application name to be sent in the User-Agent header of each request or {@code null} for * none. */ String applicationName; /** Whether discovery pattern checks should be suppressed on required parameters. */ boolean suppressPatternChecks; /** Whether discovery required parameter checks should be suppressed. */ boolean suppressRequiredParameterChecks; /** * Returns an instance of a new builder. * * @param transport The transport to use for requests * @param rootUrl root URL of the service. Must end with a "/" * @param servicePath service path * @param objectParser object parser or {@code null} for none * @param httpRequestInitializer HTTP request initializer or {@code null} for none */ protected Builder(HttpTransport transport, String rootUrl, String servicePath, ObjectParser objectParser, HttpRequestInitializer httpRequestInitializer) { this.transport = Preconditions.checkNotNull(transport); this.objectParser = objectParser; setRootUrl(rootUrl); setServicePath(servicePath); this.httpRequestInitializer = httpRequestInitializer; } /** Builds a new instance of {@link AbstractGoogleClient}. */ public abstract AbstractGoogleClient build(); /** Returns the HTTP transport. */ public final HttpTransport getTransport() { return transport; } /** * Returns the object parser or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public ObjectParser getObjectParser() { return objectParser; } /** * Returns the URL-encoded root URL of the service, for example * {@code https://www.googleapis.com/}. * * <p> * Must be URL-encoded and must end with a "/". * </p> */ public final String getRootUrl() { return rootUrl; } /** * Sets the URL-encoded root URL of the service, for example {@code https://www.googleapis.com/} * . * <p> * If the specified root URL does not end with a "/" then a "/" is added to the end. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setRootUrl(String rootUrl) { this.rootUrl = normalizeRootUrl(rootUrl); return this; } /** * Returns the URL-encoded service path of the service, for example {@code "tasks/v1/"}. * * <p> * Must be URL-encoded and must end with a "/" and not begin with a "/". It is allowed to be an * empty string {@code ""}. * </p> */ public final String getServicePath() { return servicePath; } /** * Sets the URL-encoded service path of the service, for example {@code "tasks/v1/"}. * * <p> * It is allowed to be an empty string {@code ""} or a forward slash {@code "/"}, if it is a * forward slash then it is treated as an empty string. This is determined when the library is * generated and normally should not be changed. * </p> * * <p> * If the specified service path does not end with a "/" then a "/" is added to the end. If the * specified service path begins with a "/" then the "/" is removed. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setServicePath(String servicePath) { this.servicePath = normalizeServicePath(servicePath); return this; } /** Returns the Google client request initializer or {@code null} for none. */ public final GoogleClientRequestInitializer getGoogleClientRequestInitializer() { return googleClientRequestInitializer; } /** * Sets the Google client request initializer or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setGoogleClientRequestInitializer( GoogleClientRequestInitializer googleClientRequestInitializer) { this.googleClientRequestInitializer = googleClientRequestInitializer; return this; } /** Returns the HTTP request initializer or {@code null} for none. */ public final HttpRequestInitializer getHttpRequestInitializer() { return httpRequestInitializer; } /** * Sets the HTTP request initializer or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) { this.httpRequestInitializer = httpRequestInitializer; return this; } /** * Returns the application name to be used in the UserAgent header of each request or * {@code null} for none. */ public final String getApplicationName() { return applicationName; } /** * Sets the application name to be used in the UserAgent header of each request or {@code null} * for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setApplicationName(String applicationName) { this.applicationName = applicationName; return this; } /** Returns whether discovery pattern checks should be suppressed on required parameters. */ public final boolean getSuppressPatternChecks() { return suppressPatternChecks; } /** * Sets whether discovery pattern checks should be suppressed on required parameters. * * <p> * Default value is {@code false}. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { this.suppressPatternChecks = suppressPatternChecks; return this; } /** * Returns whether discovery required parameter checks should be suppressed. * * @since 1.14 */ public final boolean getSuppressRequiredParameterChecks() { return suppressRequiredParameterChecks; } /** * Sets whether discovery required parameter checks should be suppressed. * * <p> * Default value is {@code false}. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @since 1.14 */ public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { this.suppressRequiredParameterChecks = suppressRequiredParameterChecks; return this; } /** * Suppresses all discovery pattern and required parameter checks. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @since 1.14 */ public Builder setSuppressAllChecks(boolean suppressAllChecks) { return setSuppressPatternChecks(true).setSuppressRequiredParameterChecks(true); } } }
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.services.json; import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.googleapis.batch.json.JsonBatchCallback; import com.google.api.client.googleapis.json.GoogleJsonErrorContainer; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.UriTemplate; import com.google.api.client.http.json.JsonHttpContent; import java.io.IOException; /** * Google JSON request for a {@link AbstractGoogleJsonClient}. * * <p> * Implementation is not thread-safe. * </p> * * @param <T> type of the response * @since 1.12 * @author Yaniv Inbar */ public abstract class AbstractGoogleJsonClientRequest<T> extends AbstractGoogleClientRequest<T> { /** POJO that can be serialized into JSON content or {@code null} for none. */ private final Object jsonContent; /** * @param abstractGoogleJsonClient Google JSON client * @param requestMethod HTTP Method * @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/" * the base path from the base URL will be stripped out. The URI template can also be a * full URL. URI template expansion is done using * {@link UriTemplate#expand(String, String, Object, boolean)} * @param jsonContent POJO that can be serialized into JSON content or {@code null} for none * @param responseClass response class to parse into */ protected AbstractGoogleJsonClientRequest(AbstractGoogleJsonClient abstractGoogleJsonClient, String requestMethod, String uriTemplate, Object jsonContent, Class<T> responseClass) { super(abstractGoogleJsonClient, requestMethod, uriTemplate, jsonContent == null ? null : new JsonHttpContent(abstractGoogleJsonClient.getJsonFactory(), jsonContent) .setWrapperKey(abstractGoogleJsonClient.getObjectParser().getWrapperKeys().isEmpty() ? null : "data"), responseClass); this.jsonContent = jsonContent; } @Override public AbstractGoogleJsonClient getAbstractGoogleClient() { return (AbstractGoogleJsonClient) super.getAbstractGoogleClient(); } @Override public AbstractGoogleJsonClientRequest<T> setDisableGZipContent(boolean disableGZipContent) { return (AbstractGoogleJsonClientRequest<T>) super.setDisableGZipContent(disableGZipContent); } @Override public AbstractGoogleJsonClientRequest<T> setRequestHeaders(HttpHeaders headers) { return (AbstractGoogleJsonClientRequest<T>) super.setRequestHeaders(headers); } /** * Queues the request into the specified batch request container. * * <p> * Batched requests are then executed when {@link BatchRequest#execute()} is called. * </p> * <p> * Example usage: * </p> * * <pre> request.queue(batchRequest, new JsonBatchCallback&lt;SomeResponseType&gt;() { public void onSuccess(SomeResponseType content, HttpHeaders responseHeaders) { log("Success"); } public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) { log(e.getMessage()); } }); * </pre> * * * @param batchRequest batch request container * @param callback batch callback */ public final void queue(BatchRequest batchRequest, JsonBatchCallback<T> callback) throws IOException { super.queue(batchRequest, GoogleJsonErrorContainer.class, callback); } @Override protected GoogleJsonResponseException newExceptionOnError(HttpResponse response) { return GoogleJsonResponseException.from(getAbstractGoogleClient().getJsonFactory(), response); } /** Returns POJO that can be serialized into JSON content or {@code null} for none. */ public Object getJsonContent() { return jsonContent; } @Override public AbstractGoogleJsonClientRequest<T> set(String fieldName, Object value) { return (AbstractGoogleJsonClientRequest<T>) super.set(fieldName, value); } }
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.services.json; import com.google.api.client.googleapis.services.AbstractGoogleClient; import com.google.api.client.googleapis.services.GoogleClientRequestInitializer; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonObjectParser; import java.util.Arrays; import java.util.Collections; /** * Thread-safe Google JSON client. * * @since 1.12 * @author Yaniv Inbar */ public abstract class AbstractGoogleJsonClient extends AbstractGoogleClient { /** * @param builder builder * * @since 1.14 */ protected AbstractGoogleJsonClient(Builder builder) { super(builder); } @Override public JsonObjectParser getObjectParser() { return (JsonObjectParser) super.getObjectParser(); } /** Returns the JSON Factory. */ public final JsonFactory getJsonFactory() { return getObjectParser().getJsonFactory(); } /** * Builder for {@link AbstractGoogleJsonClient}. * * <p> * Implementation is not thread-safe. * </p> */ public abstract static class Builder extends AbstractGoogleClient.Builder { /** * @param transport HTTP transport * @param jsonFactory JSON factory * @param rootUrl root URL of the service * @param servicePath service path * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @param legacyDataWrapper whether using the legacy data wrapper in responses */ protected Builder(HttpTransport transport, JsonFactory jsonFactory, String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer, boolean legacyDataWrapper) { super(transport, rootUrl, servicePath, new JsonObjectParser.Builder( jsonFactory).setWrapperKeys( legacyDataWrapper ? Arrays.asList("data", "error") : Collections.<String>emptySet()) .build(), httpRequestInitializer); } @Override public final JsonObjectParser getObjectParser() { return (JsonObjectParser) super.getObjectParser(); } /** Returns the JSON Factory. */ public final JsonFactory getJsonFactory() { return getObjectParser().getJsonFactory(); } @Override public abstract AbstractGoogleJsonClient build(); @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setGoogleClientRequestInitializer( GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } @Override public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } } }
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * Contains the basis for the generated service-specific libraries based on the JSON format. * * @since 1.12 * @author Yaniv Inbar */ package com.google.api.client.googleapis.services.json;
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.services.json; import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer; import java.io.IOException; /** * Google JSON client request initializer implementation for setting properties like key and userIp. * * <p> * The simplest usage is to use it to set the key parameter: * </p> * * <pre> public static final GoogleClientRequestInitializer KEY_INITIALIZER = new CommonGoogleJsonClientRequestInitializer(KEY); * </pre> * * <p> * There is also a constructor to set both the key and userIp parameters: * </p> * * <pre> public static final GoogleClientRequestInitializer INITIALIZER = new CommonGoogleJsonClientRequestInitializer(KEY, USER_IP); * </pre> * * <p> * If you want to implement custom logic, extend it like this: * </p> * * <pre> public static class MyRequestInitializer extends CommonGoogleJsonClientRequestInitializer { {@literal @}Override public void initialize(AbstractGoogleJsonClientRequest{@literal <}?{@literal >} request) throws IOException { // custom logic } } * </pre> * * <p> * Finally, to set the key and userIp parameters and insert custom logic, extend it like this: * </p> * * <pre> public static class MyKeyRequestInitializer extends CommonGoogleJsonClientRequestInitializer { public MyKeyRequestInitializer() { super(KEY, USER_IP); } {@literal @}Override public void initializeJsonRequest( AbstractGoogleJsonClientRequest{@literal <}?{@literal >} request) throws IOException { // custom logic } } * </pre> * * <p> * Subclasses should be thread-safe. * </p> * * @since 1.12 * @author Yaniv Inbar */ public class CommonGoogleJsonClientRequestInitializer extends CommonGoogleClientRequestInitializer { public CommonGoogleJsonClientRequestInitializer() { super(); } /** * @param key API key or {@code null} to leave it unchanged */ public CommonGoogleJsonClientRequestInitializer(String key) { super(key); } /** * @param key API key or {@code null} to leave it unchanged * @param userIp user IP or {@code null} to leave it unchanged */ public CommonGoogleJsonClientRequestInitializer(String key, String userIp) { super(key, userIp); } @Override public final void initialize(AbstractGoogleClientRequest<?> request) throws IOException { super.initialize(request); initializeJsonRequest((AbstractGoogleJsonClientRequest<?>) request); } /** * Initializes a Google JSON client request. * * <p> * Default implementation does nothing. Called from * {@link #initialize(AbstractGoogleClientRequest)}. * </p> * * @throws IOException I/O exception */ protected void initializeJsonRequest(AbstractGoogleJsonClientRequest<?> request) throws IOException { } }
Java
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * Contains the basis for the generated service-specific libraries. * * @since 1.6 * @author Ravi Mistry */ package com.google.api.client.googleapis.services;
Java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.services; import java.io.IOException; /** * Google client request initializer. * * <p> * For example, this might be used to set a key URL query parameter on all requests: * </p> * * <pre> public class KeyRequestInitializer implements GoogleClientRequestInitializer { public void initialize(GoogleClientRequest<?> request) { request.put("key", KEY); } } * </pre> * * <p> * Implementations should be thread-safe. * </p> * * @since 1.12 * @author Yaniv Inbar */ public interface GoogleClientRequestInitializer { /** Initializes a Google client request. */ void initialize(AbstractGoogleClientRequest<?> request) throws IOException; }
Java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.services; import com.google.api.client.googleapis.MethodOverride; import com.google.api.client.googleapis.batch.BatchCallback; import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.googleapis.media.MediaHttpDownloader; import com.google.api.client.googleapis.media.MediaHttpUploader; import com.google.api.client.http.AbstractInputStreamContent; import com.google.api.client.http.EmptyContent; import com.google.api.client.http.GZipEncoding; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpContent; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpMethods; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpResponseInterceptor; import com.google.api.client.http.UriTemplate; import com.google.api.client.util.GenericData; import com.google.api.client.util.Preconditions; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Abstract Google client request for a {@link AbstractGoogleClient}. * * <p> * Implementation is not thread-safe. * </p> * * @param <T> type of the response * * @since 1.12 * @author Yaniv Inbar */ public abstract class AbstractGoogleClientRequest<T> extends GenericData { /** Google client. */ private final AbstractGoogleClient abstractGoogleClient; /** HTTP method. */ private final String requestMethod; /** URI template for the path relative to the base URL. */ private final String uriTemplate; /** HTTP content or {@code null} for none. */ private final HttpContent httpContent; /** HTTP headers used for the Google client request. */ private HttpHeaders requestHeaders = new HttpHeaders(); /** HTTP headers of the last response or {@code null} before request has been executed. */ private HttpHeaders lastResponseHeaders; /** Status code of the last response or {@code -1} before request has been executed. */ private int lastStatusCode = -1; /** Status message of the last response or {@code null} before request has been executed. */ private String lastStatusMessage; /** Whether to disable GZip compression of HTTP content. */ private boolean disableGZipContent; /** Response class to parse into. */ private Class<T> responseClass; /** Media HTTP uploader or {@code null} for none. */ private MediaHttpUploader uploader; /** Media HTTP downloader or {@code null} for none. */ private MediaHttpDownloader downloader; /** * @param abstractGoogleClient Google client * @param requestMethod HTTP Method * @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/" * the base path from the base URL will be stripped out. The URI template can also be a * full URL. URI template expansion is done using * {@link UriTemplate#expand(String, String, Object, boolean)} * @param httpContent HTTP content or {@code null} for none * @param responseClass response class to parse into */ protected AbstractGoogleClientRequest(AbstractGoogleClient abstractGoogleClient, String requestMethod, String uriTemplate, HttpContent httpContent, Class<T> responseClass) { this.responseClass = Preconditions.checkNotNull(responseClass); this.abstractGoogleClient = Preconditions.checkNotNull(abstractGoogleClient); this.requestMethod = Preconditions.checkNotNull(requestMethod); this.uriTemplate = Preconditions.checkNotNull(uriTemplate); this.httpContent = httpContent; // application name String applicationName = abstractGoogleClient.getApplicationName(); if (applicationName != null) { requestHeaders.setUserAgent(applicationName); } } /** Returns whether to disable GZip compression of HTTP content. */ public final boolean getDisableGZipContent() { return disableGZipContent; } /** * Sets whether to disable GZip compression of HTTP content. * * <p> * By default it is {@code false}. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractGoogleClientRequest<T> setDisableGZipContent(boolean disableGZipContent) { this.disableGZipContent = disableGZipContent; return this; } /** Returns the HTTP method. */ public final String getRequestMethod() { return requestMethod; } /** Returns the URI template for the path relative to the base URL. */ public final String getUriTemplate() { return uriTemplate; } /** Returns the HTTP content or {@code null} for none. */ public final HttpContent getHttpContent() { return httpContent; } /** * Returns the Google client. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractGoogleClient getAbstractGoogleClient() { return abstractGoogleClient; } /** Returns the HTTP headers used for the Google client request. */ public final HttpHeaders getRequestHeaders() { return requestHeaders; } /** * Sets the HTTP headers used for the Google client request. * * <p> * These headers are set on the request after {@link #buildHttpRequest} is called, this means that * {@link HttpRequestInitializer#initialize} is called first. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractGoogleClientRequest<T> setRequestHeaders(HttpHeaders headers) { this.requestHeaders = headers; return this; } /** * Returns the HTTP headers of the last response or {@code null} before request has been executed. */ public final HttpHeaders getLastResponseHeaders() { return lastResponseHeaders; } /** * Returns the status code of the last response or {@code -1} before request has been executed. */ public final int getLastStatusCode() { return lastStatusCode; } /** * Returns the status message of the last response or {@code null} before request has been * executed. */ public final String getLastStatusMessage() { return lastStatusMessage; } /** Returns the response class to parse into. */ public final Class<T> getResponseClass() { return responseClass; } /** Returns the media HTTP Uploader or {@code null} for none. */ public final MediaHttpUploader getMediaHttpUploader() { return uploader; } /** * Initializes the media HTTP uploader based on the media content. * * @param mediaContent media content */ protected final void initializeMediaUpload(AbstractInputStreamContent mediaContent) { HttpRequestFactory requestFactory = abstractGoogleClient.getRequestFactory(); this.uploader = new MediaHttpUploader( mediaContent, requestFactory.getTransport(), requestFactory.getInitializer()); this.uploader.setInitiationRequestMethod(requestMethod); if (httpContent != null) { this.uploader.setMetadata(httpContent); } } /** Returns the media HTTP downloader or {@code null} for none. */ public final MediaHttpDownloader getMediaHttpDownloader() { return downloader; } /** Initializes the media HTTP downloader. */ protected final void initializeMediaDownload() { HttpRequestFactory requestFactory = abstractGoogleClient.getRequestFactory(); this.downloader = new MediaHttpDownloader(requestFactory.getTransport(), requestFactory.getInitializer()); } /** * Creates a new instance of {@link GenericUrl} suitable for use against this service. * * <p> * Subclasses may override by calling the super implementation. * </p> * * @return newly created {@link GenericUrl} */ public GenericUrl buildHttpRequestUrl() { return new GenericUrl( UriTemplate.expand(abstractGoogleClient.getBaseUrl(), uriTemplate, this, true)); } /** * Create a request suitable for use against this service. * * <p> * Subclasses may override by calling the super implementation. * </p> */ public HttpRequest buildHttpRequest() throws IOException { return buildHttpRequest(false); } /** * Create a request suitable for use against this service, but using HEAD instead of GET. * * <p> * Only supported when the original request method is GET. * </p> * * <p> * Subclasses may override by calling the super implementation. * </p> */ protected HttpRequest buildHttpRequestUsingHead() throws IOException { return buildHttpRequest(true); } /** Create a request suitable for use against this service. */ private HttpRequest buildHttpRequest(boolean usingHead) throws IOException { Preconditions.checkArgument(uploader == null); Preconditions.checkArgument(!usingHead || requestMethod.equals(HttpMethods.GET)); String requestMethodToUse = usingHead ? HttpMethods.HEAD : requestMethod; final HttpRequest httpRequest = getAbstractGoogleClient() .getRequestFactory().buildRequest(requestMethodToUse, buildHttpRequestUrl(), httpContent); new MethodOverride().intercept(httpRequest); httpRequest.setParser(getAbstractGoogleClient().getObjectParser()); // custom methods may use POST with no content but require a Content-Length header if (httpContent == null && (requestMethod.equals(HttpMethods.POST) || requestMethod.equals(HttpMethods.PUT) || requestMethod.equals(HttpMethods.PATCH))) { httpRequest.setContent(new EmptyContent()); } httpRequest.getHeaders().putAll(requestHeaders); if (!disableGZipContent) { httpRequest.setEncoding(new GZipEncoding()); } final HttpResponseInterceptor responseInterceptor = httpRequest.getResponseInterceptor(); httpRequest.setResponseInterceptor(new HttpResponseInterceptor() { public void interceptResponse(HttpResponse response) throws IOException { if (responseInterceptor != null) { responseInterceptor.interceptResponse(response); } if (!response.isSuccessStatusCode() && httpRequest.getThrowExceptionOnExecuteError()) { throw newExceptionOnError(response); } } }); return httpRequest; } /** * Sends the metadata request to the server and returns the raw metadata {@link HttpResponse}. * * <p> * Callers are responsible for disconnecting the HTTP response by calling * {@link HttpResponse#disconnect}. Example usage: * </p> * * <pre> HttpResponse response = request.executeUnparsed(); try { // process response.. } finally { response.disconnect(); } * </pre> * * <p> * Subclasses may override by calling the super implementation. * </p> * * @return the {@link HttpResponse} */ public HttpResponse executeUnparsed() throws IOException { return executeUnparsed(false); } /** * Sends the media request to the server and returns the raw media {@link HttpResponse}. * * <p> * Callers are responsible for disconnecting the HTTP response by calling * {@link HttpResponse#disconnect}. Example usage: * </p> * * <pre> HttpResponse response = request.executeMedia(); try { // process response.. } finally { response.disconnect(); } * </pre> * * <p> * Subclasses may override by calling the super implementation. * </p> * * @return the {@link HttpResponse} */ protected HttpResponse executeMedia() throws IOException { set("alt", "media"); return executeUnparsed(); } /** * Sends the metadata request using HEAD to the server and returns the raw metadata * {@link HttpResponse} for the response headers. * * <p> * Only supported when the original request method is GET. The response content is assumed to be * empty and ignored. Calls {@link HttpResponse#ignore()} so there is no need to disconnect the * response. Example usage: * </p> * * <pre> HttpResponse response = request.executeUsingHead(); // look at response.getHeaders() * </pre> * * <p> * Subclasses may override by calling the super implementation. * </p> * * @return the {@link HttpResponse} */ protected HttpResponse executeUsingHead() throws IOException { Preconditions.checkArgument(uploader == null); HttpResponse response = executeUnparsed(true); response.ignore(); return response; } /** * Sends the metadata request using the given request method to the server and returns the raw * metadata {@link HttpResponse}. */ private HttpResponse executeUnparsed(boolean usingHead) throws IOException { HttpResponse response; if (uploader == null) { // normal request (not upload) response = buildHttpRequest(usingHead).execute(); } else { // upload request GenericUrl httpRequestUrl = buildHttpRequestUrl(); HttpRequest httpRequest = getAbstractGoogleClient() .getRequestFactory().buildRequest(requestMethod, httpRequestUrl, httpContent); boolean throwExceptionOnExecuteError = httpRequest.getThrowExceptionOnExecuteError(); response = uploader.setInitiationHeaders(requestHeaders) .setDisableGZipContent(disableGZipContent).upload(httpRequestUrl); response.getRequest().setParser(getAbstractGoogleClient().getObjectParser()); // process any error if (throwExceptionOnExecuteError && !response.isSuccessStatusCode()) { throw newExceptionOnError(response); } } // process response lastResponseHeaders = response.getHeaders(); lastStatusCode = response.getStatusCode(); lastStatusMessage = response.getStatusMessage(); return response; } /** * Returns the exception to throw on an HTTP error response as defined by * {@link HttpResponse#isSuccessStatusCode()}. * * <p> * It is guaranteed that {@link HttpResponse#isSuccessStatusCode()} is {@code false}. Default * implementation is to call {@link HttpResponseException#HttpResponseException(HttpResponse)}, * but subclasses may override. * </p> * * @param response HTTP response * @return exception to throw */ protected IOException newExceptionOnError(HttpResponse response) { return new HttpResponseException(response); } /** * Sends the metadata request to the server and returns the parsed metadata response. * * <p> * Subclasses may override by calling the super implementation. * </p> * * @return parsed HTTP response */ public T execute() throws IOException { return executeUnparsed().parseAs(responseClass); } /** * Sends the metadata request to the server and returns the metadata content input stream of * {@link HttpResponse}. * * <p> * Callers are responsible for closing the input stream after it is processed. Example sample: * </p> * * <pre> InputStream is = request.executeAsInputStream(); try { // Process input stream.. } finally { is.close(); } * </pre> * * <p> * Subclasses may override by calling the super implementation. * </p> * * @return input stream of the response content */ public InputStream executeAsInputStream() throws IOException { return executeUnparsed().getContent(); } /** * Sends the media request to the server and returns the media content input stream of * {@link HttpResponse}. * * <p> * Callers are responsible for closing the input stream after it is processed. Example sample: * </p> * * <pre> InputStream is = request.executeMediaAsInputStream(); try { // Process input stream.. } finally { is.close(); } * </pre> * * <p> * Subclasses may override by calling the super implementation. * </p> * * @return input stream of the response content */ protected InputStream executeMediaAsInputStream() throws IOException { return executeMedia().getContent(); } /** * Sends the metadata request to the server and writes the metadata content input stream of * {@link HttpResponse} into the given destination output stream. * * <p> * This method closes the content of the HTTP response from {@link HttpResponse#getContent()}. * </p> * * <p> * Subclasses may override by calling the super implementation. * </p> * * @param outputStream destination output stream */ public void executeAndDownloadTo(OutputStream outputStream) throws IOException { executeUnparsed().download(outputStream); } /** * Sends the media request to the server and writes the media content input stream of * {@link HttpResponse} into the given destination output stream. * * <p> * This method closes the content of the HTTP response from {@link HttpResponse#getContent()}. * </p> * * <p> * Subclasses may override by calling the super implementation. * </p> * * @param outputStream destination output stream */ protected void executeMediaAndDownloadTo(OutputStream outputStream) throws IOException { if (downloader == null) { executeMedia().download(outputStream); } else { downloader.download(buildHttpRequestUrl(), requestHeaders, outputStream); } } /** * Queues the request into the specified batch request container using the specified error class. * * <p> * Batched requests are then executed when {@link BatchRequest#execute()} is called. * </p> * * @param batchRequest batch request container * @param errorClass data class the unsuccessful response will be parsed into or * {@code Void.class} to ignore the content * @param callback batch callback */ public final <E> void queue( BatchRequest batchRequest, Class<E> errorClass, BatchCallback<T, E> callback) throws IOException { Preconditions.checkArgument(uploader == null, "Batching media requests is not supported"); batchRequest.queue(buildHttpRequest(), getResponseClass(), errorClass, callback); } // @SuppressWarnings was added here because this is generic class. // see: http://stackoverflow.com/questions/4169806/java-casting-object-to-a-generic-type and // http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#Type%20Erasure // for more details @SuppressWarnings("unchecked") @Override public AbstractGoogleClientRequest<T> set(String fieldName, Object value) { return (AbstractGoogleClientRequest<T>) super.set(fieldName, value); } /** * Ensures that the specified required parameter is not null or * {@link AbstractGoogleClient#getSuppressRequiredParameterChecks()} is true. * * @param value the value of the required parameter * @param name the name of the required parameter * @throws IllegalArgumentException if the specified required parameter is null and * {@link AbstractGoogleClient#getSuppressRequiredParameterChecks()} is false * @since 1.14 */ protected final void checkRequiredParameter(Object value, String name) { Preconditions.checkArgument( abstractGoogleClient.getSuppressRequiredParameterChecks() || value != null, "Required parameter %s must be specified", name); } }
Java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.services; import java.io.IOException; /** * Google common client request initializer implementation for setting properties like key and * userIp. * * <p> * The simplest usage is to use it to set the key parameter: * </p> * * <pre> public static final GoogleClientRequestInitializer KEY_INITIALIZER = new CommonGoogleClientRequestInitializer(KEY); * </pre> * * <p> * There is also a constructor to set both the key and userIp parameters: * </p> * * <pre> public static final GoogleClientRequestInitializer INITIALIZER = new CommonGoogleClientRequestInitializer(KEY, USER_IP); * </pre> * * <p> * If you want to implement custom logic, extend it like this: * </p> * * <pre> public static class MyRequestInitializer extends CommonGoogleClientRequestInitializer { {@literal @}Override public void initialize(AbstractGoogleClientRequest{@literal <}?{@literal >} request) throws IOException { // custom logic } } * </pre> * * <p> * Finally, to set the key and userIp parameters and insert custom logic, extend it like this: * </p> * * <pre> public static class MyRequestInitializer2 extends CommonGoogleClientRequestInitializer { public MyRequestInitializer2() { super(KEY, USER_IP); } {@literal @}Override public void initialize(AbstractGoogleClientRequest{@literal <}?{@literal >} request) throws IOException { super.initialize(request); // must be called to set the key and userIp parameters // insert some additional logic } } * </pre> * * <p> * Subclasses should be thread-safe. * </p> * * @since 1.12 * @author Yaniv Inbar */ public class CommonGoogleClientRequestInitializer implements GoogleClientRequestInitializer { /** API key or {@code null} to leave it unchanged. */ private final String key; /** User IP or {@code null} to leave it unchanged. */ private final String userIp; public CommonGoogleClientRequestInitializer() { this(null); } /** * @param key API key or {@code null} to leave it unchanged */ public CommonGoogleClientRequestInitializer(String key) { this(key, null); } /** * @param key API key or {@code null} to leave it unchanged * @param userIp user IP or {@code null} to leave it unchanged */ public CommonGoogleClientRequestInitializer(String key, String userIp) { this.key = key; this.userIp = userIp; } /** * Subclasses should call super implementation in order to set the key and userIp. * * @throws IOException I/O exception */ public void initialize(AbstractGoogleClientRequest<?> request) throws IOException { if (key != null) { request.put("key", key); } if (userIp != null) { request.put("userIp", userIp); } } /** Returns the API key or {@code null} to leave it unchanged. */ public final String getKey() { return key; } /** Returns the user IP or {@code null} to leave it unchanged. */ public final String getUserIp() { return userIp; } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.compute; import com.google.api.client.auth.oauth2.BearerToken; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.auth.oauth2.CredentialRefreshListener; import com.google.api.client.auth.oauth2.TokenResponse; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonObjectParser; import com.google.api.client.util.Beta; import com.google.api.client.util.Clock; import com.google.api.client.util.Preconditions; import java.io.IOException; import java.util.Collection; /** * {@link Beta} <br/> * Google Compute Engine service accounts OAuth 2.0 credential based on <a * href="https://developers.google.com/compute/docs/authentication">Authenticating from Google * Compute Engine</a>. * * <p> * Sample usage: * </p> * * <pre> public static HttpRequestFactory createRequestFactory( HttpTransport transport, JsonFactory jsonFactory) { return transport.createRequestFactory(new GoogleComputeCredential(transport, jsonFactory)); } * </pre> * * <p> * Implementation is immutable and thread-safe. * </p> * * @since 1.15 * @author Yaniv Inbar */ @Beta public class ComputeCredential extends Credential { /** Metadata Service Account token server encoded URL. */ public static final String TOKEN_SERVER_ENCODED_URL = "http://metadata/computeMetadata/v1beta1/instance/service-accounts/default/token"; /** * @param transport HTTP transport * @param jsonFactory JSON factory */ public ComputeCredential(HttpTransport transport, JsonFactory jsonFactory) { this(new Builder(transport, jsonFactory)); } /** * @param builder builder */ protected ComputeCredential(Builder builder) { super(builder); } @Override protected TokenResponse executeRefreshToken() throws IOException { GenericUrl tokenUrl = new GenericUrl(getTokenServerEncodedUrl()); HttpRequest request = getTransport().createRequestFactory().buildGetRequest(tokenUrl); request.setParser(new JsonObjectParser(getJsonFactory())); return request.execute().parseAs(TokenResponse.class); } /** * {@link Beta} <br/> * Google Compute Engine credential builder. * * <p> * Implementation is not thread-safe. * </p> */ @Beta public static class Builder extends Credential.Builder { /** * @param transport HTTP transport * @param jsonFactory JSON factory */ public Builder(HttpTransport transport, JsonFactory jsonFactory) { super(BearerToken.authorizationHeaderAccessMethod()); setTransport(transport); setJsonFactory(jsonFactory); setTokenServerEncodedUrl(TOKEN_SERVER_ENCODED_URL); } @Override public ComputeCredential build() { return new ComputeCredential(this); } @Override public Builder setTransport(HttpTransport transport) { return (Builder) super.setTransport(Preconditions.checkNotNull(transport)); } @Override public Builder setClock(Clock clock) { return (Builder) super.setClock(clock); } @Override public Builder setJsonFactory(JsonFactory jsonFactory) { return (Builder) super.setJsonFactory(Preconditions.checkNotNull(jsonFactory)); } @Override public Builder setTokenServerUrl(GenericUrl tokenServerUrl) { return (Builder) super.setTokenServerUrl(Preconditions.checkNotNull(tokenServerUrl)); } @Override public Builder setTokenServerEncodedUrl(String tokenServerEncodedUrl) { return (Builder) super.setTokenServerEncodedUrl( Preconditions.checkNotNull(tokenServerEncodedUrl)); } @Override public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) { Preconditions.checkArgument(clientAuthentication == null); return this; } @Override public Builder setRequestInitializer(HttpRequestInitializer requestInitializer) { return (Builder) super.setRequestInitializer(requestInitializer); } @Override public Builder addRefreshListener(CredentialRefreshListener refreshListener) { return (Builder) super.addRefreshListener(refreshListener); } @Override public Builder setRefreshListeners(Collection<CredentialRefreshListener> refreshListeners) { return (Builder) super.setRefreshListeners(refreshListeners); } } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * {@link com.google.api.client.util.Beta} <br/> * Support for <a href="https://developers.google.com/compute/">Google Compute Engine</a>. * * @since 1.15 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.compute;
Java
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis; import com.google.api.client.http.EmptyContent; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpMethods; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.UrlEncodedContent; import java.io.IOException; /** * Thread-safe HTTP request execute interceptor for Google API's that wraps HTTP requests inside of * a POST request and uses {@link #HEADER} header to specify the actual HTTP method. * * <p> * Use this for example for an HTTP transport that doesn't support PATCH like * {@code NetHttpTransport} or {@code UrlFetchTransport}. By default, only the methods not supported * by the transport will be overridden. When running behind a firewall that does not support certain * verbs like PATCH, use the {@link MethodOverride.Builder#setOverrideAllMethods(boolean)} * constructor instead to specify to override all methods. POST is never overridden. * </p> * * <p> * This class also allows GET requests with a long URL (> 2048 chars) to be instead sent using * method override as a POST request. * </p> * * <p> * Sample usage, taking advantage that this class implements {@link HttpRequestInitializer}: * </p> * * <pre> public static HttpRequestFactory createRequestFactory(HttpTransport transport) { return transport.createRequestFactory(new MethodOverride()); } * </pre> * * <p> * If you have a custom request initializer, take a look at the sample usage for * {@link HttpExecuteInterceptor}, which this class also implements. * </p> * * @since 1.4 * @author Yaniv Inbar */ public final class MethodOverride implements HttpExecuteInterceptor, HttpRequestInitializer { /** * Name of the method override header. * * @since 1.13 */ public static final String HEADER = "X-HTTP-Method-Override"; /** Maximum supported URL length. */ static final int MAX_URL_LENGTH = 2048; /** * Whether to allow all methods (except GET and POST) to be overridden regardless of whether the * transport supports them. */ private final boolean overrideAllMethods; /** Only overrides HTTP methods that the HTTP transport does not support. */ public MethodOverride() { this(false); } MethodOverride(boolean overrideAllMethods) { this.overrideAllMethods = overrideAllMethods; } public void initialize(HttpRequest request) { request.setInterceptor(this); } public void intercept(HttpRequest request) throws IOException { if (overrideThisMethod(request)) { String requestMethod = request.getRequestMethod(); request.setRequestMethod(HttpMethods.POST); request.getHeaders().set(HEADER, requestMethod); if (requestMethod.equals(HttpMethods.GET)) { // take the URI query part and put it into the HTTP body request.setContent(new UrlEncodedContent(request.getUrl())); } else if (request.getContent() == null) { // Google servers will fail to process a POST unless the Content-Length header is specified request.setContent(new EmptyContent()); } } } private boolean overrideThisMethod(HttpRequest request) throws IOException { String requestMethod = request.getRequestMethod(); if (requestMethod.equals(HttpMethods.POST)) { return false; } if (requestMethod.equals(HttpMethods.GET) ? request.getUrl().build().length() > MAX_URL_LENGTH : overrideAllMethods) { return true; } return !request.getTransport().supportsMethod(requestMethod); } /** * Builder for {@link MethodOverride}. * * @since 1.12 * @author Yaniv Inbar */ public static final class Builder { /** * Whether to allow all methods (except GET and POST) to be overridden regardless of whether the * transport supports them. */ private boolean overrideAllMethods; /** Builds the {@link MethodOverride}. */ public MethodOverride build() { return new MethodOverride(overrideAllMethods); } /** * Returns whether to allow all methods (except GET and POST) to be overridden regardless of * whether the transport supports them. */ public boolean getOverrideAllMethods() { return overrideAllMethods; } /** * Sets whether to allow all methods (except GET and POST) to be overridden regardless of * whether the transport supports them. * * <p> * Default is {@code false}. * </p> */ public Builder setOverrideAllMethods(boolean overrideAllMethods) { this.overrideAllMethods = overrideAllMethods; return this; } } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications; import com.google.api.client.util.Beta; import java.io.IOException; import java.io.Serializable; /** * {@link Beta} <br/> * Callback to receive unparsed notifications for watched resource. * * <p> * Must NOT be implemented in form of an anonymous class since this would break serialization. * </p> * * <p> * Should be thread-safe as several notifications might be processed at the same time. * </p> * * <b>Example usage:</b> * * <pre> static class MyNotificationCallback implements UnparsedNotificationCallback { private static final long serialVersionUID = 1L; {@literal @}Override public void onNotification(StoredChannel storedChannel, UnparsedNotification notification) { String contentType = notification.getContentType(); InputStream contentStream = notification.getContentStream(); switch (notification.getResourceState()) { case ResourceStates.SYNC: break; case ResourceStates.EXISTS: break; case ResourceStates.NOT_EXISTS: break; } } } * </pre> * * @author Yaniv Inbar * @author Matthias Linder (mlinder) * @since 1.16 */ @Beta public interface UnparsedNotificationCallback extends Serializable { /** * Handles a received unparsed notification. * * @param storedChannel stored notification channel * @param notification unparsed notification */ void onNotification(StoredChannel storedChannel, UnparsedNotification notification) throws IOException; }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications; import java.util.UUID; /** * Utilities for notifications and notification channels. * * @author Yaniv Inbar * @since 1.16 */ public final class NotificationUtils { /** Returns a new random UUID string to be used as a notification channel ID. */ public static String randomUuidString() { return UUID.randomUUID().toString(); } private NotificationUtils() { } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Notification metadata and parsed content sent to this client about a watched resource. * * <p> * Implementation is not thread-safe. * </p> * * @param <T> Java type of the notification content * * @author Yaniv Inbar * @author Matthias Linder (mlinder) * @since 1.16 */ @Beta public class TypedNotification<T> extends AbstractNotification { /** Parsed notification content or {@code null} for none. */ private T content; /** * @param messageNumber message number (a monotonically increasing value starting with 1) * @param resourceState {@link ResourceStates resource state} * @param resourceId opaque ID for the watched resource that is stable across API versions * @param resourceUri opaque ID (in the form of a canonicalized URI) for the watched resource that * is sensitive to the API version * @param channelId notification channel UUID provided by the client in the watch request */ public TypedNotification(long messageNumber, String resourceState, String resourceId, String resourceUri, String channelId) { super(messageNumber, resourceState, resourceId, resourceUri, channelId); } /** * @param sourceNotification source notification metadata to copy */ public TypedNotification(UnparsedNotification sourceNotification) { super(sourceNotification); } /** * Returns the parsed notification content or {@code null} for none. */ public final T getContent() { return content; } /** * Sets the parsed notification content or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public TypedNotification<T> setContent(T content) { this.content = content; return this; } @Override @SuppressWarnings("unchecked") public TypedNotification<T> setMessageNumber(long messageNumber) { return (TypedNotification<T>) super.setMessageNumber(messageNumber); } @Override @SuppressWarnings("unchecked") public TypedNotification<T> setResourceState(String resourceState) { return (TypedNotification<T>) super.setResourceState(resourceState); } @Override @SuppressWarnings("unchecked") public TypedNotification<T> setResourceId(String resourceId) { return (TypedNotification<T>) super.setResourceId(resourceId); } @Override @SuppressWarnings("unchecked") public TypedNotification<T> setResourceUri(String resourceUri) { return (TypedNotification<T>) super.setResourceUri(resourceUri); } @Override @SuppressWarnings("unchecked") public TypedNotification<T> setChannelId(String channelId) { return (TypedNotification<T>) super.setChannelId(channelId); } @Override @SuppressWarnings("unchecked") public TypedNotification<T> setChannelExpiration(String channelExpiration) { return (TypedNotification<T>) super.setChannelExpiration(channelExpiration); } @Override @SuppressWarnings("unchecked") public TypedNotification<T> setChannelToken(String channelToken) { return (TypedNotification<T>) super.setChannelToken(channelToken); } @Override @SuppressWarnings("unchecked") public TypedNotification<T> setChanged(String changed) { return (TypedNotification<T>) super.setChanged(changed); } @Override public String toString() { return super.toStringHelper().add("content", content).toString(); } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications; import com.google.api.client.util.Beta; import com.google.api.client.util.Objects; import com.google.api.client.util.Preconditions; import com.google.api.client.util.store.DataStore; import com.google.api.client.util.store.DataStoreFactory; import java.io.IOException; import java.io.Serializable; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * {@link Beta} <br/> * Notification channel information to be stored in a data store. * * <p> * Implementation is thread safe. * </p> * * @author Yaniv Inbar * @author Matthias Linder (mlinder) * @since 1.16 */ @Beta public final class StoredChannel implements Serializable { /** Default data store ID. */ public static final String DEFAULT_DATA_STORE_ID = StoredChannel.class.getSimpleName(); private static final long serialVersionUID = 1L; /** Lock on access to the store. */ private final Lock lock = new ReentrantLock(); /** Notification callback called when a notification is received for this subscription. */ private final UnparsedNotificationCallback notificationCallback; /** * Arbitrary string provided by the client associated with this subscription that is delivered to * the target address with each notification or {@code null} for none. */ private String clientToken; /** * Milliseconds in Unix time at which the subscription will expire or {@code null} for an infinite * TTL. */ private Long expiration; /** Subscription UUID. */ private final String id; /** * Opaque ID for the subscribed resource that is stable across API versions or {@code null} for * none. */ private String topicId; /** * Constructor with a random UUID using {@link NotificationUtils#randomUuidString()}. * * @param notificationCallback notification handler called when a notification is received for * this subscription */ public StoredChannel(UnparsedNotificationCallback notificationCallback) { this(notificationCallback, NotificationUtils.randomUuidString()); } /** * Constructor with a custom UUID. * * @param notificationCallback notification handler called when a notification is received for * this subscription * @param id subscription UUID */ public StoredChannel(UnparsedNotificationCallback notificationCallback, String id) { this.notificationCallback = Preconditions.checkNotNull(notificationCallback); this.id = Preconditions.checkNotNull(id); } /** * Stores this notification channel in the notification channel data store, which is derived from * {@link #getDefaultDataStore(DataStoreFactory)} on the given data store factory. * * <p> * It is important that this method be called before the watch HTTP request is made in case the * notification is received before the watch HTTP response is received. * </p> * * @param dataStoreFactory data store factory */ public StoredChannel store(DataStoreFactory dataStoreFactory) throws IOException { return store(getDefaultDataStore(dataStoreFactory)); } /** * Stores this notification channel in the given notification channel data store. * * <p> * It is important that this method be called before the watch HTTP request is made in case the * notification is received before the watch HTTP response is received. * </p> * * @param dataStore notification channel data store */ public StoredChannel store(DataStore<StoredChannel> dataStore) throws IOException { lock.lock(); try { dataStore.set(getId(), this); return this; } finally { lock.unlock(); } } /** * Returns the notification callback called when a notification is received for this subscription. */ public UnparsedNotificationCallback getNotificationCallback() { lock.lock(); try { return notificationCallback; } finally { lock.unlock(); } } /** * Returns the arbitrary string provided by the client associated with this subscription that is * delivered to the target address with each notification or {@code null} for none. */ public String getClientToken() { lock.lock(); try { return clientToken; } finally { lock.unlock(); } } /** * Sets the the arbitrary string provided by the client associated with this subscription that is * delivered to the target address with each notification or {@code null} for none. */ public StoredChannel setClientToken(String clientToken) { lock.lock(); try { this.clientToken = clientToken; } finally { lock.unlock(); } return this; } /** * Returns the milliseconds in Unix time at which the subscription will expire or {@code null} for * an infinite TTL. */ public Long getExpiration() { lock.lock(); try { return expiration; } finally { lock.unlock(); } } /** * Sets the milliseconds in Unix time at which the subscription will expire or {@code null} for an * infinite TTL. */ public StoredChannel setExpiration(Long expiration) { lock.lock(); try { this.expiration = expiration; } finally { lock.unlock(); } return this; } /** Returns the subscription UUID. */ public String getId() { lock.lock(); try { return id; } finally { lock.unlock(); } } /** * Returns the opaque ID for the subscribed resource that is stable across API versions or * {@code null} for none. */ public String getTopicId() { lock.lock(); try { return topicId; } finally { lock.unlock(); } } /** * Sets the opaque ID for the subscribed resource that is stable across API versions or * {@code null} for none. */ public StoredChannel setTopicId(String topicId) { lock.lock(); try { this.topicId = topicId; } finally { lock.unlock(); } return this; } @Override public String toString() { return Objects.toStringHelper(StoredChannel.class) .add("notificationCallback", getNotificationCallback()).add("clientToken", getClientToken()) .add("expiration", getExpiration()).add("id", getId()).add("topicId", getTopicId()) .toString(); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof StoredChannel)) { return false; } StoredChannel o = (StoredChannel) other; return getId().equals(o.getId()); } @Override public int hashCode() { return getId().hashCode(); } /** * Returns the stored channel data store using the ID {@link #DEFAULT_DATA_STORE_ID}. * * @param dataStoreFactory data store factory * @return stored channel data store */ public static DataStore<StoredChannel> getDefaultDataStore(DataStoreFactory dataStoreFactory) throws IOException { return dataStoreFactory.getDataStore(DEFAULT_DATA_STORE_ID); } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * {@link com.google.api.client.util.Beta} <br/> * JSON-based notification handling for subscriptions. * * @author Yaniv Inbar * @since 1.16 */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.notifications.json;
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications.json; import com.google.api.client.googleapis.notifications.TypedNotificationCallback; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonObjectParser; import com.google.api.client.util.Beta; import java.io.IOException; /** * {@link Beta} <br/> * A {@link TypedNotificationCallback} which uses an JSON content encoding. * * <p> * Must NOT be implemented in form of an anonymous class as this will break serialization. * </p> * * <p> * Implementation should be thread-safe. * </p> * * <b>Example usage:</b> * * <pre> static class MyNotificationCallback extends JsonNotificationCallback{@literal <}ListResponse{@literal >} { private static final long serialVersionUID = 1L; {@literal @}Override protected void onNotification( StoredChannel channel, TypedNotification{@literal <}ListResponse{@literal >} notification) { ListResponse content = notification.getContent(); switch (notification.getResourceState()) { case ResourceStates.SYNC: break; case ResourceStates.EXISTS: break; case ResourceStates.NOT_EXISTS: break; } } {@literal @}Override protected JsonFactory getJsonFactory() throws IOException { return new JacksonFactory(); } {@literal @}Override protected Class{@literal <}ListResponse{@literal >} getDataClass() throws IOException { return ListResponse.class; } } * </pre> * * @param <T> Type of the data contained within a notification * @author Yaniv Inbar * @since 1.16 */ @Beta public abstract class JsonNotificationCallback<T> extends TypedNotificationCallback<T> { private static final long serialVersionUID = 1L; @Override protected final JsonObjectParser getObjectParser() throws IOException { return new JsonObjectParser(getJsonFactory()); } /** Returns the JSON factory to use to parse the notification content. */ protected abstract JsonFactory getJsonFactory() throws IOException; }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * {@link com.google.api.client.util.Beta} <br/> * Support for notification channels to listen for changes to watched Google API resources. * * @author Yaniv Inbar * @author Matthias Linder (mlinder) * @since 1.16 */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.notifications;
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications; import com.google.api.client.http.HttpMediaType; import com.google.api.client.util.Beta; import com.google.api.client.util.ObjectParser; import com.google.api.client.util.Preconditions; import java.io.IOException; import java.nio.charset.Charset; /** * {@link Beta} <br/> * Callback to receive notifications for watched resource in which the . Callback which is used to * receive typed {@link AbstractNotification}s after subscribing to a topic. * * <p> * Must NOT be implemented in form of an anonymous class as this will break serialization. * </p> * * <p> * Implementation should be thread-safe. * </p> * * <b>Example usage:</b> * * <pre> static class MyNotificationCallback extends JsonNotificationCallback{@literal <}ListResponse{@literal >} { private static final long serialVersionUID = 1L; {@literal @}Override protected void onNotification( StoredChannel subscription, Notification notification, ListResponse content) { switch (notification.getResourceState()) { case ResourceStates.SYNC: break; case ResourceStates.EXISTS: break; case ResourceStates.NOT_EXISTS: break; } } {@literal @}Override protected ObjectParser getObjectParser(Notification notification) throws IOException { return new JsonObjectParser(new JacksonFactory()); } {@literal @}Override protected Class{@literal <}ListResponse{@literal >} getDataClass() throws IOException { return ListResponse.class; } } * </pre> * * @param <T> Java type of the notification content * @author Yaniv Inbar * @author Matthias Linder (mlinder) * @since 1.16 */ @Beta public abstract class TypedNotificationCallback<T> implements UnparsedNotificationCallback { private static final long serialVersionUID = 1L; /** * Handles a received typed notification. * * @param storedChannel stored notification channel * @param notification typed notification */ protected abstract void onNotification( StoredChannel storedChannel, TypedNotification<T> notification) throws IOException; /** Returns an {@link ObjectParser} which can be used to parse this notification. */ protected abstract ObjectParser getObjectParser() throws IOException; /** * Returns the data class to parse the notification content into or {@code Void.class} if no * notification content is expected. */ protected abstract Class<T> getDataClass() throws IOException; public final void onNotification(StoredChannel storedChannel, UnparsedNotification notification) throws IOException { TypedNotification<T> typedNotification = new TypedNotification<T>(notification); // TODO(yanivi): how to properly detect if there is no content? String contentType = notification.getContentType(); if (contentType != null) { Charset charset = new HttpMediaType(contentType).getCharsetParameter(); Class<T> dataClass = Preconditions.checkNotNull(getDataClass()); typedNotification.setContent( getObjectParser().parseAndClose(notification.getContentStream(), charset, dataClass)); } onNotification(storedChannel, typedNotification); } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications; import com.google.api.client.util.Beta; import java.io.InputStream; /** * {@link Beta} <br/> * Notification metadata and unparsed content stream sent to this client about a watched resource. * * <p> * Implementation is not thread-safe. * </p> * * @author Yaniv Inbar * @author Matthias Linder (mlinder) * @since 1.16 */ @Beta public class UnparsedNotification extends AbstractNotification { /** Notification content media type for the content stream or {@code null} for none or unknown. */ private String contentType; /** Notification content input stream or {@code null} for none. */ private InputStream contentStream; /** * @param messageNumber message number (a monotonically increasing value starting with 1) * @param resourceState {@link ResourceStates resource state} * @param resourceId opaque ID for the watched resource that is stable across API versions * @param resourceUri opaque ID (in the form of a canonicalized URI) for the watched resource that * is sensitive to the API version * @param channelId notification channel UUID provided by the client in the watch request */ public UnparsedNotification(long messageNumber, String resourceState, String resourceId, String resourceUri, String channelId) { super(messageNumber, resourceState, resourceId, resourceUri, channelId); } /** * Returns the notification content media type for the content stream or {@code null} for none or * unknown. */ public final String getContentType() { return contentType; } /** * Sets the notification content media type for the content stream or {@code null} for none or * unknown. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public UnparsedNotification setContentType(String contentType) { this.contentType = contentType; return this; } /** * Returns the notification content input stream or {@code null} for none. */ public final InputStream getContentStream() { return contentStream; } /** * Sets the notification content content input stream or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public UnparsedNotification setContentStream(InputStream contentStream) { this.contentStream = contentStream; return this; } @Override public UnparsedNotification setMessageNumber(long messageNumber) { return (UnparsedNotification) super.setMessageNumber(messageNumber); } @Override public UnparsedNotification setResourceState(String resourceState) { return (UnparsedNotification) super.setResourceState(resourceState); } @Override public UnparsedNotification setResourceId(String resourceId) { return (UnparsedNotification) super.setResourceId(resourceId); } @Override public UnparsedNotification setResourceUri(String resourceUri) { return (UnparsedNotification) super.setResourceUri(resourceUri); } @Override public UnparsedNotification setChannelId(String channelId) { return (UnparsedNotification) super.setChannelId(channelId); } @Override public UnparsedNotification setChannelExpiration(String channelExpiration) { return (UnparsedNotification) super.setChannelExpiration(channelExpiration); } @Override public UnparsedNotification setChannelToken(String channelToken) { return (UnparsedNotification) super.setChannelToken(channelToken); } @Override public UnparsedNotification setChanged(String changed) { return (UnparsedNotification) super.setChanged(changed); } @Override public String toString() { return super.toStringHelper().add("contentType", contentType).toString(); } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications; import com.google.api.client.util.Beta; import com.google.api.client.util.Objects; import com.google.api.client.util.Preconditions; /** * {@link Beta} <br/> * Notification metadata sent to this client about a watched resource. * * <p> * Implementation is not thread-safe. * </p> * * @author Yaniv Inbar * @author Matthias Linder (mlinder) * @since 1.16 */ @Beta public abstract class AbstractNotification { /** Message number (a monotonically increasing value starting with 1). */ private long messageNumber; /** {@link ResourceStates Resource state}. */ private String resourceState; /** Opaque ID for the watched resource that is stable across API versions. */ private String resourceId; /** * Opaque ID (in the form of a canonicalized URI) for the watched resource that is sensitive to * the API version. */ private String resourceUri; /** Notification channel UUID provided by the client in the watch request. */ private String channelId; /** Notification channel expiration time or {@code null} for none. */ private String channelExpiration; /** * Notification channel token (an opaque string) provided by the client in the watch request or * {@code null} for none. */ private String channelToken; /** Type of change performed on the resource or {@code null} for none. */ private String changed; /** * @param messageNumber message number (a monotonically increasing value starting with 1) * @param resourceState {@link ResourceStates resource state} * @param resourceId opaque ID for the watched resource that is stable across API versions * @param resourceUri opaque ID (in the form of a canonicalized URI) for the watched resource that * is sensitive to the API version * @param channelId notification channel UUID provided by the client in the watch request */ protected AbstractNotification(long messageNumber, String resourceState, String resourceId, String resourceUri, String channelId) { setMessageNumber(messageNumber); setResourceState(resourceState); setResourceId(resourceId); setResourceUri(resourceUri); setChannelId(channelId); } /** Copy constructor based on a source notification object. */ protected AbstractNotification(AbstractNotification source) { this(source.getMessageNumber(), source.getResourceState(), source.getResourceId(), source .getResourceUri(), source.getChannelId()); setChannelExpiration(source.getChannelExpiration()); setChannelToken(source.getChannelToken()); setChanged(source.getChanged()); } @Override public String toString() { return toStringHelper().toString(); } /** Returns the helper for {@link #toString()}. */ protected Objects.ToStringHelper toStringHelper() { return Objects.toStringHelper(this).add("messageNumber", messageNumber) .add("resourceState", resourceState).add("resourceId", resourceId) .add("resourceUri", resourceUri).add("channelId", channelId) .add("channelExpiration", channelExpiration).add("channelToken", channelToken) .add("changed", changed); } /** Returns the message number (a monotonically increasing value starting with 1). */ public final long getMessageNumber() { return messageNumber; } /** * Sets the message number (a monotonically increasing value starting with 1). * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractNotification setMessageNumber(long messageNumber) { Preconditions.checkArgument(messageNumber >= 1); this.messageNumber = messageNumber; return this; } /** Returns the {@link ResourceStates resource state}. */ public final String getResourceState() { return resourceState; } /** * Sets the {@link ResourceStates resource state}. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractNotification setResourceState(String resourceState) { this.resourceState = Preconditions.checkNotNull(resourceState); return this; } /** Returns the opaque ID for the watched resource that is stable across API versions. */ public final String getResourceId() { return resourceId; } /** * Sets the opaque ID for the watched resource that is stable across API versions. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractNotification setResourceId(String resourceId) { this.resourceId = Preconditions.checkNotNull(resourceId); return this; } /** * Returns the opaque ID (in the form of a canonicalized URI) for the watched resource that is * sensitive to the API version. */ public final String getResourceUri() { return resourceUri; } /** * Sets the opaque ID (in the form of a canonicalized URI) for the watched resource that is * sensitive to the API version. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractNotification setResourceUri(String resourceUri) { this.resourceUri = Preconditions.checkNotNull(resourceUri); return this; } /** Returns the notification channel UUID provided by the client in the watch request. */ public final String getChannelId() { return channelId; } /** * Sets the notification channel UUID provided by the client in the watch request. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractNotification setChannelId(String channelId) { this.channelId = Preconditions.checkNotNull(channelId); return this; } /** Returns the notification channel expiration time or {@code null} for none. */ public final String getChannelExpiration() { return channelExpiration; } /** * Sets the notification channel expiration time or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractNotification setChannelExpiration(String channelExpiration) { this.channelExpiration = channelExpiration; return this; } /** * Returns the notification channel token (an opaque string) provided by the client in the watch * request or {@code null} for none. */ public final String getChannelToken() { return channelToken; } /** * Sets the notification channel token (an opaque string) provided by the client in the watch * request or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractNotification setChannelToken(String channelToken) { this.channelToken = channelToken; return this; } /** * Returns the type of change performed on the resource or {@code null} for none. */ public final String getChanged() { return changed; } /** * Sets the type of change performed on the resource or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public AbstractNotification setChanged(String changed) { this.changed = changed; return this; } }
Java
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.notifications; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Standard resource states used by notifications. * * @author Yaniv Inbar * @since 1.16 */ @Beta public final class ResourceStates { /** Notification that the subscription is alive (comes with no payload). */ public static final String SYNC = "SYNC"; /** Resource exists, for example on a create or update. */ public static final String EXISTS = "EXISTS"; /** Resource does not exist, for example on a delete. */ public static final String NOT_EXISTS = "NOT_EXISTS"; private ResourceStates() { } }
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.subscriptions; import com.google.api.client.util.Beta; import java.util.Collection; import java.util.Collections; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * {@link Beta} <br/> * {@link SubscriptionStore} which stores all subscription information in memory. * * <p> * Thread-safe implementation. * </p> * * <b>Example usage:</b> * <pre> service.setSubscriptionStore(new MemorySubscriptionStore()); * </pre> * * @author Matthias Linder (mlinder) * @since 1.14 */ @Beta public class MemorySubscriptionStore implements SubscriptionStore { /** Lock on the token response information. */ private final Lock lock = new ReentrantLock(); /** Map of all stored subscriptions. */ private final SortedMap<String, StoredSubscription> storedSubscriptions = new TreeMap<String, StoredSubscription>(); public void storeSubscription(StoredSubscription subscription) { lock.lock(); try { storedSubscriptions.put(subscription.getId(), subscription); } finally { lock.unlock(); } } public void removeSubscription(StoredSubscription subscription) { lock.lock(); try { storedSubscriptions.remove(subscription.getId()); } finally { lock.unlock(); } } public Collection<StoredSubscription> listSubscriptions() { lock.lock(); try { return Collections.unmodifiableCollection(storedSubscriptions.values()); } finally { lock.unlock(); } } public StoredSubscription getSubscription(String subscriptionId) { lock.lock(); try { return storedSubscriptions.get(subscriptionId); } finally { lock.unlock(); } } }
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.subscriptions; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Typed notification sent to this client about a subscribed resource. * * <p> * Thread-safe implementation. * </p> * * <b>Example usage:</b> * * <pre> void handleNotification( Subscription subscription, TypedNotification&lt;ItemList&gt; notification) { for (Item item : notification.getContent().getItems()) { System.out.println(item.getId()); } } * </pre> * * @param <T> Data content from the underlying response stored within this notification * * @author Matthias Linder (mlinder) * @since 1.14 */ @Beta public final class TypedNotification<T> extends Notification { /** Typed content or {@code null} for none. */ private final T content; /** Returns the typed content or {@code null} for none. */ public final T getContent() { return content; } /** * @param notification notification whose information is copied * @param content typed content or {@code null} for none */ public TypedNotification(Notification notification, T content) { super(notification); this.content = content; } /** * @param subscriptionId subscription UUID * @param topicId opaque ID for the subscribed resource that is stable across API versions * @param topicURI opaque ID (in the form of a canonicalized URI) for the subscribed resource that * is sensitive to the API version * @param clientToken client token (an opaque string) or {@code null} for none * @param messageNumber message number (a monotonically increasing value starting with 1) * @param eventType event type (see {@link EventTypes}) * @param changeType type of change performed on the resource or {@code null} for none * @param content typed content or {@code null} for none */ public TypedNotification(String subscriptionId, String topicId, String topicURI, String clientToken, long messageNumber, String eventType, String changeType, T content) { super(subscriptionId, topicId, topicURI, clientToken, messageNumber, eventType, changeType); this.content = content; } }
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * {@link com.google.api.client.util.Beta} <br/> * JSON-based notification handling for subscriptions. * * @since 1.14 * @author Matthias Linder (mlinder) */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.subscriptions.json;
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.subscriptions.json; import com.google.api.client.googleapis.subscriptions.TypedNotificationCallback; import com.google.api.client.googleapis.subscriptions.UnparsedNotification; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonObjectParser; import com.google.api.client.util.Beta; import com.google.api.client.util.ObjectParser; import java.io.IOException; /** * {@link Beta} <br/> * A {@link TypedNotificationCallback} which uses an JSON content encoding. * * <p> * Must not be implemented in form of an anonymous class as this will break serialization. * </p> * * <p> * Implementation should be thread-safe. * </p> * * <p> * State will only be persisted once when a subscription is created. All state changes occurring * during the {@code .handleNotification(..)} call will be lost. * </p> * * <b>Example usage:</b> * <pre> class MyJsonNotificationCallback extends JsonNotificationCallback&lt;ItemList&gt; { void handleNotification( Subscription subscription, TypedNotification&lt;ItemList&gt; notification) { for (Item item in notification.getContent().getItems()) { System.out.println(item.getId()); } } } JsonFactory createJsonFactory() { return new JacksonFactory(); } ... service.items.list("someID").subscribe(new MyJsonNotificationCallback()).execute() * </pre> * * @param <T> Type of the data contained within a notification * @author Matthias Linder (mlinder) * @since 1.14 */ @SuppressWarnings("serial") @Beta public abstract class JsonNotificationCallback<T> extends TypedNotificationCallback<T> { /** JSON factory used to deserialize notifications. {@code null} until first used. */ private transient JsonFactory jsonFactory; /** * Returns the JSON-factory used by this handler. */ public final JsonFactory getJsonFactory() throws IOException { if (jsonFactory == null) { jsonFactory = createJsonFactory(); } return jsonFactory; } // TODO(mlinder): Don't have the user supply the JsonFactory, but serialize it instead. /** * Creates a new JSON factory which is used to deserialize notifications. */ protected abstract JsonFactory createJsonFactory() throws IOException; @Override protected final ObjectParser getParser(UnparsedNotification notification) throws IOException { return new JsonObjectParser(getJsonFactory()); } @Override public JsonNotificationCallback<T> setDataType(Class<T> dataClass) { return (JsonNotificationCallback<T>) super.setDataType(dataClass); } }
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * {@link com.google.api.client.util.Beta} <br/> * Support for creating subscriptions and receiving notifications for Google APIs. * * @since 1.14 * @author Matthias Linder (mlinder) */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.subscriptions;
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.subscriptions; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Standard event-types used by notifications. * * <b>Example usage:</b> * * <pre> void handleNotification(Subscription subscription, UnparsedNotification notification) { if (notification.getEventType().equals(EventTypes.UPDATED)) { // add items in the notification to the local client state ... } } * </pre> * * @author Matthias Linder (mlinder) * @since 1.14 */ @Beta public final class EventTypes { /** Notification that the subscription is alive (comes with no payload). */ public static final String SYNC = "sync"; /** Resource was modified. */ public static final String UPDATED = "updated"; /** Resource was deleted. */ public static final String DELETED = "deleted"; /** Private constructor to prevent instantiation. */ private EventTypes() { } }
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.subscriptions; import com.google.api.client.util.Beta; import com.google.api.client.util.Preconditions; /** * {@link Beta} <br/> * Notification sent to this client about a subscribed resource. * * <p> * Implementation is thread-safe. * </p> * * @author Matthias Linder (mlinder) * @since 1.14 */ @Beta public abstract class Notification { /** Subscription UUID. */ private final String subscriptionId; /** Opaque ID for the subscribed resource that is stable across API versions. */ private final String topicId; /** * Opaque ID (in the form of a canonicalized URI) for the subscribed resource that is sensitive to * the API version. */ private final String topicURI; /** Client token (an opaque string) or {@code null} for none. */ private final String clientToken; /** Message number (a monotonically increasing value starting with 1). */ private final long messageNumber; /** Event type (see {@link EventTypes}). */ private final String eventType; /** Type of change performed on the resource or {@code null} for none. */ private final String changeType; /** * @param subscriptionId subscription UUID * @param topicId opaque ID for the subscribed resource that is stable across API versions * @param topicURI opaque ID (in the form of a canonicalized URI) for the subscribed resource that * is sensitive to the API version * @param clientToken client token (an opaque string) or {@code null} for none * @param messageNumber message number (a monotonically increasing value starting with 1) * @param eventType event type (see {@link EventTypes}) * @param changeType type of change performed on the resource or {@code null} for none */ protected Notification(String subscriptionId, String topicId, String topicURI, String clientToken, long messageNumber, String eventType, String changeType) { this.subscriptionId = Preconditions.checkNotNull(subscriptionId); this.topicId = Preconditions.checkNotNull(topicId); this.topicURI = Preconditions.checkNotNull(topicURI); this.eventType = Preconditions.checkNotNull(eventType); this.clientToken = clientToken; Preconditions.checkArgument(messageNumber >= 1); this.messageNumber = messageNumber; this.changeType = changeType; } /** * Creates a new notification by copying all information specified in the source notification. * * @param source notification whose information is copied */ protected Notification(Notification source) { this(source.getSubscriptionId(), source.getTopicId(), source.getTopicURI(), source .getClientToken(), source.getMessageNumber(), source.getEventType(), source .getChangeType()); } /** Returns the subscription UUID. */ public final String getSubscriptionId() { return subscriptionId; } /** Returns the opaque ID for the subscribed resource that is stable across API versions. */ public final String getTopicId() { return topicId; } /** Returns the client token (an opaque string) or {@code null} for none. */ public final String getClientToken() { return clientToken; } /** Returns the event type (see {@link EventTypes}). */ public final String getEventType() { return eventType; } /** * Returns the opaque ID (in the form of a canonicalized URI) for the subscribed resource that is * sensitive to the API version. */ public final String getTopicURI() { return topicURI; } /** Returns the message number (a monotonically increasing value starting with 1). */ public final long getMessageNumber() { return messageNumber; } /** Returns the type of change performed on the resource or {@code null} for none. */ public final String getChangeType() { return changeType; } }
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.subscriptions; import com.google.api.client.util.Beta; import java.io.IOException; import java.util.Collection; /** * {@link Beta} <br/> * Stores and manages registered subscriptions and their handlers. * * <p> * Implementation should be thread-safe. * </p> * * @author Matthias Linder (mlinder) * @since 1.14 */ @Beta public interface SubscriptionStore { /** * Returns all known/registered subscriptions. */ Collection<StoredSubscription> listSubscriptions() throws IOException; /** * Retrieves a known subscription or {@code null} if not found. * * @param subscriptionId ID of the subscription to retrieve */ StoredSubscription getSubscription(String subscriptionId) throws IOException; /** * Stores the subscription in the applications data store, replacing any existing subscription * with the same id. * * @param subscription New or existing {@link StoredSubscription} to store/update */ void storeSubscription(StoredSubscription subscription) throws IOException; /** * Removes a registered subscription from the store. * * @param subscription {@link StoredSubscription} to remove or {@code null} to ignore */ void removeSubscription(StoredSubscription subscription) throws IOException; }
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.subscriptions; import com.google.api.client.http.HttpMediaType; import com.google.api.client.util.Beta; import com.google.api.client.util.ObjectParser; import com.google.api.client.util.Preconditions; import java.io.IOException; import java.nio.charset.Charset; /** * {@link Beta} <br/> * Callback which is used to receive typed {@link Notification}s after subscribing to a topic. * * <p> * Must not be implemented in form of an anonymous class as this will break serialization. * </p> * * <p> * Implementation should be thread-safe. * </p> * * <p> * State will only be persisted once when a subscription is created. All state changes occurring * during the {@code .handleNotification(..)} call will be lost. * </p> * * <b>Example usage:</b> * * <pre> class MyTypedNotificationCallback extends TypedNotificationCallback&lt;ItemList&gt; { void handleNotification( Subscription subscription, TypedNotification&lt;ItemList&gt; notification) { for (Item item in notification.getContent().getItems()) { System.out.println(item.getId()); } } } ObjectParser getParser(UnparsedNotification notification) { return new JacksonFactory().createJsonObjectParser(); } ... service.items.list("someID").subscribe(new MyTypedNotificationCallback()).execute() * </pre> * * @param <T> Type of the data contained within a notification * @author Matthias Linder (mlinder) * @since 1.14 */ @SuppressWarnings("serial") @Beta public abstract class TypedNotificationCallback<T> implements NotificationCallback { /** * Data type which this handler can parse or {@code Void.class} if no data type is expected. */ private Class<T> dataClass; /** * Returns the data type which this handler can parse or {@code Void.class} if no data type is * expected. */ public final Class<T> getDataClass() { return dataClass; } /** * Sets the data type which this handler can parse or {@code Void.class} if no data type is * expected. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public TypedNotificationCallback<T> setDataType(Class<T> dataClass) { this.dataClass = Preconditions.checkNotNull(dataClass); return this; } /** * Handles a received push notification. * * @param subscription Subscription to which this notification belongs * @param notification Typed notification which was delivered to this application */ protected abstract void handleNotification( StoredSubscription subscription, TypedNotification<T> notification) throws IOException; /** * Returns an {@link ObjectParser} which can be used to parse this notification. * * @param notification Notification which should be parsable by the returned parser */ protected abstract ObjectParser getParser(UnparsedNotification notification) throws IOException; /** Parses the specified content and closes the InputStream of the notification. */ private Object parseContent(ObjectParser parser, UnparsedNotification notification) throws IOException { // Return null if no content is expected if (notification.getContentType() == null) { return null; } // Parse the response otherwise Charset charset = notification.getContentType() == null ? null : new HttpMediaType( notification.getContentType()).getCharsetParameter(); return parser.parseAndClose(notification.getContent(), charset, dataClass); } public void handleNotification(StoredSubscription subscription, UnparsedNotification notification) throws IOException { ObjectParser parser = getParser(notification); @SuppressWarnings("unchecked") T content = (T) parseContent(parser, notification); handleNotification(subscription, new TypedNotification<T>(notification, content)); } }
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.subscriptions; import com.google.api.client.util.Beta; import com.google.api.client.util.Preconditions; import com.google.api.client.util.Strings; import java.io.IOException; import java.io.InputStream; /** * {@link Beta} <br/> * A notification whose content has not been parsed yet. * * <p> * Thread-safe implementation. * </p> * * <b>Example usage:</b> * * <pre> void handleNotification(Subscription subscription, UnparsedNotification notification) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(notification.getContent())); System.out.println(reader.readLine()); reader.close(); } * </pre> * * @author Matthias Linder (mlinder) * @since 1.14 */ @Beta public final class UnparsedNotification extends Notification { /** The input stream containing the content. */ private final InputStream content; /** The content-type of the stream or {@code null} if not specified. */ private final String contentType; /** * Creates a {@link Notification} whose content has not yet been read and parsed. * * @param subscriptionId subscription UUID * @param topicId opaque ID for the subscribed resource that is stable across API versions * @param topicURI opaque ID (in the form of a canonicalized URI) for the subscribed resource that * is sensitive to the API version * @param clientToken client token (an opaque string) or {@code null} for none * @param messageNumber message number (a monotonically increasing value starting with 1) * @param eventType event type (see {@link EventTypes}) * @param changeType type of change performed on the resource or {@code null} for none * @param unparsedStream Unparsed content in form of a {@link InputStream}. Caller has the * responsibility of closing the stream. */ public UnparsedNotification(String subscriptionId, String topicId, String topicURI, String clientToken, long messageNumber, String eventType, String changeType, String contentType, InputStream unparsedStream) { super(subscriptionId, topicId, topicURI, clientToken, messageNumber, eventType, changeType); this.contentType = contentType; this.content = Preconditions.checkNotNull(unparsedStream); } /** * Returns the Content-Type of the Content of this notification. */ public final String getContentType() { return contentType; } /** * Returns the content stream of this notification. */ public final InputStream getContent() { return content; } /** * Handles a newly received notification, and delegates it to the registered handler. * * @param subscriptionStore subscription store * @return {@code true} if the notification was delivered successfully, or {@code false} if this * notification could not be delivered and the subscription should be cancelled. * @throws IllegalArgumentException if there is a client-token mismatch */ public boolean deliverNotification(SubscriptionStore subscriptionStore) throws IOException { // Find out the handler to whom this notification should go. StoredSubscription subscription = subscriptionStore.getSubscription(Preconditions.checkNotNull(getSubscriptionId())); if (subscription == null) { return false; } // Validate the notification. String expectedToken = subscription.getClientToken(); Preconditions.checkArgument( Strings.isNullOrEmpty(expectedToken) || expectedToken.equals(getClientToken()), "Token mismatch for subscription with id=%s -- got=%s expected=%s", getSubscriptionId(), getClientToken(), expectedToken); // Invoke the handler associated with this subscription. NotificationCallback h = subscription.getNotificationCallback(); h.handleNotification(subscription, this); return true; } }
Java
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.subscriptions; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Headers for notifications. * * @author Kyle Marvin (kmarvin) * @since 1.14 */ @Beta public final class NotificationHeaders { /** * Name of header for the client token (an opaque string) provided by the client in the subscribe * request and returned in the subscribe response. */ public static final String CLIENT_TOKEN = "X-Goog-Client-Token"; /** * Name of header for the subscription UUID provided by the client in the subscribe request and * returned in the subscribe response. */ public static final String SUBSCRIPTION_ID = "X-Goog-Subscription-ID"; /** * Name of header for the opaque ID for the subscribed resource that is stable across API versions * returned in the subscribe response. */ public static final String TOPIC_ID = "X-Goog-Topic-ID"; /** * Name of header for the opaque ID (in the form of a canonicalized URI) for the subscribed * resource that is sensitive to the API version returned in the subscribe response. */ public static final String TOPIC_URI = "X-Goog-Topic-URI"; /** Name of header for the event type (see {@link EventTypes}). */ public static final String EVENT_TYPE_HEADER = "X-Goog-Event-Type"; /** * Name of header for the type of change performed on the resource. */ public static final String CHANGED_HEADER = "X-Goog-Changed"; /** * Name of header for the message number (a monotonically increasing value starting with 1). */ public static final String MESSAGE_NUMBER_HEADER = "X-Goog-Message-Number"; private NotificationHeaders() { } }
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.subscriptions; import com.google.api.client.util.Beta; import java.io.IOException; import java.io.Serializable; /** * {@link Beta} <br/> * Callback which is used to receive {@link UnparsedNotification}s after subscribing to a topic. * * <p> * Must not be implemented in form of an anonymous class as this will break serialization. * </p> * * <p> * Should be thread-safe as several notifications might be processed at the same time. * </p> * * <p> * State will only be persisted once when a subscription is created. All state changes occurring * during the {@code .handleNotification(..)} call will be lost. * </p> * * <b>Example usage:</b> * * <pre> class MyNotificationCallback extends NotificationCallback { void handleNotification( Subscription subscription, UnparsedNotification notification) { if (notification.getEventType().equals(EventTypes.UPDATED)) { // add items in the notification to the local client state ... } } } ... myRequest.subscribe(new MyNotificationCallback()).execute(); * </pre> * * @author Matthias Linder (mlinder) * @since 1.14 */ @Beta public interface NotificationCallback extends Serializable { /** * Handles a received push notification. * * @param subscription Subscription to which this notification belongs * @param notification Notification which was delivered to this application */ void handleNotification(StoredSubscription subscription, UnparsedNotification notification) throws IOException; }
Java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.subscriptions; import com.google.api.client.json.GenericJson; import com.google.api.client.util.Beta; import com.google.api.client.util.Objects; import com.google.api.client.util.Preconditions; import java.io.Serializable; import java.util.UUID; /** * {@link Beta} <br/> * Client subscription information to be stored in a {@link SubscriptionStore}. * * <p> * Implementation is thread safe. * </p> * * @author Matthias Linder (mlinder) * @since 1.14 */ @Beta public final class StoredSubscription implements Serializable { private static final long serialVersionUID = 1L; /** Notification callback called when a notification is received for this subscription. */ private final NotificationCallback notificationCallback; /** * Arbitrary string provided by the client associated with this subscription that is delivered to * the target address with each notification or {@code null} for none. */ private String clientToken; /** * HTTP date indicating the time at which the subscription will expire or {@code null} for an * infinite TTL. */ private String expiration; /** Subscription UUID. */ private final String id; /** * Opaque ID for the subscribed resource that is stable across API versions or {@code null} for * none. */ private String topicId; /** * Constructor with a random UUID using {@link #randomId()}. * * @param notificationCallback notification handler called when a notification is received for * this subscription */ public StoredSubscription(NotificationCallback notificationCallback) { this(notificationCallback, randomId()); } /** * Constructor with a custom UUID. * * @param notificationCallback notification handler called when a notification is received for * this subscription * @param id subscription UUID */ public StoredSubscription(NotificationCallback notificationCallback, String id) { this.notificationCallback = Preconditions.checkNotNull(notificationCallback); this.id = Preconditions.checkNotNull(id); } /** * Constructor based on a JSON-formatted subscription response information. * * @param notificationCallback notification handler called when a notification is received for * this subscription * @param subscriptionJson JSON-formatted subscription response information, where the: * <ul> * <li>{@code "id"} has a JSON string value for the subscription ID</li> * <li>{@code "clientToken"} has a JSON string value for the client token (see * {@link #setClientToken(String)})</li> * <li>{@code "expiration"} has a JSON string value for the client token (see * {@link #setExpiration(String)})</li> * <li>{@code "topicId"} has a JSON string value for the client token (see * {@link #setTopicId(String)})</li> * </ul> */ public StoredSubscription( NotificationCallback notificationCallback, GenericJson subscriptionJson) { this(notificationCallback, (String) subscriptionJson.get("id")); setClientToken((String) subscriptionJson.get("clientToken")); setExpiration((String) subscriptionJson.get("expiration")); setTopicId((String) subscriptionJson.get("topicId")); } /** * Returns the notification callback called when a notification is received for this subscription. */ public synchronized NotificationCallback getNotificationCallback() { return notificationCallback; } /** * Returns the arbitrary string provided by the client associated with this subscription that is * delivered to the target address with each notification or {@code null} for none. */ public synchronized String getClientToken() { return clientToken; } /** * Sets the the arbitrary string provided by the client associated with this subscription that is * delivered to the target address with each notification or {@code null} for none. */ public synchronized StoredSubscription setClientToken(String clientToken) { this.clientToken = clientToken; return this; } /** * Returns the HTTP date indicating the time at which the subscription will expire or {@code null} * for an infinite TTL. */ public synchronized String getExpiration() { return expiration; } /** * Sets the HTTP date indicating the time at which the subscription will expire or {@code null} * for an infinite TTL. */ public synchronized StoredSubscription setExpiration(String expiration) { this.expiration = expiration; return this; } /** Returns the subscription UUID. */ public synchronized String getId() { return id; } /** * Returns the opaque ID for the subscribed resource that is stable across API versions or * {@code null} for none. */ public synchronized String getTopicId() { return topicId; } /** * Sets the opaque ID for the subscribed resource that is stable across API versions or * {@code null} for none. */ public synchronized StoredSubscription setTopicId(String topicId) { this.topicId = topicId; return this; } @Override public String toString() { return Objects.toStringHelper(StoredSubscription.class) .add("notificationCallback", getNotificationCallback()).add("clientToken", getClientToken()) .add("expiration", getExpiration()).add("id", getId()).add("topicId", getTopicId()) .toString(); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof StoredSubscription)) { return false; } StoredSubscription o = (StoredSubscription) other; return getId().equals(o.getId()); } @Override public int hashCode() { return getId().hashCode(); } /** Returns a new random UUID to be used as a subscription ID. */ public static String randomId() { return UUID.randomUUID().toString(); } }
Java
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.xml.atom; import com.google.api.client.util.ArrayMap; import com.google.api.client.util.Beta; import com.google.api.client.util.ClassInfo; import com.google.api.client.util.Data; import com.google.api.client.util.FieldInfo; import com.google.api.client.util.GenericData; import com.google.api.client.util.Types; import java.util.Collection; import java.util.Map; import java.util.TreeSet; /** * {@link Beta} <br/> * Utilities for working with the Atom XML of Google Data APIs. * * @since 1.0 * @author Yaniv Inbar */ @Beta public class GoogleAtom { /** * GData namespace. * * @since 1.0 */ public static final String GD_NAMESPACE = "http://schemas.google.com/g/2005"; /** * Content type used on an error formatted in XML. * * @since 1.5 */ public static final String ERROR_CONTENT_TYPE = "application/vnd.google.gdata.error+xml"; // TODO(yanivi): require XmlNamespaceDictory and include xmlns declarations since there is no // guarantee that there is a match between Google's mapping and the one used by client /** * Returns the fields mask to use for the given data class of key/value pairs. It cannot be a * {@link Map}, {@link GenericData} or a {@link Collection}. * * @param dataClass data class of key/value pairs */ public static String getFieldsFor(Class<?> dataClass) { StringBuilder fieldsBuf = new StringBuilder(); appendFieldsFor(fieldsBuf, dataClass, new int[1]); return fieldsBuf.toString(); } /** * Returns the fields mask to use for the given data class of key/value pairs for the feed class * and for the entry class. This should only be used if the feed class does not contain the entry * class as a field. The data classes cannot be a {@link Map}, {@link GenericData} or a * {@link Collection}. * * @param feedClass feed data class * @param entryClass entry data class */ public static String getFeedFields(Class<?> feedClass, Class<?> entryClass) { StringBuilder fieldsBuf = new StringBuilder(); appendFeedFields(fieldsBuf, feedClass, entryClass); return fieldsBuf.toString(); } private static void appendFieldsFor( StringBuilder fieldsBuf, Class<?> dataClass, int[] numFields) { if (Map.class.isAssignableFrom(dataClass) || Collection.class.isAssignableFrom(dataClass)) { throw new IllegalArgumentException( "cannot specify field mask for a Map or Collection class: " + dataClass); } ClassInfo classInfo = ClassInfo.of(dataClass); for (String name : new TreeSet<String>(classInfo.getNames())) { FieldInfo fieldInfo = classInfo.getFieldInfo(name); if (fieldInfo.isFinal()) { continue; } if (++numFields[0] != 1) { fieldsBuf.append(','); } fieldsBuf.append(name); // TODO(yanivi): handle Java arrays? Class<?> fieldClass = fieldInfo.getType(); if (Collection.class.isAssignableFrom(fieldClass)) { // TODO(yanivi): handle Java collection of Java collection or Java map? fieldClass = (Class<?>) Types.getIterableParameter(fieldInfo.getField().getGenericType()); } // TODO(yanivi): implement support for map when server implements support for *:* if (fieldClass != null) { if (fieldInfo.isPrimitive()) { if (name.charAt(0) != '@' && !name.equals("text()")) { // TODO(yanivi): wait for bug fix from server to support text() -- already fixed??? // buf.append("/text()"); } } else if (!Collection.class.isAssignableFrom(fieldClass) && !Map.class.isAssignableFrom(fieldClass)) { int[] subNumFields = new int[1]; int openParenIndex = fieldsBuf.length(); fieldsBuf.append('('); // TODO(yanivi): abort if found cycle to avoid infinite loop appendFieldsFor(fieldsBuf, fieldClass, subNumFields); updateFieldsBasedOnNumFields(fieldsBuf, openParenIndex, subNumFields[0]); } } } } private static void appendFeedFields( StringBuilder fieldsBuf, Class<?> feedClass, Class<?> entryClass) { int[] numFields = new int[1]; appendFieldsFor(fieldsBuf, feedClass, numFields); if (numFields[0] != 0) { fieldsBuf.append(","); } fieldsBuf.append("entry("); int openParenIndex = fieldsBuf.length() - 1; numFields[0] = 0; appendFieldsFor(fieldsBuf, entryClass, numFields); updateFieldsBasedOnNumFields(fieldsBuf, openParenIndex, numFields[0]); } private static void updateFieldsBasedOnNumFields( StringBuilder fieldsBuf, int openParenIndex, int numFields) { switch (numFields) { case 0: fieldsBuf.deleteCharAt(openParenIndex); break; case 1: fieldsBuf.setCharAt(openParenIndex, '/'); break; default: fieldsBuf.append(')'); } } /** * Compute the patch object of key/value pairs from the given original and patched objects, adding * a {@code @gd:fields} key for the fields mask. * * @param patched patched object * @param original original object * @return patch object of key/value pairs */ public static Map<String, Object> computePatch(Object patched, Object original) { FieldsMask fieldsMask = new FieldsMask(); ArrayMap<String, Object> result = computePatchInternal(fieldsMask, patched, original); if (fieldsMask.numDifferences != 0) { result.put("@gd:fields", fieldsMask.buf.toString()); } return result; } private static ArrayMap<String, Object> computePatchInternal( FieldsMask fieldsMask, Object patchedObject, Object originalObject) { ArrayMap<String, Object> result = ArrayMap.create(); Map<String, Object> patchedMap = Data.mapOf(patchedObject); Map<String, Object> originalMap = Data.mapOf(originalObject); TreeSet<String> fieldNames = new TreeSet<String>(); fieldNames.addAll(patchedMap.keySet()); fieldNames.addAll(originalMap.keySet()); for (String name : fieldNames) { Object originalValue = originalMap.get(name); Object patchedValue = patchedMap.get(name); if (originalValue == patchedValue) { continue; } Class<?> type = originalValue == null ? patchedValue.getClass() : originalValue.getClass(); if (Data.isPrimitive(type)) { if (originalValue != null && originalValue.equals(patchedValue)) { continue; } fieldsMask.append(name); // TODO(yanivi): wait for bug fix from server // if (!name.equals("text()") && name.charAt(0) != '@') { // fieldsMask.buf.append("/text()"); // } if (patchedValue != null) { result.add(name, patchedValue); } } else if (Collection.class.isAssignableFrom(type)) { if (originalValue != null && patchedValue != null) { @SuppressWarnings("unchecked") Collection<Object> originalCollection = (Collection<Object>) originalValue; @SuppressWarnings("unchecked") Collection<Object> patchedCollection = (Collection<Object>) patchedValue; int size = originalCollection.size(); if (size == patchedCollection.size()) { int i; for (i = 0; i < size; i++) { FieldsMask subFieldsMask = new FieldsMask(); computePatchInternal(subFieldsMask, patchedValue, originalValue); if (subFieldsMask.numDifferences != 0) { break; } } if (i == size) { continue; } } } // TODO(yanivi): implement throw new UnsupportedOperationException( "not yet implemented: support for patching collections"); } else { if (originalValue == null) { // TODO(yanivi): test fieldsMask.append(name); result.add(name, Data.mapOf(patchedValue)); } else if (patchedValue == null) { // TODO(yanivi): test fieldsMask.append(name); } else { FieldsMask subFieldsMask = new FieldsMask(); ArrayMap<String, Object> patch = computePatchInternal(subFieldsMask, patchedValue, originalValue); int numDifferences = subFieldsMask.numDifferences; if (numDifferences != 0) { fieldsMask.append(name, subFieldsMask); result.add(name, patch); } } } } return result; } static class FieldsMask { int numDifferences; StringBuilder buf = new StringBuilder(); void append(String name) { StringBuilder buf = this.buf; if (++numDifferences != 1) { buf.append(','); } buf.append(name); } void append(String name, FieldsMask subFields) { append(name); StringBuilder buf = this.buf; boolean isSingle = subFields.numDifferences == 1; if (isSingle) { buf.append('/'); } else { buf.append('('); } buf.append(subFields.buf); if (!isSingle) { buf.append(')'); } } } private GoogleAtom() { } }
Java