idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
26,400
public void inverse ( Transformation2D inverse ) { double det = xx * yy - xy * yx ; if ( det == 0 ) { inverse . setZero ( ) ; return ; } det = 1 / det ; inverse . xd = ( xy * yd - xd * yy ) * det ; inverse . yd = ( xd * yx - xx * yd ) * det ; inverse . xx = yy * det ; inverse . xy = - xy * det ; inverse . yx = - yx * det ; inverse . yy = xx * det ; }
Produces inverse matrix for this matrix and puts result into the inverse parameter .
26,401
static boolean _isRingInRing2D ( MultiPath polygon , int iRing1 , int iRing2 , double tolerance , QuadTree quadTree ) { MultiPathImpl polygonImpl = ( MultiPathImpl ) polygon . _getImpl ( ) ; SegmentIteratorImpl segIter = polygonImpl . querySegmentIterator ( ) ; segIter . resetToPath ( iRing1 ) ; if ( ! segIter . nextPath ( ) || ! segIter . hasNextSegment ( ) ) throw new GeometryException ( "corrupted geometry" ) ; int res = 2 ; while ( res == 2 && segIter . hasNextSegment ( ) ) { Segment segment = segIter . nextSegment ( ) ; Point2D point = segment . getCoord2D ( 0.5 ) ; res = PointInPolygonHelper . isPointInRing ( polygonImpl , iRing2 , point , tolerance , quadTree ) ; } if ( res == 2 ) throw GeometryException . GeometryInternalError ( ) ; if ( res == 1 ) return true ; return false ; }
we assume that all of Ring1 is inside Ring2 .
26,402
public void add ( MultiPath src , boolean bReversePaths ) { m_impl . add ( ( MultiPathImpl ) src . _getImpl ( ) , bReversePaths ) ; }
Appends all paths from another multipath .
26,403
public void addPath ( MultiPath src , int srcPathIndex , boolean bForward ) { m_impl . addPath ( ( MultiPathImpl ) src . _getImpl ( ) , srcPathIndex , bForward ) ; }
Copies a path from another multipath .
26,404
void addPath ( Point2D [ ] points , int count , boolean bForward ) { m_impl . addPath ( points , count , bForward ) ; }
Adds a new path to this multipath .
26,405
public void addSegmentsFromPath ( MultiPath src , int srcPathIndex , int srcSegmentFrom , int srcSegmentCount , boolean bStartNewPath ) { m_impl . addSegmentsFromPath ( ( MultiPathImpl ) src . _getImpl ( ) , srcPathIndex , srcSegmentFrom , srcSegmentCount , bStartNewPath ) ; }
Adds segments from a source multipath to this MultiPath .
26,406
public void insertPath ( int pathIndex , MultiPath src , int srcPathIndex , boolean bForward ) { m_impl . insertPath ( pathIndex , ( MultiPathImpl ) src . _getImpl ( ) , srcPathIndex , bForward ) ; }
Inserts a path from another multipath .
26,407
void insertPath ( int pathIndex , Point2D [ ] points , int pointsOffset , int count , boolean bForward ) { m_impl . insertPath ( pathIndex , points , pointsOffset , count , bForward ) ; }
Inserts a path from an array of 2D Points .
26,408
public void insertPoints ( int pathIndex , int beforePointIndex , MultiPath src , int srcPathIndex , int srcPointIndexFrom , int srcPointCount , boolean bForward ) { m_impl . insertPoints ( pathIndex , beforePointIndex , ( MultiPathImpl ) src . _getImpl ( ) , srcPathIndex , srcPointIndexFrom , srcPointCount , bForward ) ; }
Inserts vertices from the given multipath into this multipath . All added vertices are connected by linear segments with each other and with the existing vertices .
26,409
void insertPoints ( int pathIndex , int beforePointIndex , Point2D [ ] src , int srcPointIndexFrom , int srcPointCount , boolean bForward ) { m_impl . insertPoints ( pathIndex , beforePointIndex , src , srcPointIndexFrom , srcPointCount , bForward ) ; }
Inserts a part of a path from the given array .
26,410
void bezierTo ( Point2D controlPoint1 , Point2D controlPoint2 , Point2D endPoint ) { m_impl . bezierTo ( controlPoint1 , controlPoint2 , endPoint ) ; }
Adds a Cubic Bezier Segment to the current Path . The Bezier Segment connects the current last Point and the given endPoint .
26,411
public static boolean isDefaultValue ( int semantics , double v ) { return NumberUtils . doubleToInt64Bits ( _defaultValues [ semantics ] ) == NumberUtils . doubleToInt64Bits ( v ) ; }
Checks if the given value is the default one . The simple equality test with GetDefaultValue does not work due to the use of NaNs as default value for some parameters .
26,412
public int createTreap ( int treap_data ) { int treap = m_treapData . newElement ( ) ; setSize_ ( 0 , treap ) ; setTreapData_ ( treap_data , treap ) ; return treap ; }
Create a new treap and returns the treap handle .
26,413
public int addElement ( int element , int treap ) { int treap_ ; if ( treap == - 1 ) { if ( m_defaultTreap == nullNode ( ) ) m_defaultTreap = createTreap ( - 1 ) ; treap_ = m_defaultTreap ; } else { treap_ = treap ; } return addElement_ ( element , 0 , treap_ ) ; }
Adds new element to the treap . Allows duplicates to be added .
26,414
public int addUniqueElement ( int element , int treap ) { int treap_ ; if ( treap == - 1 ) { if ( m_defaultTreap == nullNode ( ) ) m_defaultTreap = createTreap ( - 1 ) ; treap_ = m_defaultTreap ; } else { treap_ = treap ; } return addElement_ ( element , 1 , treap_ ) ; }
the already existing element equal to element .
26,415
public int addElementAtPosition ( int prevNode , int nextNode , int element , boolean bUnique , boolean bCallCompare , int treap ) { int treap_ = treap ; if ( treap_ == - 1 ) { if ( m_defaultTreap == nullNode ( ) ) m_defaultTreap = createTreap ( - 1 ) ; treap_ = m_defaultTreap ; } if ( getRoot_ ( treap_ ) == nullNode ( ) ) { assert ( nextNode == nullNode ( ) && prevNode == nullNode ( ) ) ; int root = newNode_ ( element ) ; setRoot_ ( root , treap_ ) ; addToList_ ( - 1 , root , treap_ ) ; return root ; } int cmpNext ; int cmpPrev ; if ( bCallCompare ) { cmpNext = nextNode != nullNode ( ) ? m_comparator . compare ( this , element , nextNode ) : - 1 ; assert ( cmpNext <= 0 ) ; cmpPrev = prevNode != nullNode ( ) ? m_comparator . compare ( this , element , prevNode ) : 1 ; } else { cmpNext = - 1 ; cmpPrev = 1 ; } if ( bUnique && ( cmpNext == 0 || cmpPrev == 0 ) ) { m_comparator . onAddUniqueElementFailedImpl_ ( element ) ; int cur = cmpNext == 0 ? nextNode : prevNode ; setDuplicateElement_ ( cur , treap_ ) ; return - 1 ; } int cur ; int cmp ; boolean bNext ; if ( nextNode != nullNode ( ) && prevNode != nullNode ( ) ) { bNext = m_random > NumberUtils . nextRand ( m_random ) >> 1 ; } else bNext = nextNode != nullNode ( ) ; if ( bNext ) { cmp = cmpNext ; cur = nextNode ; } else { cmp = cmpPrev ; cur = prevNode ; } int newNode = - 1 ; int before = - 1 ; boolean b_first = true ; for ( ; ; ) { if ( cmp < 0 ) { int left = getLeft ( cur ) ; if ( left != nullNode ( ) ) cur = left ; else { before = cur ; newNode = newNode_ ( element ) ; setLeft_ ( cur , newNode ) ; setParent_ ( newNode , cur ) ; break ; } } else { int right = getRight ( cur ) ; if ( right != nullNode ( ) ) cur = right ; else { before = getNext ( cur ) ; newNode = newNode_ ( element ) ; setRight_ ( cur , newNode ) ; setParent_ ( newNode , cur ) ; break ; } } if ( b_first ) { cmp *= - 1 ; b_first = false ; } } bubbleUp_ ( newNode ) ; if ( getParent ( newNode ) == nullNode ( ) ) setRoot_ ( newNode , treap_ ) ; addToList_ ( before , newNode , treap_ ) ; return newNode ; }
get_duplicate_element reutrns the node of the already existing element .
26,416
public void deleteNode ( int treap_node_index , int treap ) { touch_ ( ) ; if ( m_comparator != null ) m_comparator . onDeleteImpl_ ( this , treap_node_index ) ; int treap_ ; if ( treap == - 1 ) treap_ = m_defaultTreap ; else treap_ = treap ; if ( ! m_b_balancing ) { unbalancedDelete_ ( treap_node_index , treap_ ) ; } else deleteNode_ ( treap_node_index , treap_ ) ; }
Removes a node from the treap . Throws if doesn t exist .
26,417
public int search ( int data , int treap ) { int cur = getRoot ( treap ) ; while ( cur != nullNode ( ) ) { int res = m_comparator . compare ( this , data , cur ) ; if ( res == 0 ) return cur ; else if ( res < 0 ) cur = getLeft ( cur ) ; else cur = getRight ( cur ) ; } m_comparator . onEndSearchImpl_ ( data ) ; return nullNode ( ) ; }
Finds an element in the treap and returns its node or - 1 .
26,418
public void setElement ( int treap_node_index , int newElement ) { if ( m_comparator != null ) m_comparator . onSetImpl_ ( this , treap_node_index ) ; setElement_ ( treap_node_index , newElement ) ; }
element will change the sorted order .
26,419
private static Point2D computePointsCentroid ( MultiPoint multiPoint ) { double xSum = 0 ; double ySum = 0 ; int pointCount = multiPoint . getPointCount ( ) ; Point2D point2D = new Point2D ( ) ; for ( int i = 0 ; i < pointCount ; i ++ ) { multiPoint . getXY ( i , point2D ) ; xSum += point2D . x ; ySum += point2D . y ; } return new Point2D ( xSum / pointCount , ySum / pointCount ) ; }
Points centroid is arithmetic mean of the input points
26,420
private static Point2D computePolylineCentroid ( Polyline polyline ) { double xSum = 0 ; double ySum = 0 ; double weightSum = 0 ; Point2D startPoint = new Point2D ( ) ; Point2D endPoint = new Point2D ( ) ; for ( int i = 0 ; i < polyline . getPathCount ( ) ; i ++ ) { polyline . getXY ( polyline . getPathStart ( i ) , startPoint ) ; polyline . getXY ( polyline . getPathEnd ( i ) - 1 , endPoint ) ; double dx = endPoint . x - startPoint . x ; double dy = endPoint . y - startPoint . y ; double length = sqrt ( dx * dx + dy * dy ) ; weightSum += length ; xSum += ( startPoint . x + endPoint . x ) * length / 2 ; ySum += ( startPoint . y + endPoint . y ) * length / 2 ; } return new Point2D ( xSum / weightSum , ySum / weightSum ) ; }
Lines centroid is weighted mean of each line segment weight in terms of line length
26,421
public void mergeVertexDescription ( VertexDescription src ) { _touch ( ) ; if ( src == m_description ) return ; VertexDescription newdescription = VertexDescriptionDesignerImpl . getMergedVertexDescription ( m_description , src ) ; if ( newdescription == m_description ) return ; _assignVertexDescriptionImpl ( newdescription ) ; }
Merges the new VertexDescription by adding missing attributes from the src . The Geometry will have a union of the current and the src descriptions .
26,422
public void addAttribute ( int semantics ) { _touch ( ) ; if ( m_description . hasAttribute ( semantics ) ) return ; VertexDescription newvd = VertexDescriptionDesignerImpl . getMergedVertexDescription ( m_description , semantics ) ; _assignVertexDescriptionImpl ( newvd ) ; }
Adds a new attribute to the Geometry .
26,423
public void dropAttribute ( int semantics ) { _touch ( ) ; if ( ! m_description . hasAttribute ( semantics ) ) return ; VertexDescription newvd = VertexDescriptionDesignerImpl . removeSemanticsFromVertexDescription ( m_description , semantics ) ; _assignVertexDescriptionImpl ( newvd ) ; }
Drops an attribute from the Geometry . Dropping the attribute is equivalent to setting the attribute to the default value for each vertex However it is faster and the result Geometry has smaller memory footprint and smaller size when persisted .
26,424
int createList ( ) { int node = newList_ ( ) ; if ( m_b_allow_navigation_between_lists ) { m_lists . setField ( node , 3 , m_list_of_lists ) ; if ( m_list_of_lists != nullNode ( ) ) m_lists . setField ( m_list_of_lists , 2 , node ) ; m_list_of_lists = node ; } return node ; }
Creates new list and returns it s handle .
26,425
void deleteList ( int list ) { int ptr = getFirst ( list ) ; while ( ptr != nullNode ( ) ) { int p = ptr ; ptr = getNext ( ptr ) ; freeNode_ ( p ) ; } if ( m_b_allow_navigation_between_lists ) { int prevList = m_lists . getField ( list , 2 ) ; int nextList = m_lists . getField ( list , 3 ) ; if ( prevList != nullNode ( ) ) m_lists . setField ( prevList , 3 , nextList ) ; else m_list_of_lists = nextList ; if ( nextList != nullNode ( ) ) m_lists . setField ( nextList , 2 , prevList ) ; } freeList_ ( list ) ; }
Deletes a list .
26,426
void deleteElement ( int list , int prevNode , int node ) { if ( prevNode != nullNode ( ) ) { assert ( m_listNodes . getField ( prevNode , 1 ) == node ) ; m_listNodes . setField ( prevNode , 1 , m_listNodes . getField ( node , 1 ) ) ; if ( m_lists . getField ( list , 1 ) == node ) { m_lists . setField ( list , 1 , prevNode ) ; } } else { assert ( m_lists . getField ( list , 0 ) == node ) ; m_lists . setField ( list , 0 , m_listNodes . getField ( node , 1 ) ) ; if ( m_lists . getField ( list , 1 ) == node ) { assert ( m_listNodes . getField ( node , 1 ) == nullNode ( ) ) ; m_lists . setField ( list , 1 , nullNode ( ) ) ; } } freeNode_ ( node ) ; }
required because the list is singly connected ) .
26,427
int concatenateLists ( int list1 , int list2 ) { int tailNode1 = m_lists . getField ( list1 , 1 ) ; int headNode2 = m_lists . getField ( list2 , 0 ) ; if ( headNode2 != nullNode ( ) ) { if ( tailNode1 != nullNode ( ) ) { m_listNodes . setField ( tailNode1 , 1 , headNode2 ) ; m_lists . setField ( list1 , 1 , m_lists . getField ( list2 , 1 ) ) ; } else { m_lists . setField ( list1 , 0 , headNode2 ) ; m_lists . setField ( list1 , 1 , m_lists . getField ( list2 , 1 ) ) ; } } if ( m_b_allow_navigation_between_lists ) { int prevList = m_lists . getField ( list2 , 2 ) ; int nextList = m_lists . getField ( list2 , 3 ) ; if ( prevList != nullNode ( ) ) m_lists . setField ( prevList , 3 , nextList ) ; else m_list_of_lists = nextList ; if ( nextList != nullNode ( ) ) m_lists . setField ( nextList , 2 , prevList ) ; } freeList_ ( list2 ) ; return list1 ; }
Returns list1 .
26,428
public int addElement ( int element , int hash ) { int bit_bucket = hash % ( m_bit_filter . length << 5 ) ; m_bit_filter [ ( bit_bucket >> 5 ) ] |= ( 1 << ( bit_bucket & 0x1F ) ) ; int bucket = hash % m_hashBuckets . size ( ) ; int list = m_hashBuckets . get ( bucket ) ; if ( list == - 1 ) { list = m_lists . createList ( ) ; m_hashBuckets . set ( bucket , list ) ; } int node = m_lists . addElement ( list , element ) ; return node ; }
Adds new element to the hash table .
26,429
public int findNode ( int element ) { int hash = m_hash . getHash ( element ) ; int ptr = getFirstInBucket ( hash ) ; while ( ptr != - 1 ) { int e = m_lists . getElement ( ptr ) ; if ( m_hash . equal ( e , element ) ) { return ptr ; } ptr = m_lists . getNext ( ptr ) ; } return - 1 ; }
the given one .
26,430
public int findNode ( Object elementDescriptor ) { int hash = m_hash . getHash ( elementDescriptor ) ; int ptr = getFirstInBucket ( hash ) ; ; while ( ptr != - 1 ) { int e = m_lists . getElement ( ptr ) ; if ( m_hash . equal ( elementDescriptor , e ) ) { return ptr ; } ptr = m_lists . getNext ( ptr ) ; } return - 1 ; }
the given element descriptor .
26,431
public int getNextNode ( int elementHandle ) { int element = m_lists . getElement ( elementHandle ) ; int ptr = m_lists . getNext ( elementHandle ) ; while ( ptr != - 1 ) { int e = m_lists . getElement ( ptr ) ; if ( m_hash . equal ( e , element ) ) { return ptr ; } ptr = m_lists . getNext ( ptr ) ; } return - 1 ; }
Gets next equal node .
26,432
public void deleteNode ( int node ) { int element = getElement ( node ) ; int hash = m_hash . getHash ( element ) ; int bucket = hash % m_hashBuckets . size ( ) ; int list = m_hashBuckets . get ( bucket ) ; if ( list == - 1 ) throw new IllegalArgumentException ( ) ; int ptr = m_lists . getFirst ( list ) ; int prev = - 1 ; while ( ptr != - 1 ) { if ( ptr == node ) { m_lists . deleteElement ( list , prev , ptr ) ; if ( m_lists . getFirst ( list ) == - 1 ) { m_lists . deleteList ( list ) ; m_hashBuckets . set ( bucket , - 1 ) ; } return ; } prev = ptr ; ptr = m_lists . getNext ( ptr ) ; } throw new IllegalArgumentException ( ) ; }
Removes a node .
26,433
public void clear ( ) { Arrays . fill ( m_bit_filter , 0 ) ; m_hashBuckets = new AttributeStreamOfInt32 ( m_hashBuckets . size ( ) , nullNode ( ) ) ; m_lists . clear ( ) ; }
Removes all elements from the hash table .
26,434
public static ViewPropertyAnimator animate ( View view ) { ViewPropertyAnimator animator = ANIMATORS . get ( view ) ; if ( animator == null ) { final int version = Integer . valueOf ( Build . VERSION . SDK ) ; if ( version >= Build . VERSION_CODES . ICE_CREAM_SANDWICH ) { animator = new ViewPropertyAnimatorICS ( view ) ; } else if ( version >= Build . VERSION_CODES . HONEYCOMB ) { animator = new ViewPropertyAnimatorHC ( view ) ; } else { animator = new ViewPropertyAnimatorPreHC ( view ) ; } ANIMATORS . put ( view , animator ) ; } return animator ; }
This method returns a ViewPropertyAnimator object which can be used to animate specific properties on this View .
26,435
void addFlakes ( int quantity ) { for ( int i = 0 ; i < quantity ; ++ i ) { flakes . add ( Flake . createFlake ( getWidth ( ) , droid ) ) ; } setNumFlakes ( numFlakes + quantity ) ; }
Add the specified number of droidflakes .
26,436
void subtractFlakes ( int quantity ) { for ( int i = 0 ; i < quantity ; ++ i ) { int index = numFlakes - i - 1 ; flakes . remove ( index ) ; } setNumFlakes ( numFlakes - quantity ) ; }
Subtract the specified number of droidflakes . We just take them off the end of the list leaving the others unchanged .
26,437
static Flake createFlake ( float xRange , Bitmap originalBitmap ) { Flake flake = new Flake ( ) ; flake . width = ( int ) ( 5 + ( float ) Math . random ( ) * 50 ) ; float hwRatio = originalBitmap . getHeight ( ) / originalBitmap . getWidth ( ) ; flake . height = ( int ) ( flake . width * hwRatio ) ; flake . x = ( float ) Math . random ( ) * ( xRange - flake . width ) ; flake . y = 0 - ( flake . height + ( float ) Math . random ( ) * flake . height ) ; flake . speed = 50 + ( float ) Math . random ( ) * 150 ; flake . rotation = ( float ) Math . random ( ) * 180 - 90 ; flake . rotationSpeed = ( float ) Math . random ( ) * 90 - 45 ; flake . bitmap = bitmapMap . get ( flake . width ) ; if ( flake . bitmap == null ) { flake . bitmap = Bitmap . createScaledBitmap ( originalBitmap , ( int ) flake . width , ( int ) flake . height , true ) ; bitmapMap . put ( flake . width , flake . bitmap ) ; } return flake ; }
Creates a new droidflake in the given xRange and with the given bitmap . Parameters of location size rotation and speed are randomly determined .
26,438
public static PropertyValuesHolder ofObject ( String propertyName , TypeEvaluator evaluator , Object ... values ) { PropertyValuesHolder pvh = new PropertyValuesHolder ( propertyName ) ; pvh . setObjectValues ( values ) ; pvh . setEvaluator ( evaluator ) ; return pvh ; }
Constructs and returns a PropertyValuesHolder with a given property name and set of Object values . This variant also takes a TypeEvaluator because the system cannot automatically interpolate between objects of unknown type .
26,439
public static < V > PropertyValuesHolder ofObject ( Property property , TypeEvaluator < V > evaluator , V ... values ) { PropertyValuesHolder pvh = new PropertyValuesHolder ( property ) ; pvh . setObjectValues ( values ) ; pvh . setEvaluator ( evaluator ) ; return pvh ; }
Constructs and returns a PropertyValuesHolder with a given property and set of Object values . This variant also takes a TypeEvaluator because the system cannot automatically interpolate between objects of unknown type .
26,440
public void setKeyframes ( Keyframe ... values ) { int numKeyframes = values . length ; Keyframe keyframes [ ] = new Keyframe [ Math . max ( numKeyframes , 2 ) ] ; mValueType = ( ( Keyframe ) values [ 0 ] ) . getType ( ) ; for ( int i = 0 ; i < numKeyframes ; ++ i ) { keyframes [ i ] = ( Keyframe ) values [ i ] ; } mKeyframeSet = new KeyframeSet ( keyframes ) ; }
Set the animated values for this object to this set of Keyframes .
26,441
private Method getPropertyFunction ( Class targetClass , String prefix , Class valueType ) { Method returnVal = null ; String methodName = getMethodName ( prefix , mPropertyName ) ; Class args [ ] = null ; if ( valueType == null ) { try { returnVal = targetClass . getMethod ( methodName , args ) ; } catch ( NoSuchMethodException e ) { try { returnVal = targetClass . getDeclaredMethod ( methodName , args ) ; returnVal . setAccessible ( true ) ; } catch ( NoSuchMethodException e2 ) { Log . e ( "PropertyValuesHolder" , "Couldn't find no-arg method for property " + mPropertyName + ": " + e ) ; } } } else { args = new Class [ 1 ] ; Class typeVariants [ ] ; if ( mValueType . equals ( Float . class ) ) { typeVariants = FLOAT_VARIANTS ; } else if ( mValueType . equals ( Integer . class ) ) { typeVariants = INTEGER_VARIANTS ; } else if ( mValueType . equals ( Double . class ) ) { typeVariants = DOUBLE_VARIANTS ; } else { typeVariants = new Class [ 1 ] ; typeVariants [ 0 ] = mValueType ; } for ( Class typeVariant : typeVariants ) { args [ 0 ] = typeVariant ; try { returnVal = targetClass . getMethod ( methodName , args ) ; mValueType = typeVariant ; return returnVal ; } catch ( NoSuchMethodException e ) { try { returnVal = targetClass . getDeclaredMethod ( methodName , args ) ; returnVal . setAccessible ( true ) ; mValueType = typeVariant ; return returnVal ; } catch ( NoSuchMethodException e2 ) { } } } Log . e ( "PropertyValuesHolder" , "Couldn't find setter/getter for property " + mPropertyName + " with value type " + mValueType ) ; } return returnVal ; }
Determine the setter or getter function using the JavaBeans convention of setFoo or getFoo for a property named foo . This function figures out what the name of the function should be and uses reflection to find the Method with that name on the target object .
26,442
private Method setupSetterOrGetter ( Class targetClass , HashMap < Class , HashMap < String , Method > > propertyMapMap , String prefix , Class valueType ) { Method setterOrGetter = null ; try { mPropertyMapLock . writeLock ( ) . lock ( ) ; HashMap < String , Method > propertyMap = propertyMapMap . get ( targetClass ) ; if ( propertyMap != null ) { setterOrGetter = propertyMap . get ( mPropertyName ) ; } if ( setterOrGetter == null ) { setterOrGetter = getPropertyFunction ( targetClass , prefix , valueType ) ; if ( propertyMap == null ) { propertyMap = new HashMap < String , Method > ( ) ; propertyMapMap . put ( targetClass , propertyMap ) ; } propertyMap . put ( mPropertyName , setterOrGetter ) ; } } finally { mPropertyMapLock . writeLock ( ) . unlock ( ) ; } return setterOrGetter ; }
Returns the setter or getter requested . This utility function checks whether the requested method exists in the propertyMapMap cache . If not it calls another utility function to request the Method from the targetClass directly .
26,443
void setupEndValue ( Object target ) { setupValue ( target , mKeyframeSet . mKeyframes . get ( mKeyframeSet . mKeyframes . size ( ) - 1 ) ) ; }
This function is called by ObjectAnimator when setting the end values for an animation . The end values are set according to the current values in the target object . The property whose value is extracted is whatever is specified by the propertyName of this PropertyValuesHolder object .
26,444
void init ( ) { if ( mEvaluator == null ) { mEvaluator = ( mValueType == Integer . class ) ? sIntEvaluator : ( mValueType == Float . class ) ? sFloatEvaluator : null ; } if ( mEvaluator != null ) { mKeyframeSet . setEvaluator ( mEvaluator ) ; } }
Internal function called by ValueAnimator to set up the TypeEvaluator that will be used to calculate animated values .
26,445
public ViewPropertyAnimator setDuration ( long duration ) { if ( duration < 0 ) { throw new IllegalArgumentException ( "Animators cannot have negative duration: " + duration ) ; } mDurationSet = true ; mDuration = duration ; return this ; }
Sets the duration for the underlying animator that animates the requested properties . By default the animator uses the default value for ValueAnimator . Calling this method will cause the declared value to be used instead .
26,446
private void startAnimation ( ) { ValueAnimator animator = ValueAnimator . ofFloat ( 1.0f ) ; ArrayList < NameValuesHolder > nameValueList = ( ArrayList < NameValuesHolder > ) mPendingAnimations . clone ( ) ; mPendingAnimations . clear ( ) ; int propertyMask = 0 ; int propertyCount = nameValueList . size ( ) ; for ( int i = 0 ; i < propertyCount ; ++ i ) { NameValuesHolder nameValuesHolder = nameValueList . get ( i ) ; propertyMask |= nameValuesHolder . mNameConstant ; } mAnimatorMap . put ( animator , new PropertyBundle ( propertyMask , nameValueList ) ) ; animator . addUpdateListener ( mAnimatorEventListener ) ; animator . addListener ( mAnimatorEventListener ) ; if ( mStartDelaySet ) { animator . setStartDelay ( mStartDelay ) ; } if ( mDurationSet ) { animator . setDuration ( mDuration ) ; } if ( mInterpolatorSet ) { animator . setInterpolator ( mInterpolator ) ; } animator . start ( ) ; }
Starts the underlying Animator for a set of properties . We use a single animator that simply runs from 0 to 1 and then use that fractional value to set each property value accordingly .
26,447
public void setTarget ( Object target ) { if ( mTarget != target ) { final Object oldTarget = mTarget ; mTarget = target ; if ( oldTarget != null && target != null && oldTarget . getClass ( ) == target . getClass ( ) ) { return ; } mInitialized = false ; } }
Sets the target object whose property will be animated by this animation
26,448
public static ValueAnimator ofPropertyValuesHolder ( PropertyValuesHolder ... values ) { ValueAnimator anim = new ValueAnimator ( ) ; anim . setValues ( values ) ; return anim ; }
Constructs and returns a ValueAnimator that animates between the values specified in the PropertyValuesHolder objects .
26,449
public void addUpdateListener ( AnimatorUpdateListener listener ) { if ( mUpdateListeners == null ) { mUpdateListeners = new ArrayList < AnimatorUpdateListener > ( ) ; } mUpdateListeners . add ( listener ) ; }
Adds a listener to the set of listeners that are sent update events through the life of an animation . This method is called on all listeners for every frame of the animation after the values for the animation have been calculated .
26,450
public void removeUpdateListener ( AnimatorUpdateListener listener ) { if ( mUpdateListeners == null ) { return ; } mUpdateListeners . remove ( listener ) ; if ( mUpdateListeners . size ( ) == 0 ) { mUpdateListeners = null ; } }
Removes a listener from the set listening to frame updates for this animation .
26,451
public void reverse ( ) { mPlayingBackwards = ! mPlayingBackwards ; if ( mPlayingState == RUNNING ) { long currentTime = AnimationUtils . currentAnimationTimeMillis ( ) ; long currentPlayTime = currentTime - mStartTime ; long timeLeft = mDuration - currentPlayTime ; mStartTime = currentTime - timeLeft ; } else { start ( true ) ; } }
Plays the ValueAnimator in reverse . If the animation is already running it will stop itself and play backwards from the point reached when reverse was called . If the animation is not currently running then it will start from the end and play backwards . This behavior is only set for the current animation ; future playing of the animation will use the default behavior of playing forward .
26,452
private void endAnimation ( ) { sAnimations . get ( ) . remove ( this ) ; sPendingAnimations . get ( ) . remove ( this ) ; sDelayedAnims . get ( ) . remove ( this ) ; mPlayingState = STOPPED ; if ( mRunning && mListeners != null ) { ArrayList < AnimatorListener > tmpListeners = ( ArrayList < AnimatorListener > ) mListeners . clone ( ) ; int numListeners = tmpListeners . size ( ) ; for ( int i = 0 ; i < numListeners ; ++ i ) { tmpListeners . get ( i ) . onAnimationEnd ( this ) ; } } mRunning = false ; mStarted = false ; }
Called internally to end an animation by removing it from the animations list . Must be called on the UI thread .
26,453
private void startAnimation ( ) { initAnimation ( ) ; sAnimations . get ( ) . add ( this ) ; if ( mStartDelay > 0 && mListeners != null ) { ArrayList < AnimatorListener > tmpListeners = ( ArrayList < AnimatorListener > ) mListeners . clone ( ) ; int numListeners = tmpListeners . size ( ) ; for ( int i = 0 ; i < numListeners ; ++ i ) { tmpListeners . get ( i ) . onAnimationStart ( this ) ; } } }
Called internally to start an animation by adding it to the active animations list . Must be called on the UI thread .
26,454
public static void clearAllAnimations ( ) { sAnimations . get ( ) . clear ( ) ; sPendingAnimations . get ( ) . clear ( ) ; sDelayedAnims . get ( ) . clear ( ) ; }
Clear all animations on this thread without canceling or ending them . This should be used with caution .
26,455
public ArrayList < Animator > getChildAnimations ( ) { ArrayList < Animator > childList = new ArrayList < Animator > ( ) ; for ( Node node : mNodes ) { childList . add ( node . animation ) ; } return childList ; }
Returns the current list of child Animator objects controlled by this AnimatorSet . This is a copy of the internal list ; modifications to the returned list will not affect the AnimatorSet although changes to the underlying Animator objects will affect those objects being managed by the AnimatorSet .
26,456
public boolean isRunning ( ) { for ( Node node : mNodes ) { if ( node . animation . isRunning ( ) ) { return true ; } } return false ; }
Returns true if any of the child animations of this AnimatorSet have been started and have not yet ended .
26,457
public AnimatorSet setDuration ( long duration ) { if ( duration < 0 ) { throw new IllegalArgumentException ( "duration must be a value of zero or greater" ) ; } for ( Node node : mNodes ) { node . animation . setDuration ( duration ) ; } mDuration = duration ; return this ; }
Sets the length of each of the current child animations of this AnimatorSet . By default each child animation will use its own duration . If the duration is set on the AnimatorSet then each child animation inherits this duration .
26,458
public void doStart ( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { if ( ! common . checkPost ( request , response ) ) return ; User user = common . requireLoggedInUser ( request , response ) ; if ( user == null ) return ; DbxWebAuth . Request authRequest = DbxWebAuth . newRequestBuilder ( ) . withRedirectUri ( getRedirectUri ( request ) , getSessionStore ( request ) ) . build ( ) ; String authorizeUrl = getWebAuth ( request ) . authorize ( authRequest ) ; response . sendRedirect ( authorizeUrl ) ; }
Start the process of getting a Dropbox API access token for the user s Dropbox account .
26,459
public void doFinish ( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { if ( ! common . checkGet ( request , response ) ) return ; User user = common . requireLoggedInUser ( request , response ) ; if ( user == null ) { common . pageSoftError ( response , "Can't do /dropbox-auth-finish. Nobody is logged in." ) ; return ; } DbxAuthFinish authFinish ; try { authFinish = getWebAuth ( request ) . finishFromRedirect ( getRedirectUri ( request ) , getSessionStore ( request ) , request . getParameterMap ( ) ) ; } catch ( DbxWebAuth . BadRequestException e ) { common . log . println ( "On /dropbox-auth-finish: Bad request: " + e . getMessage ( ) ) ; response . sendError ( 400 ) ; return ; } catch ( DbxWebAuth . BadStateException e ) { response . sendRedirect ( common . getUrl ( request , "/dropbox-auth-start" ) ) ; return ; } catch ( DbxWebAuth . CsrfException e ) { common . log . println ( "On /dropbox-auth-finish: CSRF mismatch: " + e . getMessage ( ) ) ; response . sendError ( 403 ) ; return ; } catch ( DbxWebAuth . NotApprovedException e ) { common . page ( response , 200 , "Not approved?" , "Why not, bro?" ) ; return ; } catch ( DbxWebAuth . ProviderException e ) { common . log . println ( "On /dropbox-auth-finish: Auth failed: " + e . getMessage ( ) ) ; response . sendError ( 503 , "Error communicating with Dropbox." ) ; return ; } catch ( DbxException e ) { common . log . println ( "On /dropbox-auth-finish: Error getting token: " + e ) ; response . sendError ( 503 , "Error communicating with Dropbox." ) ; return ; } user . dropboxAccessToken = authFinish . getAccessToken ( ) ; common . saveUserDb ( ) ; response . sendRedirect ( "/" ) ; }
an HTTP POST .
26,460
public String start ( String urlState ) { if ( deprecatedRequest == null ) { throw new IllegalStateException ( "Must use DbxWebAuth.authorize instead." ) ; } return authorizeImpl ( deprecatedRequest . copy ( ) . withState ( urlState ) . build ( ) ) ; }
Starts authorization and returns a authorization URL on the Dropbox website that gives the lets the user grant your app access to their Dropbox account .
26,461
public DbxAuthFinish finishFromRedirect ( String redirectUri , DbxSessionStore sessionStore , Map < String , String [ ] > params ) throws DbxException , BadRequestException , BadStateException , CsrfException , NotApprovedException , ProviderException { if ( redirectUri == null ) throw new NullPointerException ( "redirectUri" ) ; if ( sessionStore == null ) throw new NullPointerException ( "sessionStore" ) ; if ( params == null ) throw new NullPointerException ( "params" ) ; String state = getParam ( params , "state" ) ; if ( state == null ) { throw new BadRequestException ( "Missing required parameter: \"state\"." ) ; } String error = getParam ( params , "error" ) ; String code = getParam ( params , "code" ) ; String errorDescription = getParam ( params , "error_description" ) ; if ( code == null && error == null ) { throw new BadRequestException ( "Missing both \"code\" and \"error\"." ) ; } if ( code != null && error != null ) { throw new BadRequestException ( "Both \"code\" and \"error\" are set." ) ; } if ( code != null && errorDescription != null ) { throw new BadRequestException ( "Both \"code\" and \"error_description\" are set." ) ; } state = verifyAndStripCsrfToken ( state , sessionStore ) ; if ( error != null ) { if ( error . equals ( "access_denied" ) ) { String exceptionMessage = errorDescription == null ? "No additional description from Dropbox" : "Additional description from Dropbox: " + errorDescription ; throw new NotApprovedException ( exceptionMessage ) ; } else { String exceptionMessage = errorDescription == null ? error : String . format ( "%s: %s" , error , errorDescription ) ; throw new ProviderException ( exceptionMessage ) ; } } return finish ( code , redirectUri , state ) ; }
Call this after the user has visited the authorizaton URL and Dropbox has redirected them back to you at the redirect URI .
26,462
protected void addExtrasToIntent ( Context context , Intent intent ) { intent . putExtra ( EXTRA_DROPBOX_UID , uid ) ; intent . putExtra ( EXTRA_CALLING_PACKAGE , context . getPackageName ( ) ) ; }
Add uid information to an explicit intent directed to DropboxApp
26,463
private static int getLoggedinState ( Context context , String uid ) { Cursor cursor = context . getContentResolver ( ) . query ( LOGGED_IN_URI . buildUpon ( ) . appendPath ( uid ) . build ( ) , null , null , null , null ) ; if ( cursor == null ) { return NO_USER ; } cursor . moveToFirst ( ) ; return cursor . getInt ( cursor . getColumnIndex ( "logged_in" ) ) ; }
Determine if user uid is logged in
26,464
static PackageInfo getDropboxAppPackage ( Context context , Intent intent ) { PackageManager manager = context . getPackageManager ( ) ; List < ResolveInfo > infos = manager . queryIntentActivities ( intent , 0 ) ; if ( null == infos || 1 != infos . size ( ) ) { return null ; } else { ResolveInfo resolveInfo = manager . resolveActivity ( intent , 0 ) ; if ( resolveInfo == null ) { return null ; } final PackageInfo packageInfo ; try { packageInfo = manager . getPackageInfo ( resolveInfo . activityInfo . packageName , PackageManager . GET_SIGNATURES ) ; } catch ( NameNotFoundException e ) { return null ; } for ( Signature signature : packageInfo . signatures ) { for ( String dbSignature : DROPBOX_APP_SIGNATURES ) { if ( dbSignature . equals ( signature . toCharsString ( ) ) ) { return packageInfo ; } } } } return null ; }
Verify that intent will be processed by Dropbox App
26,465
private static String toLanguageTag ( Locale locale ) { if ( locale == null ) { return null ; } StringBuilder tag = new StringBuilder ( ) ; tag . append ( locale . getLanguage ( ) . toLowerCase ( ) ) ; if ( ! locale . getCountry ( ) . isEmpty ( ) ) { tag . append ( "-" ) ; tag . append ( locale . getCountry ( ) . toUpperCase ( ) ) ; } return tag . toString ( ) ; }
Available in Java 7 but not in Java 6 . Do a hacky version of it here .
26,466
private static String toLanguageTag ( String locale ) { if ( locale == null ) { return null ; } if ( ! locale . contains ( "_" ) ) { return locale ; } if ( locale . startsWith ( "_" ) ) { return locale ; } String [ ] parts = locale . split ( "_" , 3 ) ; String lang = parts [ 0 ] ; String country = parts [ 1 ] ; String variant = parts . length == 3 ? parts [ 2 ] : "" ; return toLanguageTag ( new Locale ( lang , country , variant ) ) ; }
formats to the new one .
26,467
public DbxEntry getMetadata ( final String path , boolean includeMediaInfo ) throws DbxException { DbxPathV1 . checkArg ( "path" , path ) ; String host = this . host . getApi ( ) ; String apiPath = "1/metadata/auto" + path ; String [ ] params = { "list" , "false" , "include_media_info" , includeMediaInfo ? "true" : null , } ; return doGet ( host , apiPath , params , null , new DbxRequestUtil . ResponseHandler < DbxEntry > ( ) { public DbxEntry handle ( HttpRequestor . Response response ) throws DbxException { if ( response . getStatusCode ( ) == 404 ) return null ; if ( response . getStatusCode ( ) != 200 ) throw DbxRequestUtil . unexpectedStatus ( response ) ; return DbxRequestUtil . readJsonFromResponse ( DbxEntry . ReaderMaybeDeleted , response ) ; } } ) ; }
Get the file or folder metadata for a given path .
26,468
public DbxEntry . WithChildren getMetadataWithChildren ( String path , boolean includeMediaInfo ) throws DbxException { return getMetadataWithChildrenBase ( path , includeMediaInfo , DbxEntry . WithChildren . ReaderMaybeDeleted ) ; }
Get the metadata for a given path ; if the path refers to a folder get all the children s metadata as well .
26,469
public DbxAccountInfo getAccountInfo ( ) throws DbxException { String host = this . host . getApi ( ) ; String apiPath = "1/account/info" ; return doGet ( host , apiPath , null , null , new DbxRequestUtil . ResponseHandler < DbxAccountInfo > ( ) { public DbxAccountInfo handle ( HttpRequestor . Response response ) throws DbxException { if ( response . getStatusCode ( ) != 200 ) throw DbxRequestUtil . unexpectedStatus ( response ) ; return DbxRequestUtil . readJsonFromResponse ( DbxAccountInfo . Reader , response ) ; } } ) ; }
Retrieve the user s account information .
26,470
private Downloader startGetSomething ( final String apiPath , final String [ ] params ) throws DbxException { final String host = this . host . getContent ( ) ; return DbxRequestUtil . runAndRetry ( requestConfig . getMaxRetries ( ) , new DbxRequestUtil . RequestMaker < Downloader , DbxException > ( ) { public Downloader run ( ) throws DbxException { HttpRequestor . Response response = DbxRequestUtil . startGet ( requestConfig , accessToken , USER_AGENT_ID , host , apiPath , params , null ) ; boolean passedOwnershipOfStream = false ; try { if ( response . getStatusCode ( ) == 404 ) return null ; if ( response . getStatusCode ( ) != 200 ) throw DbxRequestUtil . unexpectedStatus ( response ) ; String metadataString = DbxRequestUtil . getFirstHeader ( response , "x-dropbox-metadata" ) ; DbxEntry . File metadata ; try { metadata = DbxEntry . File . Reader . readFully ( metadataString ) ; } catch ( JsonReadException ex ) { String requestId = DbxRequestUtil . getRequestId ( response ) ; throw new BadResponseException ( requestId , "Bad JSON in X-Dropbox-Metadata header: " + ex . getMessage ( ) , ex ) ; } Downloader result = new Downloader ( metadata , response . getBody ( ) ) ; passedOwnershipOfStream = true ; return result ; } finally { if ( ! passedOwnershipOfStream ) { try { response . getBody ( ) . close ( ) ; } catch ( IOException ex ) { } } } } } ) ; }
Generic function that downloads either files or thumbnails .
26,471
private < E extends Throwable > HttpRequestor . Response chunkedUploadCommon ( String [ ] params , long chunkSize , DbxStreamWriter < E > writer ) throws DbxException , E { String apiPath = "1/chunked_upload" ; ArrayList < HttpRequestor . Header > headers = new ArrayList < HttpRequestor . Header > ( ) ; headers . add ( new HttpRequestor . Header ( "Content-Type" , "application/octet-stream" ) ) ; headers . add ( new HttpRequestor . Header ( "Content-Length" , Long . toString ( chunkSize ) ) ) ; HttpRequestor . Uploader uploader = DbxRequestUtil . startPut ( requestConfig , accessToken , USER_AGENT_ID , host . getContent ( ) , apiPath , params , headers ) ; try { NoThrowOutputStream nt = new NoThrowOutputStream ( uploader . getBody ( ) ) ; try { writer . write ( nt ) ; } catch ( NoThrowOutputStream . HiddenException ex ) { if ( ex . owner == nt ) throw new NetworkIOException ( ex . getCause ( ) ) ; throw ex ; } long bytesWritten = nt . getBytesWritten ( ) ; if ( bytesWritten != chunkSize ) { throw new IllegalStateException ( "'chunkSize' is " + chunkSize + ", but 'writer' only wrote " + bytesWritten + " bytes" ) ; } try { return uploader . finish ( ) ; } catch ( IOException ex ) { throw new NetworkIOException ( ex ) ; } } finally { uploader . close ( ) ; } }
Internal function called by both chunkedUploadFirst and chunkedUploadAppend .
26,472
public long chunkedUploadAppend ( String uploadId , long uploadOffset , byte [ ] data , int dataOffset , int dataLength ) throws DbxException { return chunkedUploadAppend ( uploadId , uploadOffset , dataLength , new DbxStreamWriter . ByteArrayCopier ( data , dataOffset , dataLength ) ) ; }
Append data to a chunked upload session .
26,473
public < E extends Throwable > long chunkedUploadAppend ( String uploadId , long uploadOffset , long chunkSize , DbxStreamWriter < E > writer ) throws DbxException , E { if ( uploadId == null ) throw new IllegalArgumentException ( "'uploadId' can't be null" ) ; if ( uploadId . length ( ) == 0 ) throw new IllegalArgumentException ( "'uploadId' can't be empty" ) ; if ( uploadOffset < 0 ) throw new IllegalArgumentException ( "'offset' can't be negative" ) ; String [ ] params = { "upload_id" , uploadId , "offset" , Long . toString ( uploadOffset ) , } ; HttpRequestor . Response response = chunkedUploadCommon ( params , chunkSize , writer ) ; String requestId = DbxRequestUtil . getRequestId ( response ) ; try { ChunkedUploadState correctedState = chunkedUploadCheckForOffsetCorrection ( response ) ; long expectedOffset = uploadOffset + chunkSize ; if ( correctedState != null ) { if ( ! correctedState . uploadId . equals ( uploadId ) ) { throw new BadResponseException ( requestId , "uploadId mismatch: us=" + jq ( uploadId ) + ", server=" + jq ( correctedState . uploadId ) ) ; } if ( correctedState . offset == uploadOffset ) { throw new BadResponseException ( requestId , "Corrected offset is same as given: " + uploadOffset ) ; } if ( correctedState . offset < uploadOffset ) { throw new BadResponseException ( requestId , "we were at offset " + uploadOffset + ", server said " + correctedState . offset ) ; } if ( correctedState . offset > expectedOffset ) { throw new BadResponseException ( requestId , "we were at offset " + uploadOffset + ", server said " + correctedState . offset ) ; } assert correctedState . offset != expectedOffset ; return correctedState . offset ; } if ( response . getStatusCode ( ) != 200 ) throw DbxRequestUtil . unexpectedStatus ( response ) ; ChunkedUploadState returnedState = chunkedUploadParse200 ( response ) ; if ( returnedState . offset != expectedOffset ) { throw new BadResponseException ( requestId , "Expected offset " + expectedOffset + " bytes, but returned offset is " + returnedState . offset ) ; } return - 1 ; } finally { IOUtil . closeInput ( response . getBody ( ) ) ; } }
Append a chunk of data to a chunked upload session .
26,474
public DbxEntry . File getThumbnail ( DbxThumbnailSize sizeBound , DbxThumbnailFormat format , String path , String rev , OutputStream target ) throws DbxException , IOException { if ( target == null ) throw new IllegalArgumentException ( "'target' can't be null" ) ; Downloader downloader = startGetThumbnail ( sizeBound , format , path , rev ) ; if ( downloader == null ) return null ; return downloader . copyBodyAndClose ( target ) ; }
Downloads a thumbnail for the image file at the given path in Dropbox .
26,475
public DbxEntry . File restoreFile ( String path , String rev ) throws DbxException { DbxPathV1 . checkArgNonRoot ( "path" , path ) ; if ( rev == null ) throw new IllegalArgumentException ( "'rev' can't be null" ) ; if ( rev . length ( ) == 0 ) throw new IllegalArgumentException ( "'rev' can't be empty" ) ; String apiPath = "1/restore/auto" + path ; String [ ] params = { "rev" , rev , } ; return doGet ( host . getApi ( ) , apiPath , params , null , new DbxRequestUtil . ResponseHandler < DbxEntry . File > ( ) { public DbxEntry . File handle ( HttpRequestor . Response response ) throws DbxException { if ( response . getStatusCode ( ) == 404 ) return null ; if ( response . getStatusCode ( ) != 200 ) throw DbxRequestUtil . unexpectedStatus ( response ) ; return DbxRequestUtil . readJsonFromResponse ( DbxEntry . File . Reader , response ) ; } } ) ; }
Takes a copy of the file at the given revision and saves it over the current latest copy . This will create a new revision but the file contents will match the revision you specified .
26,476
public List < DbxEntry > searchFileAndFolderNames ( String basePath , String query ) throws DbxException { DbxPathV1 . checkArg ( "basePath" , basePath ) ; if ( query == null ) throw new IllegalArgumentException ( "'query' can't be null" ) ; if ( query . length ( ) == 0 ) throw new IllegalArgumentException ( "'query' can't be empty" ) ; String apiPath = "1/search/auto" + basePath ; String [ ] params = { "query" , query } ; return doPost ( host . getApi ( ) , apiPath , params , null , new DbxRequestUtil . ResponseHandler < List < DbxEntry > > ( ) { public List < DbxEntry > handle ( HttpRequestor . Response response ) throws DbxException { if ( response . getStatusCode ( ) != 200 ) throw DbxRequestUtil . unexpectedStatus ( response ) ; return DbxRequestUtil . readJsonFromResponse ( JsonArrayReader . mk ( DbxEntry . Reader ) , response ) ; } } ) ; }
Returns metadata for all files and folders whose name matches the query string .
26,477
public String createShareableUrl ( String path ) throws DbxException { DbxPathV1 . checkArg ( "path" , path ) ; String apiPath = "1/shares/auto" + path ; String [ ] params = { "short_url" , "false" } ; return doPost ( host . getApi ( ) , apiPath , params , null , new DbxRequestUtil . ResponseHandler < String > ( ) { public String handle ( HttpRequestor . Response response ) throws DbxException { if ( response . getStatusCode ( ) == 404 ) return null ; if ( response . getStatusCode ( ) != 200 ) throw DbxRequestUtil . unexpectedStatus ( response ) ; DbxUrlWithExpiration uwe = DbxRequestUtil . readJsonFromResponse ( DbxUrlWithExpiration . Reader , response ) ; return uwe . url ; } } ) ; }
Creates and returns a publicly - shareable URL to a file or folder s preview page . This URL can be used without authentication . The preview page may contain a thumbnail or some other preview of the file along with a link to download the actual filel .
26,478
public DbxUrlWithExpiration createTemporaryDirectUrl ( String path ) throws DbxException { DbxPathV1 . checkArgNonRoot ( "path" , path ) ; String apiPath = "1/media/auto" + path ; return doPost ( host . getApi ( ) , apiPath , null , null , new DbxRequestUtil . ResponseHandler < DbxUrlWithExpiration > ( ) { public DbxUrlWithExpiration handle ( HttpRequestor . Response response ) throws DbxException { if ( response . getStatusCode ( ) == 404 ) return null ; if ( response . getStatusCode ( ) != 200 ) throw DbxRequestUtil . unexpectedStatus ( response ) ; return DbxRequestUtil . readJsonFromResponse ( DbxUrlWithExpiration . Reader , response ) ; } } ) ; }
Creates and returns a publicly - shareable URL to a file s contents . This URL can be used without authentication . This link will stop working after a few hours .
26,479
public String createCopyRef ( String path ) throws DbxException { DbxPathV1 . checkArgNonRoot ( "path" , path ) ; String apiPath = "1/copy_ref/auto" + path ; return doPost ( host . getApi ( ) , apiPath , null , null , new DbxRequestUtil . ResponseHandler < String > ( ) { public String handle ( HttpRequestor . Response response ) throws DbxException { if ( response . getStatusCode ( ) == 404 ) return null ; if ( response . getStatusCode ( ) != 200 ) throw DbxRequestUtil . unexpectedStatus ( response ) ; CopyRef copyRef = DbxRequestUtil . readJsonFromResponse ( CopyRef . Reader , response ) ; return copyRef . id ; } } ) ; }
Creates and returns a copy ref to a file . A copy ref can be used to copy a file across different Dropbox accounts without downloading and re - uploading .
26,480
public DbxEntry . Folder createFolder ( String path ) throws DbxException { DbxPathV1 . checkArgNonRoot ( "path" , path ) ; String [ ] params = { "root" , "auto" , "path" , path , } ; return doPost ( host . getApi ( ) , "1/fileops/create_folder" , params , null , new DbxRequestUtil . ResponseHandler < DbxEntry . Folder > ( ) { public DbxEntry . Folder handle ( HttpRequestor . Response response ) throws DbxException { if ( response . getStatusCode ( ) == 403 ) return null ; if ( response . getStatusCode ( ) != 200 ) throw DbxRequestUtil . unexpectedStatus ( response ) ; return DbxRequestUtil . readJsonFromResponse ( DbxEntry . Folder . Reader , response ) ; } } ) ; }
Create a new folder in Dropbox .
26,481
public void delete ( String path ) throws DbxException { DbxPathV1 . checkArgNonRoot ( "path" , path ) ; String [ ] params = { "root" , "auto" , "path" , path , } ; doPost ( host . getApi ( ) , "1/fileops/delete" , params , null , new DbxRequestUtil . ResponseHandler < Void > ( ) { public Void handle ( HttpRequestor . Response response ) throws DbxException { if ( response . getStatusCode ( ) != 200 ) throw DbxRequestUtil . unexpectedStatus ( response ) ; return null ; } } ) ; }
Delete a file or folder from Dropbox .
26,482
private < T > T doGet ( String host , String path , String [ ] params , ArrayList < HttpRequestor . Header > headers , DbxRequestUtil . ResponseHandler < T > handler ) throws DbxException { return DbxRequestUtil . doGet ( requestConfig , accessToken , USER_AGENT_ID , host , path , params , headers , handler ) ; }
Convenience function that calls RequestUtil . doGet with the first two parameters filled in .
26,483
public R finish ( ) throws X , DbxException { assertOpenAndUnfinished ( ) ; HttpRequestor . Response response = null ; try { response = httpUploader . finish ( ) ; try { if ( response . getStatusCode ( ) == 200 ) { return responseSerializer . deserialize ( response . getBody ( ) ) ; } else if ( response . getStatusCode ( ) == 409 ) { DbxWrappedException wrapped = DbxWrappedException . fromResponse ( errorSerializer , response , this . userId ) ; throw newException ( wrapped ) ; } else { throw DbxRequestUtil . unexpectedStatus ( response ) ; } } catch ( JsonProcessingException ex ) { String requestId = DbxRequestUtil . getRequestId ( response ) ; throw new BadResponseException ( requestId , "Bad JSON in response: " + ex , ex ) ; } } catch ( IOException ex ) { throw new NetworkIOException ( ex ) ; } finally { if ( response != null ) { IOUtil . closeQuietly ( response . getBody ( ) ) ; } finished = true ; } }
Completes the request and returns response from the server .
26,484
private static void uploadFile ( DbxClientV2 dbxClient , File localFile , String dropboxPath ) { try ( InputStream in = new FileInputStream ( localFile ) ) { ProgressListener progressListener = l -> printProgress ( l , localFile . length ( ) ) ; FileMetadata metadata = dbxClient . files ( ) . uploadBuilder ( dropboxPath ) . withMode ( WriteMode . ADD ) . withClientModified ( new Date ( localFile . lastModified ( ) ) ) . uploadAndFinish ( in , progressListener ) ; System . out . println ( metadata . toStringMultiline ( ) ) ; } catch ( UploadErrorException ex ) { System . err . println ( "Error uploading to Dropbox: " + ex . getMessage ( ) ) ; System . exit ( 1 ) ; } catch ( DbxException ex ) { System . err . println ( "Error uploading to Dropbox: " + ex . getMessage ( ) ) ; System . exit ( 1 ) ; } catch ( IOException ex ) { System . err . println ( "Error reading from file \"" + localFile + "\": " + ex . getMessage ( ) ) ; System . exit ( 1 ) ; } }
Uploads a file in a single request . This approach is preferred for small files since it eliminates unnecessary round - trips to the servers .
26,485
public void doBrowse ( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { if ( ! common . checkGet ( request , response ) ) return ; User user = common . getLoggedInUser ( request ) ; if ( user == null ) { common . pageSoftError ( response , "Can't do /browse. Nobody is logged in." ) ; return ; } DbxClientV2 dbxClient = requireDbxClient ( request , response , user ) ; if ( dbxClient == null ) return ; String path = request . getParameter ( "path" ) ; if ( path == null || path . length ( ) == 0 ) { renderFolder ( response , user , dbxClient , "" ) ; } else { String pathError = DbxPathV2 . findError ( path ) ; if ( pathError != null ) { response . sendError ( 400 , "Invalid path: " + jq ( path ) + ": " + pathError ) ; return ; } Metadata metadata ; try { metadata = dbxClient . files ( ) . getMetadata ( path ) ; } catch ( GetMetadataErrorException ex ) { if ( ex . errorValue . isPath ( ) ) { LookupError le = ex . errorValue . getPathValue ( ) ; if ( le . isNotFound ( ) ) { response . sendError ( 400 , "Path doesn't exist on Dropbox: " + jq ( path ) ) ; return ; } } common . handleException ( response , ex , "getMetadata(" + jq ( path ) + ")" ) ; return ; } catch ( DbxException ex ) { common . handleDbxException ( response , user , ex , "getMetadata(" + jq ( path ) + ")" ) ; return ; } path = DbxPathV2 . getParent ( path ) + "/" + metadata . getName ( ) ; if ( metadata instanceof FolderMetadata ) { renderFolder ( response , user , dbxClient , path ) ; } else { renderFile ( response , path , ( FileMetadata ) metadata ) ; } } }
the contents of your files and folders and display them to you .
26,486
public String createOAuth2AccessToken ( DbxOAuth1AccessToken token ) throws DbxException { if ( token == null ) throw new IllegalArgumentException ( "'token' can't be null" ) ; return DbxRequestUtil . doPostNoAuth ( requestConfig , DbxClientV1 . USER_AGENT_ID , appInfo . getHost ( ) . getApi ( ) , "1/oauth2/token_from_oauth1" , null , getHeaders ( token ) , new DbxRequestUtil . ResponseHandler < String > ( ) { public String handle ( HttpRequestor . Response response ) throws DbxException { if ( response . getStatusCode ( ) != 200 ) throw DbxRequestUtil . unexpectedStatus ( response ) ; return DbxRequestUtil . readJsonFromResponse ( ResponseReader , response ) ; } } ) ; }
Given an existing active OAuth 1 access token make a Dropbox API call to get a new OAuth 2 access token that represents the same user and app .
26,487
public void disableOAuth1AccessToken ( DbxOAuth1AccessToken token ) throws DbxException { if ( token == null ) throw new IllegalArgumentException ( "'token' can't be null" ) ; DbxRequestUtil . doPostNoAuth ( requestConfig , DbxClientV1 . USER_AGENT_ID , appInfo . getHost ( ) . getApi ( ) , "1/disable_access_token" , null , getHeaders ( token ) , new DbxRequestUtil . ResponseHandler < Void > ( ) { public Void handle ( HttpRequestor . Response response ) throws DbxException { if ( response . getStatusCode ( ) != 200 ) throw DbxRequestUtil . unexpectedStatus ( response ) ; return null ; } } ) ; }
Tell the Dropbox API server to disable an OAuth 1 access token .
26,488
public String start ( ) { DbxWebAuth . Request request = DbxWebAuth . newRequestBuilder ( ) . withNoRedirect ( ) . build ( ) ; return auth . authorize ( request ) ; }
Start authorization . Returns a authorization URL on the Dropbox website that gives the lets the user grant your app access to their Dropbox account .
26,489
public static void longpoll ( DbxAuthInfo auth , String path ) throws IOException { long longpollTimeoutSecs = TimeUnit . MINUTES . toSeconds ( 2 ) ; StandardHttpRequestor . Config config = StandardHttpRequestor . Config . DEFAULT_INSTANCE ; StandardHttpRequestor . Config longpollConfig = config . copy ( ) . withReadTimeout ( 5 , TimeUnit . MINUTES ) . build ( ) ; DbxClientV2 dbxClient = createClient ( auth , config ) ; DbxClientV2 dbxLongpollClient = createClient ( auth , longpollConfig ) ; try { String cursor = getLatestCursor ( dbxClient , path ) ; System . out . println ( "Longpolling for changes... press CTRL-C to exit." ) ; while ( true ) { ListFolderLongpollResult result = dbxLongpollClient . files ( ) . listFolderLongpoll ( cursor , longpollTimeoutSecs ) ; if ( result . getChanges ( ) ) { cursor = printChanges ( dbxClient , cursor ) ; } Long backoff = result . getBackoff ( ) ; if ( backoff != null ) { try { System . out . printf ( "backing off for %d secs...\n" , backoff . longValue ( ) ) ; Thread . sleep ( TimeUnit . SECONDS . toMillis ( backoff ) ) ; } catch ( InterruptedException ex ) { System . exit ( 0 ) ; } } } } catch ( DbxApiException ex ) { String message = ex . getUserMessage ( ) != null ? ex . getUserMessage ( ) . getText ( ) : ex . getMessage ( ) ; System . err . println ( "Error making API call: " + message ) ; System . exit ( 1 ) ; } catch ( NetworkIOException ex ) { System . err . println ( "Error making API call: " + ex . getMessage ( ) ) ; if ( ex . getCause ( ) instanceof SocketTimeoutException ) { System . err . println ( "Consider increasing socket read timeout or decreasing longpoll timeout." ) ; } System . exit ( 1 ) ; } catch ( DbxException ex ) { System . err . println ( "Error making API call: " + ex . getMessage ( ) ) ; System . exit ( 1 ) ; } }
Will perform longpoll request for changes in the user s Dropbox account and display those changes . This is more efficient that periodic polling the endpoint .
26,490
private static DbxClientV2 createClient ( DbxAuthInfo auth , StandardHttpRequestor . Config config ) { String clientUserAgentId = "examples-longpoll" ; StandardHttpRequestor requestor = new StandardHttpRequestor ( config ) ; DbxRequestConfig requestConfig = DbxRequestConfig . newBuilder ( clientUserAgentId ) . withHttpRequestor ( requestor ) . build ( ) ; return new DbxClientV2 ( requestConfig , auth . getAccessToken ( ) , auth . getHost ( ) ) ; }
Create a new Dropbox client using the given authentication information and HTTP client config .
26,491
private static String printChanges ( DbxClientV2 client , String cursor ) throws DbxApiException , DbxException { while ( true ) { ListFolderResult result = client . files ( ) . listFolderContinue ( cursor ) ; for ( Metadata metadata : result . getEntries ( ) ) { String type ; String details ; if ( metadata instanceof FileMetadata ) { FileMetadata fileMetadata = ( FileMetadata ) metadata ; type = "file" ; details = "(rev=" + fileMetadata . getRev ( ) + ")" ; } else if ( metadata instanceof FolderMetadata ) { FolderMetadata folderMetadata = ( FolderMetadata ) metadata ; type = "folder" ; details = folderMetadata . getSharingInfo ( ) != null ? "(shared)" : "" ; } else if ( metadata instanceof DeletedMetadata ) { type = "deleted" ; details = "" ; } else { throw new IllegalStateException ( "Unrecognized metadata type: " + metadata . getClass ( ) ) ; } System . out . printf ( "\t%10s %24s \"%s\"\n" , type , details , metadata . getPathLower ( ) ) ; } cursor = result . getCursor ( ) ; if ( ! result . getHasMore ( ) ) { break ; } } return cursor ; }
Prints changes made to a folder in Dropbox since the given cursor was retrieved .
26,492
private static < T > T executeRetriable ( int maxRetries , RetriableExecution < T > execution ) throws DbxWrappedException , DbxException { if ( maxRetries == 0 ) { return execution . execute ( ) ; } int retries = 0 ; while ( true ) { try { return execution . execute ( ) ; } catch ( RetryException ex ) { if ( retries < maxRetries ) { ++ retries ; sleepQuietlyWithJitter ( ex . getBackoffMillis ( ) ) ; } else { throw ex ; } } } }
Retries the execution at most a maximum number of times .
26,493
public void doLogin ( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { if ( ! common . checkPost ( request , response ) ) return ; String username = request . getParameter ( "username" ) ; if ( username == null ) { response . sendError ( 400 , "Missing field \"username\"." ) ; return ; } String usernameError = checkUsername ( username ) ; if ( usernameError != null ) { response . sendError ( 400 , "Invalid username: " + usernameError ) ; return ; } User user ; synchronized ( common . userDb ) { user = common . userDb . get ( username ) ; if ( user == null ) { user = new User ( ) ; user . username = username ; user . dropboxAccessToken = null ; common . userDb . put ( user . username , user ) ; common . saveUserDb ( ) ; } } request . getSession ( ) . setAttribute ( "logged-in-username" , user . username ) ; response . sendRedirect ( "/" ) ; }
Login form handler .
26,494
private static String checkUsername ( String username ) { if ( username . length ( ) < 3 ) { return "too short (minimum: 3 characters)" ; } else if ( username . length ( ) > 64 ) { return "too long (maximum: 64 characters)" ; } for ( int i = 0 ; i < username . length ( ) ; i ++ ) { char c = username . charAt ( i ) ; if ( c >= 'A' && c <= 'Z' ) continue ; if ( c >= 'a' && c <= 'z' ) continue ; if ( c >= '0' && c <= '9' ) continue ; if ( c == '_' ) continue ; return "invalid character at position " + ( i + 1 ) + ": " + jq ( "" + c ) ; } return null ; }
Returns null if the username is ok .
26,495
public void doLogout ( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { if ( ! common . checkPost ( request , response ) ) return ; request . getSession ( ) . removeAttribute ( "logged-in-username" ) ; response . sendRedirect ( "/" ) ; }
Logout form handler .
26,496
public static HttpRequestor . Response startGet ( DbxRequestConfig requestConfig , String accessToken , String sdkUserAgentIdentifier , String host , String path , String [ ] params , List < HttpRequestor . Header > headers ) throws NetworkIOException { headers = copyHeaders ( headers ) ; headers = addUserAgentHeader ( headers , requestConfig , sdkUserAgentIdentifier ) ; headers = addAuthHeader ( headers , accessToken ) ; String url = buildUrlWithParams ( requestConfig . getUserLocale ( ) , host , path , params ) ; try { return requestConfig . getHttpRequestor ( ) . doGet ( url , headers ) ; } catch ( IOException ex ) { throw new NetworkIOException ( ex ) ; } }
Convenience function for making HTTP GET requests .
26,497
public static HttpRequestor . Response startPostNoAuth ( DbxRequestConfig requestConfig , String sdkUserAgentIdentifier , String host , String path , String [ ] params , List < HttpRequestor . Header > headers ) throws NetworkIOException { byte [ ] encodedParams = StringUtil . stringToUtf8 ( encodeUrlParams ( requestConfig . getUserLocale ( ) , params ) ) ; headers = copyHeaders ( headers ) ; headers . add ( new HttpRequestor . Header ( "Content-Type" , "application/x-www-form-urlencoded; charset=utf-8" ) ) ; return startPostRaw ( requestConfig , sdkUserAgentIdentifier , host , path , encodedParams , headers ) ; }
Convenience function for making HTTP POST requests .
26,498
public static String javaQuotedLiteral ( String value ) { StringBuilder b = new StringBuilder ( value . length ( ) * 2 ) ; b . append ( '"' ) ; for ( int i = 0 ; i < value . length ( ) ; i ++ ) { char c = value . charAt ( i ) ; switch ( c ) { case '"' : b . append ( "\\\"" ) ; break ; case '\\' : b . append ( "\\\\" ) ; break ; case '\n' : b . append ( "\\n" ) ; break ; case '\r' : b . append ( "\\t" ) ; break ; case '\t' : b . append ( "\\r" ) ; break ; case '\0' : b . append ( "\\000" ) ; break ; default : if ( c >= 0x20 && c <= 0x7e ) { b . append ( c ) ; } else { int h1 = ( c >> 12 ) & 0xf ; int h2 = ( c >> 8 ) & 0xf ; int h3 = ( c >> 4 ) & 0xf ; int h4 = c & 0xf ; b . append ( "\\u" ) ; b . append ( hexDigit ( h1 ) ) ; b . append ( hexDigit ( h2 ) ) ; b . append ( hexDigit ( h3 ) ) ; b . append ( hexDigit ( h4 ) ) ; } break ; } } b . append ( '"' ) ; return b . toString ( ) ; }
Given a string returns the representation of that string as a Java string literal .
26,499
public static String binaryToHex ( byte [ ] data , int offset , int length ) { assert offset < data . length && offset >= 0 : offset + ", " + data . length ; int end = offset + length ; assert end <= data . length && end >= 0 : offset + ", " + length + ", " + data . length ; char [ ] chars = new char [ length * 2 ] ; int j = 0 ; for ( int i = offset ; i < end ; i ++ ) { int b = data [ i ] ; chars [ j ++ ] = hexDigit ( b >>> 4 & 0xF ) ; chars [ j ++ ] = hexDigit ( b & 0xF ) ; } return new String ( chars ) ; }
Convert a string of binary bytes to the equivalent hexadecimal string . The resulting String will have two characters for every byte in the input .