@Override
  public int compareTo(Timespan timespan)
  {
    if(timespan.getTimeUnit() == getTimeUnit())
      return LangUtils.compare(getDuration(), timespan.getDuration());
    else
      return LangUtils.compare(getDurationInMilliseconds(), timespan.getDurationInMilliseconds());
  }

@ Override public int compareTo ( Timespan timespan ) { if ( timespan . getTimeUnit ( ) == getTimeUnit ( ) ) return LangUtils . compare ( getDuration ( ) , timespan . getDuration ( ) ) ; else return LangUtils . compare ( getDurationInMilliseconds ( ) , timespan . getDurationInMilliseconds ( ) ) ; }

Compares 2 timespan. Based on duration in milliseconds.

@param timespan
@return 0 if same duration in milliseconds,

Compares 2 timespan . Based on duration in milliseconds .


public MemorySize truncate(SizeUnit sizeUnit)
  {
    if (getSizeUnit() == sizeUnit)
      return this;

    long sizeInBytes = getSizeInBytes();

    if (sizeInBytes >= sizeUnit.getBytesCount())
    {
      return new MemorySize(sizeInBytes / sizeUnit.getBytesCount(), sizeUnit);
    }
    else
    {
      return ZERO_SIZES.get(sizeUnit);
    }
  }

public MemorySize truncate ( SizeUnit sizeUnit ) { if ( getSizeUnit ( ) == sizeUnit ) return this ; long sizeInBytes = getSizeInBytes ( ) ; if ( sizeInBytes >= sizeUnit . getBytesCount ( ) ) { return new MemorySize ( sizeInBytes / sizeUnit . getBytesCount ( ) , sizeUnit ) ; } else { return ZERO_SIZES . get ( sizeUnit ) ; } }

Return a new instance of MemorySize that is truncated to the given unit

@param sizeUnit
@return a new instance of MemorySize that is truncated to the given unit


public MemorySize add(MemorySize other)
  {
    if(other == null)
      throw new NullPointerException();

    if(getSizeUnit() == other.getSizeUnit())
      return new MemorySize(getSize() + other.getSize(), getSizeUnit());

    return new MemorySize(getSizeInBytes() + other.getSizeInBytes(),
                        SizeUnit.BYTE);
  }

public MemorySize add ( MemorySize other ) { if ( other == null ) throw new NullPointerException ( ) ; if ( getSizeUnit ( ) == other . getSizeUnit ( ) ) return new MemorySize ( getSize ( ) + other . getSize ( ) , getSizeUnit ( ) ) ; return new MemorySize ( getSizeInBytes ( ) + other . getSizeInBytes ( ) , SizeUnit . BYTE ) ; }

Return a new instance of MemorySize that adds up the size of this object
with that of the 'other'

@param other
@return a new instance of MemorySize that adds up the size of this object
with the that of the 'other'

Return a new instance of MemorySize that adds up the size of this object with that of the other


@Override
  public int compareTo(MemorySize memorySize)
  {
    // according to javadoc for interface Comparable<T>, a NullPointerException
    // should be thrown when the object to be compared with is null
    // http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Comparable.html#compareTo(T)
    if (memorySize == null)
      throw new NullPointerException();

    if (getSizeUnit() == memorySize.getSizeUnit())
      return LangUtils.compare(getSize(), memorySize.getSize());

    return LangUtils.compare(getSizeInBytes(), memorySize.getSizeInBytes());
  }

Compare with another instance of MemorySize based on size in bytes

@see java.lang.Comparable#compareTo(java.lang.Object)


public static MemorySize create(MemorySize...memorySizes)
  {
    if(memorySizes == null)
      return null;

    if(memorySizes.length == 0)
      return ZERO_BYTES;

    MemorySize res = memorySizes[0];

    for(int i = 1; i < memorySizes.length; i++)
    {
      MemorySize memorySize = memorySizes[i];
      if(memorySize != null)
        res = res.add(memorySize);
    }

    return res;
  }

public static MemorySize create ( MemorySize ... memorySizes ) { if ( memorySizes == null ) return null ; if ( memorySizes . length == 0 ) return ZERO_BYTES ; MemorySize res = memorySizes [ 0 ] ; for ( int i = 1 ; i < memorySizes . length ; i ++ ) { MemorySize memorySize = memorySizes [ i ] ; if ( memorySize != null ) res = res . add ( memorySize ) ; } return res ; }

Create a new instance of MemorySize by adding up the given
array of memorySizes

@param memorySizes
@return a new instance of MemorySize


public static <V> Future<V> execute(Callable<V> callable)
  {
    FutureTask<V> futureTask = new FutureTask<V>(callable);

    new Thread(futureTask).start();

    return futureTask;
  }

public static < V > Future < V > execute ( Callable < V > callable ) { FutureTask < V > futureTask = new FutureTask < V > ( callable ) ; new Thread ( futureTask ) . start ( ) ; return futureTask ; }

Executes the callable in a separate thread and return the future to get the result. Note
that this implementation is not efficient and should be used very carefully.

@param callable
@return the future to get the result.

Executes the callable in a separate thread and return the future to get the result . Note that this implementation is not efficient and should be used very carefully .


public void addMarker(T marker) {

        final MarkerOptions markerOptions = new MarkerOptions();
        marker.setMarkerManager(this);
        marker.prepareMarker(markerOptions);

        markerCache.put(marker, googleMap.addMarker(markerOptions));

        marker.onAdd();
    }

public void addMarker ( T marker ) { final MarkerOptions markerOptions = new MarkerOptions ( ) ; marker . setMarkerManager ( this ) ; marker . prepareMarker ( markerOptions ) ; markerCache . put ( marker , googleMap . addMarker ( markerOptions ) ) ; marker . onAdd ( ) ; }

Add a marker to the map.

@param marker marker to add


public void removeMarker(T marker) {

        final Marker realMarker = markerCache.get(marker);

        if (realMarker != null) {
            realMarker.remove();
        }

        markerCache.remove(marker);
    }

public void removeMarker ( T marker ) { final Marker realMarker = markerCache . get ( marker ) ; if ( realMarker != null ) { realMarker . remove ( ) ; } markerCache . remove ( marker ) ; }

Remove a marker from the map.

@param marker marker to remove


public static BitmapDescriptor fromView(View view) {

        // TODO: Single views have trouble with measure.
        final int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(spec, spec);

        final int width = view.getMeasuredWidth();
        final int height = view.getMeasuredHeight();

        view.layout(0, 0, width, height);

        final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);

        view.draw(canvas);

        return BitmapDescriptorFactory.fromBitmap(bitmap);
    }

Returns a bitmap icon showing a screenshot of the view passed in.

@param view View to convert
@return Bitmap icon of view

Returns a bitmap icon showing a screenshot of the view passed in .


private final static Func1<WatchEvent<?>, Boolean> onlyRelatedTo(final File file) {
        return new Func1<WatchEvent<?>, Boolean>() {

            @Override
            public Boolean call(WatchEvent<?> event) {

                final boolean ok;
                if (file.isDirectory())
                    ok = true;
                else if (StandardWatchEventKinds.OVERFLOW.equals(event.kind()))
                    ok = true;
                else {
                    Object context = event.context();
                    if (context != null && context instanceof Path) {
                        Path p = (Path) context;
                        Path basePath = getBasePath(file);
                        File pFile = new File(basePath.toFile(), p.toString());
                        ok = pFile.getAbsolutePath().equals(file.getAbsolutePath());
                    } else
                        ok = false;
                }
                return ok;
            }
        };
    }

private final static Func1 < WatchEvent < ? > , Boolean > onlyRelatedTo ( final File file ) { return new Func1 < WatchEvent < ? > , Boolean > ( ) { @ Override public Boolean call ( WatchEvent < ? > event ) { final boolean ok ; if ( file . isDirectory ( ) ) ok = true ; else if ( StandardWatchEventKinds . OVERFLOW . equals ( event . kind ( ) ) ) ok = true ; else { Object context = event . context ( ) ; if ( context != null && context instanceof Path ) { Path p = ( Path ) context ; Path basePath = getBasePath ( file ) ; File pFile = new File ( basePath . toFile ( ) , p . toString ( ) ) ; ok = pFile . getAbsolutePath ( ) . equals ( file . getAbsolutePath ( ) ) ; } else ok = false ; } return ok ; } } ; }

Returns true if and only if the path corresponding to a WatchEvent
represents the given file. This will be the case for Create, Modify,
Delete events.

@param file
the file to restrict events to
@return predicate

Returns true if and only if the path corresponding to a WatchEvent represents the given file . This will be the case for Create Modify Delete events .


private static boolean emitEvents(WatchService watchService,
            Subscriber<? super WatchEvent<?>> subscriber, long pollDurationMs,
            long pollIntervalMs) {
        // get the first event
        WatchKey key = nextKey(watchService, subscriber, pollDurationMs);

        if (key != null) {
            if (subscriber.isUnsubscribed())
                return false;
            // we have a polled event, now we traverse it and
            // receive all the states from it
            for (WatchEvent<?> event : key.pollEvents()) {
                if (subscriber.isUnsubscribed())
                    return false;
                else
                    subscriber.onNext(event);
            }

            boolean valid = key.reset();
            if (!valid && !subscriber.isUnsubscribed()) {
                subscriber.onCompleted();
                return false;
            } else if (!valid)
                return false;
        }
        return true;
    }

returns true if and only there may be more events


private StateListDrawable getSelectorDrawable() {
        StateListDrawable d = null;

        try {
            d = new StateListDrawable();
            ShapeDrawable selectedDrawable = new ShapeDrawable(new OvalShape());
            selectedDrawable.getPaint().setColor(mItemSelectedColor);
            selectedDrawable.setIntrinsicHeight(mItemRadius * 2);
            selectedDrawable.setIntrinsicWidth(mItemRadius * 2);
            ShapeDrawable unselectedDrawable = new ShapeDrawable(new OvalShape());
            unselectedDrawable.getPaint().setColor(mItemUnselectedColor);
            unselectedDrawable.setIntrinsicHeight(mItemRadius * 2);
            unselectedDrawable.setIntrinsicWidth(mItemRadius * 2);

            d.addState(new int[]{android.R.attr.state_checked}, selectedDrawable);
            d.addState(new int[]{}, unselectedDrawable);
        } catch(Exception e) {
            Log.e(TAG, getMessageFor(e));
        }

        return d;
    }

private StateListDrawable getSelectorDrawable ( ) { StateListDrawable d = null ; try { d = new StateListDrawable ( ) ; ShapeDrawable selectedDrawable = new ShapeDrawable ( new OvalShape ( ) ) ; selectedDrawable . getPaint ( ) . setColor ( mItemSelectedColor ) ; selectedDrawable . setIntrinsicHeight ( mItemRadius * 2 ) ; selectedDrawable . setIntrinsicWidth ( mItemRadius * 2 ) ; ShapeDrawable unselectedDrawable = new ShapeDrawable ( new OvalShape ( ) ) ; unselectedDrawable . getPaint ( ) . setColor ( mItemUnselectedColor ) ; unselectedDrawable . setIntrinsicHeight ( mItemRadius * 2 ) ; unselectedDrawable . setIntrinsicWidth ( mItemRadius * 2 ) ; d . addState ( new int [ ] { android . R . attr . state_checked } , selectedDrawable ) ; d . addState ( new int [ ] { } , unselectedDrawable ) ; } catch ( Exception e ) { Log . e ( TAG , getMessageFor ( e ) ) ; } return d ; }

Create a StateListDrawable for the pager indicator

@return a proper StateListDrawable


public void initWithViewPager(ViewPager viewPager) throws IllegalStateException {
        if ( viewPager == null ) return;

        if ( viewPager.getAdapter() == null ) throw new IllegalStateException("ViewPager has no adapter set.");

        try {
            mViewPager = viewPager;

            mViewPager.addOnPageChangeListener(mOnPageChangeListener);

            addViews();
        } catch(Exception e) {
            Log.e(TAG, getMessageFor(e));
        }
    }

public
void
initWithViewPager
(
ViewPager
viewPager
)
throws
IllegalStateException
{
if
(
viewPager
==
)
return
;
if
(
viewPager
.
getAdapter
(
)
==
)
throw
new
IllegalStateException
(
"ViewPager has no adapter set."
)
;
try
{
mViewPager
=
viewPager
;
mViewPager
.
addOnPageChangeListener
(
mOnPageChangeListener
)
;
addViews
(
)
;
}
catch
(
Exception
e
)
{
Log
.
e
(
TAG
,
getMessageFor
(
e
)
)
;
}
}

Initialize ViewPagerIndicator with a properly set up ViewPager
@param viewPager an instance of android.support.v4.view.ViewPager
@throws IllegalStateException if no adapter has been provided to the viewPager


private void addViews() {
        try {
            if ( mViewPager == null || mViewPager.getAdapter() == null || mViewPager.getAdapter().getCount() == 0 ) return;
            removeAllViews();
            AppCompatRadioButton firstItem = new AppCompatRadioButton(getContext());
            firstItem.setText("");
            firstItem.setButtonDrawable(mButtonDrawable.getConstantState().newDrawable());
            ViewPagerIndicator.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            firstItem.setLayoutParams(params);
            firstItem.setClickable(false);
            addView(firstItem);
            for ( int i=1; i<mViewPager.getAdapter().getCount(); i++ ) {
                AppCompatRadioButton item = new AppCompatRadioButton(getContext());
                item.setText("");
                item.setButtonDrawable(mButtonDrawable.getConstantState().newDrawable());
                params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                params.setMargins(mItemDividerWidth, 0, 0, 0);
                item.setLayoutParams(params);
                item.setClickable(false);
                addView(item);
            }
            check(firstItem.getId());
        } catch(Exception e) {
            Log.e(TAG, getMessageFor(e));
        }
    }

private void addViews ( ) { try { if ( mViewPager == null || mViewPager . getAdapter ( ) == null || mViewPager . getAdapter ( ) . getCount ( ) == 0 ) return ; removeAllViews ( ) ; AppCompatRadioButton firstItem = new AppCompatRadioButton ( getContext ( ) ) ; firstItem . setText ( "" ) ; firstItem . setButtonDrawable ( mButtonDrawable . getConstantState ( ) . newDrawable ( ) ) ; ViewPagerIndicator . LayoutParams params = new LayoutParams ( LayoutParams . WRAP_CONTENT , LayoutParams . WRAP_CONTENT ) ; firstItem . setLayoutParams ( params ) ; firstItem . setClickable ( false ) ; addView ( firstItem ) ; for ( int i = 1 ; i < mViewPager . getAdapter ( ) . getCount ( ) ; i ++ ) { AppCompatRadioButton item = new AppCompatRadioButton ( getContext ( ) ) ; item . setText ( "" ) ; item . setButtonDrawable ( mButtonDrawable . getConstantState ( ) . newDrawable ( ) ) ; params = new LayoutParams ( LayoutParams . WRAP_CONTENT , LayoutParams . WRAP_CONTENT ) ; params . setMargins ( mItemDividerWidth , 0 , 0 , 0 ) ; item . setLayoutParams ( params ) ; item . setClickable ( false ) ; addView ( item ) ; } check ( firstItem . getId ( ) ) ; } catch ( Exception e ) { Log . e ( TAG , getMessageFor ( e ) ) ; } }

Add page indicators based on the attached ViewPager


private String getMessageFor(Exception e) {
        if ( e == null ) return TAG + ": No Message.";

        return e != null && e.getMessage() != null ? e.getMessage() : e.getClass().getName() + ": No Message.";
    }

private
String
getMessageFor
(
Exception
e
)
{
if
(
e
==
)
return
TAG
+
": No Message."
;
return
e
!=
&&
e
.
getMessage
(
)
!=
e
.
getMessage
(
)
:
e
.
getClass
(
)
.
getName
(
)
+
": No Message."
;
}

Always get a message for an exception
@param e an Exception
@return a String describing the Exception


public static void useSequentialIds() {
        if (!sequential) {
            // get string that changes every 10 minutes
            TimeZone tz = TimeZone.getTimeZone("UTC");
            DateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
            df.setTimeZone(tz);
            String date = df.format(new Date()).substring(0, 11);

            // run an md5 hash of the string, no reason this needs to be secure
            byte[] digest;
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                digest = md.digest(date.getBytes("UTF-8"));
            }
            catch (Exception e) {
                throw new RuntimeException("Could not create hash of date for the sequential counter", e);
            }

            // create integer from first 4 bytes of md5 hash
            int x;
            x  = ((int)digest[0] & 0xFF);
            x |= ((int)digest[1] & 0xFF) << 8;
            x |= ((int)digest[2] & 0xFF) << 16;
            x |= ((int)digest[3] & 0xFF) << 24;
            COUNTER.set(x);
        }
        sequential = true;
    }

Toggle UUID generator into sequential mode, so the random segment is in order and increases by one. In
sequential mode, there is presumably a desire that UUIDs generated around the same time should begin with similar
characters, but this is difficult in a distributed environment. The solution is to set the counter value based
on a hash of the UTC date and time up to a 10 minute precision. This means that UUID classes initialized at
similar times should start with similar counter values, but this is not guaranteed. If one of these classes
is generating vastly more UUIDs than others, then these counters can become skewed.

Calling this method more than once without toggling back to variable mode has no effect, so it probably makes
more sense to call this from a static context, like your main method or in a class' static initialization.

Toggle UUID generator into sequential mode so the random segment is in order and increases by one . In sequential mode there is presumably a desire that UUIDs generated around the same time should begin with similar characters but this is difficult in a distributed environment . The solution is to set the counter value based on a hash of the UTC date and time up to a 10 minute precision . This means that UUID classes initialized at similar times should start with similar counter values but this is not guaranteed . If one of these classes is generating vastly more UUIDs than others then these counters can become skewed .


private static int intValue(char x) {
        if (x >= '0' && x <= '9')
            return x - '0';
        if (x >= 'a' && x <= 'f')
            return x - 'a' + 10;
        if (x >= 'A' && x <= 'F')
            return x - 'A' + 10;
        throw new RuntimeException("Error parsing UUID at character: " + x);
    }

private
static
int
intValue
(
char
x
)
{
if
(
x
>=
'
'
&&
x
<=
'
'
)
return
x
'
'
;
if
(
x
>=
'
'
&&
x
<=
'
'
)
return
x
'
'
+
10
;
if
(
x
>=
'
'
&&
x
<=
'
'
)
return
x
'
'
+
10
;
throw
new
RuntimeException
(
"Error parsing UUID at character: "
+
x
)
;
}

This method maps a hex character to its 4-bit representation in an int.
@param x Hex character in the range ('0' - '9', 'a' - 'f', 'A' - 'F').
@return 4-bit number in int representing hex offset from 0.

This method maps a hex character to its 4 - bit representation in an int .


private static byte mapToByte(char a, char b) {
        int ai = intValue(a);
        int bi = intValue(b);
        return (byte) ((ai << 4) | bi);
    }

private static byte mapToByte ( char a , char b ) { int ai = intValue ( a ) ; int bi = intValue ( b ) ; return ( byte ) ( ( ai << 4 ) | bi ) ; }

Map two hex characters to 4-bit numbers and combine them to produce 8-bit number in byte.
@param a First hex character.
@param b Second hex character.
@return Byte representation of given hex characters.

Map two hex characters to 4 - bit numbers and combine them to produce 8 - bit number in byte .


public Date getTimestamp() {
        if (getVersion() != VERSION)
            return null;

        long time;
        time  = ((long)content[10] & 0xFF) << 40;
        time |= ((long)content[11] & 0xFF) << 32;
        time |= ((long)content[12] & 0xFF) << 24;
        time |= ((long)content[13] & 0xFF) << 16;
        time |= ((long)content[14] & 0xFF) << 8;
        time |= ((long)content[15] & 0xFF);
        return new Date(time);
    }

public Date getTimestamp ( ) { if ( getVersion ( ) != VERSION ) return null ; long time ; time = ( ( long ) content [ 10 ] & 0xFF ) << 40 ; time |= ( ( long ) content [ 11 ] & 0xFF ) << 32 ; time |= ( ( long ) content [ 12 ] & 0xFF ) << 24 ; time |= ( ( long ) content [ 13 ] & 0xFF ) << 16 ; time |= ( ( long ) content [ 14 ] & 0xFF ) << 8 ; time |= ( ( long ) content [ 15 ] & 0xFF ) ; return new Date ( time ) ; }

Extract timestamp from raw UUID bytes and return as int. If the UUID is not the default type, then we can't parse
the timestamp out and null is returned.
@return Millisecond UTC timestamp from generation of the UUID, or null for unrecognized format.

Extract timestamp from raw UUID bytes and return as int . If the UUID is not the default type then we can t parse the timestamp out and null is returned .


public byte[] getMacFragment() {
        if (getVersion() != 'b')
            return null;

        byte[] x = new byte[6];

        x[0] = 0;
        x[1] = 0;
        x[2] = (byte) (content[6] & 0xF);
        x[3] = content[7];
        x[4] = content[8];
        x[5] = content[9];

        return x;
    }

public byte [ ] getMacFragment ( ) { if ( getVersion ( ) != ' ' ) return null ; byte [ ] x = new byte [ 6 ] ; x [ 0 ] = 0 ; x [ 1 ] = 0 ; x [ 2 ] = ( byte ) ( content [ 6 ] & 0xF ) ; x [ 3 ] = content [ 7 ] ; x [ 4 ] = content [ 8 ] ; x [ 5 ] = content [ 9 ] ; return x ; }

Extract MAC address fragment from raw UUID bytes, setting missing values to 0, thus the first 2 and a half bytes
will be 0, followed by 3 and a half bytes of the active MAC address when the UUID was generated.
@return Byte array of UUID fragment, or null for unrecognized format.

Extract MAC address fragment from raw UUID bytes setting missing values to 0 thus the first 2 and a half bytes will be 0 followed by 3 and a half bytes of the active MAC address when the UUID was generated .


public void setProperty(String key, String value) {
		if(properties == null) {
			properties = createProperties();
		}

		if(value != null) {
			value = value.trim();
			properties.put(key, value);
		}
		else {
			properties.remove(key);
		}
	}

public void setProperty ( String key , String value ) { if ( properties == null ) { properties = createProperties ( ) ; } if ( value != null ) { value = value . trim ( ) ; properties . put ( key , value ) ; } else { properties . remove ( key ) ; } }

Sets a custom property.  This will override settings in socialize.properties.
@param key
@param value

Sets a custom property . This will override settings in socialize . properties .


@Deprecated
	public void setFacebookUserCredentials(String userId, String token) {
		setProperty(SocializeConfig.FACEBOOK_USER_ID, userId);
		setProperty(SocializeConfig.FACEBOOK_USER_TOKEN, token);
	}

@ Deprecated public void setFacebookUserCredentials ( String userId , String token ) { setProperty ( SocializeConfig . FACEBOOK_USER_ID , userId ) ; setProperty ( SocializeConfig . FACEBOOK_USER_TOKEN , token ) ; }

Sets the FB credentials for the current user if available.
@param userId
@param token
@deprecated No longer used. Any values set here will be ignored.  Use FacebookUtils to link a known user.

Sets the FB credentials for the current user if available .


public void setSocializeCredentials(String consumerKey, String consumerSecret) {
		setProperty(SocializeConfig.SOCIALIZE_CONSUMER_KEY, consumerKey);
		setProperty(SocializeConfig.SOCIALIZE_CONSUMER_SECRET, consumerSecret);
	}

public void setSocializeCredentials ( String consumerKey , String consumerSecret ) { setProperty ( SocializeConfig . SOCIALIZE_CONSUMER_KEY , consumerKey ) ; setProperty ( SocializeConfig . SOCIALIZE_CONSUMER_SECRET , consumerSecret ) ; }

Sets the Socialize credentials for your App.
@param consumerKey Your consumer key, obtained via registration at http://getsocialize.com
@param consumerSecret Your consumer secret, obtained via registration at http://getsocialize.com

Sets the Socialize credentials for your App .


public void merge(Properties other, Set<String> toBeRemoved) {
		if(properties == null) {
			properties = createProperties();
		}

		if(other != null && other.size() > 0) {
			Set<Entry<Object, Object>> entrySet = other.entrySet();
			for (Entry<Object, Object> entry : entrySet) {
				properties.put(entry.getKey(),  entry.getValue());
			}
		}

		if(toBeRemoved != null && toBeRemoved.size() > 0) {
			for (String key : toBeRemoved) {
				properties.remove(key);
			}
			toBeRemoved.clear();
		}
	}

public void merge ( Properties other , Set < String > toBeRemoved ) { if ( properties == null ) { properties = createProperties ( ) ; } if ( other != null && other . size ( ) > 0 ) { Set < Entry < Object , Object > > entrySet = other . entrySet ( ) ; for ( Entry < Object , Object > entry : entrySet ) { properties . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } if ( toBeRemoved != null && toBeRemoved . size ( ) > 0 ) { for ( String key : toBeRemoved ) { properties . remove ( key ) ; } toBeRemoved . clear ( ) ; } }

Merge properties into the config.
@param other


protected void doShare(final Activity context, final Entity entity, final ShareType shareType, final ShareAddListener shareAddListener) {
		final SocializeSession session = getSocialize().getSession();
		shareSystem.addShare(context, session, entity, "", shareType, null, new ShareAddListener() {
			@Override
			public void onError(SocializeException error) {
				if(shareAddListener != null) {
					shareAddListener.onError(error);
				}
			}

			@Override
			public void onCreate(Share share) {
				if(share != null && shareSystem != null) {
					handleNonNetworkShare(context, session, shareType, share, "", null, shareAddListener);
				}
			}
		});
	}

protected void doShare ( final Activity context , final Entity entity , final ShareType shareType , final ShareAddListener shareAddListener ) { final SocializeSession session = getSocialize ( ) . getSession ( ) ; shareSystem . addShare ( context , session , entity , "" , shareType , null , new ShareAddListener ( ) { @ Override public void onError ( SocializeException error ) { if ( shareAddListener != null ) { shareAddListener . onError ( error ) ; } } @ Override public void onCreate ( Share share ) { if ( share != null && shareSystem != null ) { handleNonNetworkShare ( context , session , shareType , share , "" , null , shareAddListener ) ; } } } ) ; }


protected void handleNonNetworkShare(Activity activity, final SocializeSession session, final ShareType shareType, final Share share, String shareText, Location location, final ShareAddListener shareAddListener) {

		SocialNetworkListener snListener = new SocialNetworkListener() {

			@Override
			public void onNetworkError(Activity context, SocialNetwork network, Exception error) {
				if(shareAddListener != null) {
					shareAddListener.onError(SocializeException.wrap(error));
				}
			}

			@Override
			public void onCancel() {
				if(shareAddListener != null) {
					shareAddListener.onCancel();
				}
			}

			@Override
			public boolean onBeforePost(Activity parent, SocialNetwork socialNetwork, PostData postData) {
				return shareAddListener instanceof SocialNetworkListener && ((SimpleShareListener) shareAddListener).onBeforePost(parent, socialNetwork, postData);
			}

			@Override
			public void onAfterPost(Activity parent, SocialNetwork socialNetwork, JSONObject responseObject) {
				if(shareAddListener != null) {
					shareAddListener.onCreate(share);
				}
			}
		};

		shareSystem.share(activity, session, share, shareText, location, shareType, snListener);
	}

protected void handleNonNetworkShare ( Activity activity , final SocializeSession session , final ShareType shareType , final Share share , String shareText , Location location , final ShareAddListener shareAddListener ) { SocialNetworkListener snListener = new SocialNetworkListener ( ) { @ Override public void onNetworkError ( Activity context , SocialNetwork network , Exception error ) { if ( shareAddListener != null ) { shareAddListener . onError ( SocializeException . wrap ( error ) ) ; } } @ Override public void onCancel ( ) { if ( shareAddListener != null ) { shareAddListener . onCancel ( ) ; } } @ Override public boolean onBeforePost ( Activity parent , SocialNetwork socialNetwork , PostData postData ) { return shareAddListener instanceof SocialNetworkListener && ( ( SimpleShareListener ) shareAddListener ) . onBeforePost ( parent , socialNetwork , postData ) ; } @ Override public void onAfterPost ( Activity parent , SocialNetwork socialNetwork , JSONObject responseObject ) { if ( shareAddListener != null ) { shareAddListener . onCreate ( share ) ; } } } ; shareSystem . share ( activity , session , share , shareText , location , shareType , snListener ) ; }

Handles a non-network share like email or SMS.

Handles a non - network share like email or SMS .


public static void addComment (Activity context, Entity entity, String text, CommentAddListener listener) {
		proxy.addComment(context, entity, text, listener);
	}

public static void addComment ( Activity context , Entity entity , String text , CommentAddListener listener ) { proxy . addComment ( context , entity , text , listener ) ; }

Adds a comment to the given entity.  This method will also prompt the user to share their comment.
@param context The current context.
@param entity The entity on which the comment will be associated.
@param text The text of the comment.
@param listener A listener to handle the result.

Adds a comment to the given entity . This method will also prompt the user to share their comment .


public static void deleteComment (Activity context, long id, CommentDeleteListener listener) {
		proxy.deleteComment(context, id, listener);
	}

public static void deleteComment ( Activity context , long id , CommentDeleteListener listener ) { proxy . deleteComment ( context , id , listener ) ; }

Deletes a comment.  Only the person that created the comment can delete it.
@param context The current context.
@param id The ID of the comment to be deleted.
@param listener A listener to handle the result.

Deletes a comment . Only the person that created the comment can delete it .


public static void addComment (Activity context, Entity entity, String text, CommentOptions commentOptions, CommentAddListener listener, SocialNetwork...networks) {
		proxy.addComment(context, entity, text, commentOptions, listener, networks);
	}

public static void addComment ( Activity context , Entity entity , String text , CommentOptions commentOptions , CommentAddListener listener , SocialNetwork ... networks ) { proxy . addComment ( context , entity , text , commentOptions , listener , networks ) ; }

Adds a comment to the given entity.  This method will NOT prompt the user to share their comment as the desired networks are passed as a parameter.
@param context The current context.
@param entity The entity on which the comment will be associated.
@param text The text of the comment.
@param commentOptions Optional parameters for the comment.
@param listener A listener to handle the result.
@param networks 0 or more networks on which to share the comment.  It is assumed that the user is already linked to the given networks.  If not an error will be reported in the listener for each propagation failure.

Adds a comment to the given entity . This method will NOT prompt the user to share their comment as the desired networks are passed as a parameter .


public static void getComment (Activity context, CommentGetListener listener, long id) {
		proxy.getComment(context, id, listener);
	}

public static void getComment ( Activity context , CommentGetListener listener , long id ) { proxy . getComment ( context , id , listener ) ; }

Retrieves a single comment based on ID.
@param context The current context.
@param id
@param listener A listener to handle the result.

Retrieves a single comment based on ID .


public static void getComments (Activity context, CommentListListener listener, long...ids) {
		proxy.getComments(context, listener, ids);
	}

public static void getComments ( Activity context , CommentListListener listener , long ... ids ) { proxy . getComments ( context , listener , ids ) ; }

Retrieves comments based on a set of IDs.
@param context The current context.
@param listener A listener to handle the result.
@param ids An array of comment IDs

Retrieves comments based on a set of IDs .


public static void getCommentsByUser (Activity context, User user, int start, int end, CommentListListener listener) {
		proxy.getCommentsByUser(context, user, start, end, listener);
	}

public static void getCommentsByUser ( Activity context , User user , int start , int end , CommentListListener listener ) { proxy . getCommentsByUser ( context , user , start , end , listener ) ; }

Retrieves all comments made by the given user.
@param context The current context.
@param user The user.
@param start The start index for pagination (from 0).
@param end The end index for pagination.
@param listener A listener to handle the result.

Retrieves all comments made by the given user .


public static void getCommentsByEntity (Activity context, String entityKey, int start, int end, CommentListListener listener) {
		proxy.getCommentsByEntity(context, entityKey, start, end, listener);
	}

public static void getCommentsByEntity ( Activity context , String entityKey , int start , int end , CommentListListener listener ) { proxy . getCommentsByEntity ( context , entityKey , start , end , listener ) ; }

Retrieves all comments associated with the given entity.
@param context The current context.
@param entityKey The entity on which the comment were associated.
@param start The start index for pagination (from 0).
@param end The end index for pagination.
@param listener A listener to handle the result.

Retrieves all comments associated with the given entity .


public static void getCommentsByApplication (Activity context, int start, int end, CommentListListener listener) {
		proxy.getCommentsByApplication(context, start, end, listener);
	}

public static void getCommentsByApplication ( Activity context , int start , int end , CommentListListener listener ) { proxy . getCommentsByApplication ( context , start , end , listener ) ; }

Retrieves all comments across all entities.
@param context The current context.
@param start The start index for pagination (from 0).
@param end The end index for pagination.
@param listener A listener to handle the result.

Retrieves all comments across all entities .


public static void showCommentView(Activity context, Entity entity, OnCommentViewActionListener listener) {
		proxy.showCommentView(context, entity, listener);
	}

public static void showCommentView ( Activity context , Entity entity , OnCommentViewActionListener listener ) { proxy . showCommentView ( context , entity , listener ) ; }

Shows the comments for an entity.
@param listener A listener to handle the result.


public JSONObject parseObject(String json) throws JSONException {
		json = json.trim();
		if(json.startsWith("[")) {
			JSONArray array = new JSONArray(json);
			JSONObject obj = new JSONObject();
			obj.put("data", array);
			return obj;
		}
		else {
			return new JSONObject(json);
		}
	}

public JSONObject parseObject ( String json ) throws JSONException { json = json . trim ( ) ; if ( json . startsWith ( "[" ) ) { JSONArray array = new JSONArray ( json ) ; JSONObject obj = new JSONObject ( ) ; obj . put ( "data" , array ) ; return obj ; } else { return new JSONObject ( json ) ; } }

Detects whether the inbound string is a JSONArray and if so wraps the array in an object with a single field called "data"
@param json
@return

Detects whether the inbound string is a JSONArray and if so wraps the array in an object with a single field called data


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();
    }

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

Connect to an HTTP URL and return the response as a string .


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;
    }

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

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 .


public static void showAlert(Context context, String title, String text) {
        Builder alertBuilder = new Builder(context);
        alertBuilder.setTitle(title);
        alertBuilder.setMessage(text);
        alertBuilder.create().show();
    }

public static void showAlert ( Context context , String title , String text ) { Builder alertBuilder = new Builder ( context ) ; alertBuilder . setTitle ( title ) ; alertBuilder . setMessage ( text ) ; alertBuilder . create ( ) . show ( ) ; }

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

Display a simple alert dialog with the given text and title .


public static void logd(String tag, String msg) {
        if (ENABLE_LOG) {
            Log.d(tag, msg);
        }
    }

public static void logd ( String tag , String msg ) { if ( ENABLE_LOG ) { Log . d ( tag , msg ) ; } }

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

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 .


private Type getRuntimeTypeIfMoreSpecific(Type type, Object value) {
    if (value != null
        && (type == Object.class || type instanceof TypeVariable<?> || type instanceof Class<?>)) {
      type = value.getClass();
    }
    return type;
  }

private Type getRuntimeTypeIfMoreSpecific ( Type type , Object value ) { if ( value != null && ( type == Object . class || type instanceof TypeVariable < ? > || type instanceof Class < ? > ) ) { type = value . getClass ( ) ; } return type ; }

Finds a compatible runtime type if it is more specific


public void setEntitySafe(Entity entity) {
		if(StringUtils.isEmpty(entity.getName())) {
			setEntityKey(entity.getKey());
		}
		else {
			setEntity(entity);
		}
	}

public void setEntitySafe ( Entity entity ) { if ( StringUtils . isEmpty ( entity . getName ( ) ) ) { setEntityKey ( entity . getKey ( ) ) ; } else { setEntity ( entity ) ; } }

Reverts to only set the entity key if the name is not defined.
This ensures an existing entity name is not wiped out when the action is saved.
@param entity

Reverts to only set the entity key if the name is not defined . This ensures an existing entity name is not wiped out when the action is saved .


public String buildProfileImageUrl(String id) {
		StringBuilder builder = new StringBuilder();
		builder.append("http://graph.facebook.com/");
		builder.append(id);
		builder.append("/picture?type=large");
		return builder.toString();
	}

public String buildProfileImageUrl ( String id ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "http://graph.facebook.com/" ) ; builder . append ( id ) ; builder . append ( "/picture?type=large" ) ; return builder . toString ( ) ; }

Constructs the URL to access the FB graph API and retrieve a profile image for the
user with the given facebook id.
@param id
@return

Constructs the URL to access the FB graph API and retrieve a profile image for the user with the given facebook id .


public void onImageChange(Bitmap bitmap) {
		if(bitmap != null) {
			Bitmap scaled = bitmapUtils.getScaledBitmap(bitmap, 200, 200);
			content.onProfilePictureChange(scaled);
		}
	}

public void onImageChange ( Bitmap bitmap ) { if ( bitmap != null ) { Bitmap scaled = bitmapUtils . getScaledBitmap ( bitmap , 200 , 200 ) ; content . onProfilePictureChange ( scaled ) ; } }

Called when the profile picture has been changed by the user.
@param bitmap

Called when the profile picture has been changed by the user .


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 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 ) ; } }

Builds the signature base string from the data this instance was
configured with.

@return the signature base string
@throws OAuthMessageSignerException

Builds the signature base string from the data this instance was configured with .


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();
    }

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 ( ) ; }

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

Normalizes the set of request parameters this instance was configured with as per OAuth spec section 9 . 1 . 1 .


public void authorize(Activity activity, final DialogListener listener) {
        authorize(activity, new String[] {}, DEFAULT_AUTH_ACTIVITY_CODE,
                listener);
    }

public void authorize ( Activity activity , final DialogListener listener ) { authorize ( activity , new String [ ] { } , DEFAULT_AUTH_ACTIVITY_CODE , listener ) ; }

Default authorize method. Grants only basic permissions.

See authorize() below for @params.

Default authorize method . Grants only basic permissions .


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);
        }
    }

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.


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);
    }

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 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.

Helper to validate an activity intent by resolving and checking the provider s package signature .


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;
    }

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 ; }

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)

Invalidate the current user session by removing the access token in memory clearing the browser cookie and calling auth . expireSession through the API .


public void dialog(Context context, String action, Bundle parameters,
            final DialogListener 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 {
            new FbDialog(context, url, listener).show();
        }
    }

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.

Generate a UI dialog for the request action in the given Android context with the provided parameters .


public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
    synchronized (localFormat) {
      String dateFormatAsString = enUsFormat.format(src);
      return new JsonPrimitive(dateFormatAsString);
    }
  }

public JsonElement serialize ( Date src , Type typeOfSrc , JsonSerializationContext context ) { synchronized ( localFormat ) { String dateFormatAsString = enUsFormat . format ( src ) ; return new JsonPrimitive ( dateFormatAsString ) ; } }


@Deprecated
	public static void link (Activity context, SocializeAuthListener listener) {
		proxy.link(context, listener);
	}

@ Deprecated public static void link ( Activity context , SocializeAuthListener listener ) { proxy . link ( context , listener ) ; }

Links the current user to a facebook account.  The user will be presented with the Facebook authentication dialog.
@param context The current context.
@param listener A listener to handle the result.

Links the current user to a facebook account . The user will be presented with the Facebook authentication dialog .


@Deprecated
	public static void link (Activity context, SocializeAuthListener listener, String...permissions) {
		proxy.link(context, listener, permissions);
	}

@ Deprecated public static void link ( Activity context , SocializeAuthListener listener , String ... permissions ) { proxy . link ( context , listener , permissions ) ; }

Links the current user to a facebook account with custom FB permissions.  The user will be presented with the Facebook authentication dialog.
@param context The current context.
@param listener A listener to handle the result.
@param permissions One or more permissions defined by http://developers.facebook.com/docs/authentication/permissions/

Links the current user to a facebook account with custom FB permissions . The user will be presented with the Facebook authentication dialog .


@Deprecated
	public static void link (Activity context, String token, boolean verifyPermissions, SocializeAuthListener listener){
		proxy.link(context, token, verifyPermissions, listener);
	}

@ Deprecated public static void link ( Activity context , String token , boolean verifyPermissions , SocializeAuthListener listener ) { proxy . link ( context , token , verifyPermissions , listener ) ; }

Links an existing Facebook access token with the current user.  No authentication dialog will be shown.
@param context The current context.
@param token The Facebook access token.
@param verifyPermissions If true this method will also verify that the permissions assigned to the given token match the default permissions required by Socialize.
If not an authentication with FB will be attempted.  If this parameter is false it is ASSUMED that permissions are valid.
@param listener A listener to handle the result.

Links an existing Facebook access token with the current user . No authentication dialog will be shown .


public static void postEntity(final Activity context, final Entity entity, final String text, final SocialNetworkShareListener listener){

		if(proxy.isLinkedForWrite(context)) {
			proxy.postEntity(context, entity, text, listener);
		}
		else {
			proxy.linkForWrite(context, new SocializeAuthListener() {

				@Override
				public void onError(SocializeException error) {
					if(listener != null) {
						listener.onNetworkError(context, SocialNetwork.FACEBOOK, error);
					}
				}

				@Override
				public void onCancel() {
					if(listener != null) {
						listener.onCancel();
					}
				}

				@Override
				public void onAuthSuccess(SocializeSession session) {
					proxy.postEntity(context, entity, text, listener);
				}

				@Override
				public void onAuthFail(SocializeException error) {
					if(listener != null) {
						listener.onNetworkError(context, SocialNetwork.FACEBOOK, error);
					}
				}
			});
		}
	}

public static void postEntity ( final Activity context , final Entity entity , final String text , final SocialNetworkShareListener listener ) { if ( proxy . isLinkedForWrite ( context ) ) { proxy . postEntity ( context , entity , text , listener ) ; } else { proxy . linkForWrite ( context , new SocializeAuthListener ( ) { @ Override public void onError ( SocializeException error ) { if ( listener != null ) { listener . onNetworkError ( context , SocialNetwork . FACEBOOK , error ) ; } } @ Override public void onCancel ( ) { if ( listener != null ) { listener . onCancel ( ) ; } } @ Override public void onAuthSuccess ( SocializeSession session ) { proxy . postEntity ( context , entity , text , listener ) ; } @ Override public void onAuthFail ( SocializeException error ) { if ( listener != null ) { listener . onNetworkError ( context , SocialNetwork . FACEBOOK , error ) ; } } } ) ; } }

Posts an entity to the user's Facebook wall.  Post data can be customized by implementing the onBeforePost method in the given SocialNetworkListener.
@param context The current context.
@param entity The Socialize entity to which the post corresponds (Required)
@param text The text for the post.
@param listener A listnener to handle callbacks from the post.

Posts an entity to the user s Facebook wall . Post data can be customized by implementing the onBeforePost method in the given SocialNetworkListener .


@Deprecated
	public static void extendAccessToken(Activity context, SocializeAuthListener listener) {
		proxy.extendAccessToken(context, listener);
	}

@ Deprecated public static void extendAccessToken ( Activity context , SocializeAuthListener listener ) { proxy . extendAccessToken ( context , listener ) ; }

Extends the user's Facebook access token if needed.
@param context The current context
@param listener A listener to handle the result after re-authentication with Socialize.
@deprecated Use onResume()

Extends the user s Facebook access token if needed .


public static void getCurrentPermissions(Activity context, String token, OnPermissionResult callback) {
		proxy.getCurrentPermissions(context, token, callback);
	}

public static void getCurrentPermissions ( Activity context , String token , OnPermissionResult callback ) { proxy . getCurrentPermissions ( context , token , callback ) ; }

Retrieves the current permissions for token provided.
@param parent The current context.
@param token The token for which we are going to retrieve permissions.
@param callback A callback to handle the response.

Retrieves the current permissions for token provided .


public static String[] getHashKeys(Activity context) throws NoSuchAlgorithmException {
        PackageInfo packageInfo = null;
        String[] keys = null;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);

            if(packageInfo != null && packageInfo.signatures != null && packageInfo.signatures.length > 0) {

            	keys = new String[packageInfo.signatures.length];
            	for (int i = 0; i < packageInfo.signatures.length; i++) {
            		Signature signature = packageInfo.signatures[i];
            		MessageDigest md = MessageDigest.getInstance("SHA1");
            		md.update(signature.toByteArray());
            		String hash = new String(Base64.encode(md.digest(), 0));
            		keys[i] = hash;
				}
            }
        }
        catch (PackageManager.NameNotFoundException e) {
        	e.printStackTrace();
        }

        return keys;
	}

public static String [ ] getHashKeys ( Activity context ) throws NoSuchAlgorithmException { PackageInfo packageInfo = null ; String [ ] keys = null ; try { packageInfo = context . getPackageManager ( ) . getPackageInfo ( context . getPackageName ( ) , PackageManager . GET_SIGNATURES ) ; if ( packageInfo != null && packageInfo . signatures != null && packageInfo . signatures . length > 0 ) { keys = new String [ packageInfo . signatures . length ] ; for ( int i = 0 ; i < packageInfo . signatures . length ; i ++ ) { Signature signature = packageInfo . signatures [ i ] ; MessageDigest md = MessageDigest . getInstance ( "SHA1" ) ; md . update ( signature . toByteArray ( ) ) ; String hash = new String ( Base64 . encode ( md . digest ( ) , 0 ) ) ; keys [ i ] = hash ; } } } catch ( PackageManager . NameNotFoundException e ) { e . printStackTrace ( ) ; } return keys ; }

Returns the hash key used to authenticate this application with Facebook.  Useful for debugging.
@param context
@return
@throws NoSuchAlgorithmException

Returns the hash key used to authenticate this application with Facebook . Useful for debugging .


public static void saveEntity (Activity context, Entity e, EntityAddListener listener) {
		proxy.saveEntity(context, e, listener);
	}

public static void saveEntity ( Activity context , Entity e , EntityAddListener listener ) { proxy . saveEntity ( context , e , listener ) ; }

Saves or Creates an entity
@param context The current context.
@param e The entity to be created.
@param listener A listener to handle the result.


public static void getEntity (Activity context, String key, EntityGetListener listener) {
		proxy.getEntity(context, key, listener);
	}

public static void getEntity ( Activity context , String key , EntityGetListener listener ) { proxy . getEntity ( context , key , listener ) ; }

Retrieves an entity based on its key.
@param context The current context.
@param key The entity key.
@param listener A listener to handle the result.


public static void getEntity (Activity context, long id, EntityGetListener listener) {
		proxy.getEntity(context, id, listener);
	}

public static void getEntity ( Activity context , long id , EntityGetListener listener ) { proxy . getEntity ( context , id , listener ) ; }

Retrieves an entity based on its id.
@param context The current context.
@param id The entity id.
@param listener A listener to handle the result.


public static void getEntities (Activity context, int start, int end, EntityListListener listener) {
		proxy.getEntities(context, start, end, SortOrder.CREATION_DATE, listener);
	}

public static void getEntities ( Activity context , int start , int end , EntityListListener listener ) { proxy . getEntities ( context , start , end , SortOrder . CREATION_DATE , listener ) ; }

Retrieves all entities sorted by creation date.
@param context The current context.
@param start The start index for pagination (0 based).
@param end The end index for pagination (0 based).
@param listener A listener to handle the result.

Retrieves all entities sorted by creation date .


public static void getEntities (Activity context, EntityListListener listener, String...keys) {
		proxy.getEntities(context, SortOrder.CREATION_DATE, listener, keys);
	}

public static void getEntities ( Activity context , EntityListListener listener , String ... keys ) { proxy . getEntities ( context , SortOrder . CREATION_DATE , listener , keys ) ; }

Retrieves the entities designated by the given keys.
@param context The current context.
@param listener A listener to handle the result.
@param keys One or more entity keys.

Retrieves the entities designated by the given keys .


@Override
	public boolean onCreateContextMenu(SocializeUIActivity activity, ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
		return false;
	}

@ Override public boolean onCreateContextMenu ( SocializeUIActivity activity , ContextMenu menu , View v , ContextMenu . ContextMenuInfo menuInfo ) { return false ; }

Called BEFORE the default activity onCreateContextMenu event.

@param activity The calling activity.
@param menu     The context menu that is being built
@param v        The view for which the context menu is being built
@param menuInfo Extra information about the item for which the context menu should be shown. This information will vary depending on the class of v.
@return True to PREVENT the default implementation from executing.

Called BEFORE the default activity onCreateContextMenu event .


public static void subscribe (Activity context, Entity e, SubscriptionType type, SubscriptionResultListener listener) {
		subscriptionUtils.subscribe(context, e, type, listener);
	}

public static void subscribe ( Activity context , Entity e , SubscriptionType type , SubscriptionResultListener listener ) { subscriptionUtils . subscribe ( context , e , type , listener ) ; }

Subscribes the current user to notifications for new comments on this entity.
@param context The current context.
@param e The entity.
@param type The subscription type.
@param listener A listener to handle the result.

Subscribes the current user to notifications for new comments on this entity .


public static void isSubscribed (Activity context, Entity e, SubscriptionType type, SubscriptionCheckListener listener) {
		subscriptionUtils.isSubscribed(context, e, type, listener);
	}

public static void isSubscribed ( Activity context , Entity e , SubscriptionType type , SubscriptionCheckListener listener ) { subscriptionUtils . isSubscribed ( context , e , type , listener ) ; }

Determines if the current user is subscribed to notifications on new comments for the given entity.
@param context The current context.
@param e The entity.
@param type The subscription type.
@param listener A listener to handle the result.

Determines if the current user is subscribed to notifications on new comments for the given entity .


public boolean checkRegistrations(Context context, SocializeSession session) {

		boolean checked = false;

		if(!checking) {
			checking = true;

			try {

				if(appUtils.isNotificationsAvailable(context)) {

					if(config.getBooleanProperty(SocializeConfig.SOCIALIZE_CHECK_NOTIFICATIONS, true)) {
						if(logger != null && logger.isDebugEnabled()) {
							logger.debug("Checking GCM registration state");
						}

						boolean c2DMRegistered = notificationRegistrationSystem.isRegisteredC2DM(context);
						boolean socRegistered = notificationRegistrationSystem.isRegisteredSocialize(context, session.getUser());

						if(!c2DMRegistered || !socRegistered) {

							// Reload
							notificationRegistrationState.reload(context);

							c2DMRegistered = notificationRegistrationSystem.isRegisteredC2DM(context);
							socRegistered = notificationRegistrationSystem.isRegisteredSocialize(context, session.getUser());

							if(!c2DMRegistered || !socRegistered) {
								if(!c2DMRegistered && config.getBooleanProperty(SocializeConfig.GCM_REGISTRATION_ENABLED, true)) {

									if(notificationRegistrationSystem.isRegistrationPending()) {
										if(logger != null && logger.isDebugEnabled()) {
											logger.debug("GCM Registration already pending");
										}
									}
									else {
										if(logger != null && logger.isInfoEnabled()) {
											logger.info("Not registered with GCM, sending registration request...");
										}

										notificationRegistrationSystem.registerC2DMAsync(context);
									}
								}
								else if(!socRegistered && !StringUtils.isEmpty(notificationRegistrationState.getC2DMRegistrationId())) {

									if(notificationRegistrationSystem.isSocializeRegistrationPending()) {
										if(logger != null && logger.isDebugEnabled()) {
											logger.debug("Registration already pending with Socialize for GCM");
										}
									}
									else {
										if(logger != null && logger.isInfoEnabled()) {
											logger.info("Not registered with Socialize for GCM, registering...");
										}

										notificationRegistrationSystem.registerSocialize(context, notificationRegistrationState.getC2DMRegistrationId());
									}
								}
							}
							else {
								if(logger != null && logger.isDebugEnabled()) {
									logger.debug("GCM registration OK");
								}
							}
						}
						else {
							if(logger != null && logger.isDebugEnabled()) {
								logger.debug("GCM registration OK");
							}
						}

						checked = true;
					}
					else {
						if(logger != null && logger.isWarnEnabled()) {
							logger.warn("GCM registration check skipped");
						}
					}
				}
				else {
					if(logger != null && logger.isInfoEnabled()) {
						logger.info("Notifications not enabled.  Check the AndroidManifest.xml for correct configuration.");
					}

					checked = true;
				}
			}
			finally {
				checking = false;
			}
		}

		return checked;
	}

Called at application startup.
@param context


public JsonToken peek() throws IOException {
    if (token != null) {
      return token;
    }

    switch (stack[stackSize - 1]) {
    case EMPTY_DOCUMENT:
      if (lenient) {
        consumeNonExecutePrefix();
      }
      stack[stackSize - 1] = JsonScope.NONEMPTY_DOCUMENT;
      JsonToken firstToken = nextValue();
      if (!lenient && token != JsonToken.BEGIN_ARRAY && token != JsonToken.BEGIN_OBJECT) {
        throw new IOException("Expected JSON document to start with '[' or '{' but was " + token
            + " at line " + getLineNumber() + " column " + getColumnNumber());
      }
      return firstToken;
    case EMPTY_ARRAY:
      return nextInArray(true);
    case NONEMPTY_ARRAY:
      return nextInArray(false);
    case EMPTY_OBJECT:
      return nextInObject(true);
    case DANGLING_NAME:
      return objectValue();
    case NONEMPTY_OBJECT:
      return nextInObject(false);
    case NONEMPTY_DOCUMENT:
      int c = nextNonWhitespace(false);
      if (c == -1) {
        return JsonToken.END_DOCUMENT;
      }
      pos--;
      if (!lenient) {
        throw syntaxError("Expected EOF");
      }
      return nextValue();
    case CLOSED:
      throw new IllegalStateException("JsonReader is closed");
    default:
      throw new AssertionError();
    }
  }

Returns the type of the next token without consuming it.

Returns the type of the next token without consuming it .


public void nextNull() throws IOException {
    peek();
    if (token != JsonToken.NULL) {
      throw new IllegalStateException("Expected null but was " + token
          + " at line " + getLineNumber() + " column " + getColumnNumber());
    }

    advance();
  }

public
void
nextNull
(
)
throws
IOException
{
peek
(
)
;
if
(
token
!=
JsonToken
.
)
{
throw
new
IllegalStateException
(
"Expected null but was "
+
token
+
" at line "
+
getLineNumber
(
)
+
" column "
+
getColumnNumber
(
)
)
;
}
advance
(
)
;
}

Consumes the next token from the JSON stream and asserts that it is a
literal null.

@throws IllegalStateException if the next token is not null or if this
reader is closed.

Consumes the next token from the JSON stream and asserts that it is a literal null .


private char readEscapeCharacter() throws IOException {
    if (pos == limit && !fillBuffer(1)) {
      throw syntaxError("Unterminated escape sequence");
    }

    char escaped = buffer[pos++];
    switch (escaped) {
    case 'u':
      if (pos + 4 > limit && !fillBuffer(4)) {
        throw syntaxError("Unterminated escape sequence");
      }
      // Equivalent to Integer.parseInt(stringPool.get(buffer, pos, 4), 16);
      char result = 0;
      for (int i = pos, end = i + 4; i < end; i++) {
        char c = buffer[i];
        result <<= 4;
        if (c >= '0' && c <= '9') {
          result += (c - '0');
        } else if (c >= 'a' && c <= 'f') {
          result += (c - 'a' + 10);
        } else if (c >= 'A' && c <= 'F') {
          result += (c - 'A' + 10);
        } else {
          throw new NumberFormatException("\\u" + stringPool.get(buffer, pos, 4));
        }
      }
      pos += 4;
      return result;

    case 't':
      return '\t';

    case 'b':
      return '\b';

    case 'n':
      return '\n';

    case 'r':
      return '\r';

    case 'f':
      return '\f';

    case '\'':
    case '"':
    case '\\':
    default:
      return escaped;
    }
  }

Unescapes the character identified by the character or characters that
immediately follow a backslash. The backslash '\' should have already
been read. This supports both unicode escapes "u000A" and two-character
escapes "\n".

@throws NumberFormatException if any unicode escape sequences are
malformed.

Unescapes the character identified by the character or characters that immediately follow a backslash . The backslash \ should have already been read . This supports both unicode escapes u000A and two - character escapes \ n .


public static void showShareDialog (Activity context, Entity entity) {
		proxy.showShareDialog(context, entity, DEFAULT, null, null);
	}

public static void showShareDialog ( Activity context , Entity entity ) { proxy . showShareDialog ( context , entity , DEFAULT , null , null ) ; }

Displays the default share dialog.  In most cases this is the simplest version to use.
@param context The current context.
@param entity The entity being shared.

Displays the default share dialog . In most cases this is the simplest version to use .


public static void showShareDialog (Activity context, Entity entity, SocialNetworkDialogListener listener) {
		proxy.showShareDialog(context, entity, DEFAULT, listener, listener);
	}

public static void showShareDialog ( Activity context , Entity entity , SocialNetworkDialogListener listener ) { proxy . showShareDialog ( context , entity , DEFAULT , listener , listener ) ; }

Displays the default share dialog and allows for the handling of share dialog events.
@param context The current context.
@param entity The entity being shared.
@param listener A listener to handle events on the dialog.

Displays the default share dialog and allows for the handling of share dialog events .


public static void shareViaEmail(Activity context, Entity entity, ShareAddListener listener) {
		proxy.shareViaEmail(context, entity, listener);
	}

public static void shareViaEmail ( Activity context , Entity entity , ShareAddListener listener ) { proxy . shareViaEmail ( context , entity , listener ) ; }

Shares the given entity via email.  This method with launch the default email application on the device.
@param context The current context.
@param entity The entity being shared.
@param listener A listener to handle events.

Shares the given entity via email . This method with launch the default email application on the device .


public static void shareViaGooglePlus(Activity context, Entity entity, ShareAddListener listener) {
		proxy.shareViaGooglePlus(context, entity, listener);
	}

public static void shareViaGooglePlus ( Activity context , Entity entity , ShareAddListener listener ) { proxy . shareViaGooglePlus ( context , entity , listener ) ; }

Shares the given entity via Google+.  This method with launch the Google+ application on the device.
@param context The current context.
@param entity The entity being shared.
@param listener A listener to handle events.

Shares the given entity via Google + . This method with launch the Google + application on the device .


public static void shareViaOther(Activity context, Entity entity, ShareAddListener listener) {
		proxy.shareViaOther(context, entity, listener);
	}

public static void shareViaOther ( Activity context , Entity entity , ShareAddListener listener ) { proxy . shareViaOther ( context , entity , listener ) ; }

Shares the given entity via a user selected medium.  This method with launch the default application share dialog on the device.
@param context The current context.
@param entity The entity being shared.
@param listener A listener to handle events.

Shares the given entity via a user selected medium . This method with launch the default application share dialog on the device .


public static void shareViaSMS(Activity context, Entity entity, ShareAddListener listener) {
		proxy.shareViaSMS(context, entity, listener);
	}

public static void shareViaSMS ( Activity context , Entity entity , ShareAddListener listener ) { proxy . shareViaSMS ( context , entity , listener ) ; }

Shares the given entity via SMS.  This method with launch the default SMS application on the device.
@param context The current context.
@param entity The entity being shared.
@param listener A listener to handle events.

Shares the given entity via SMS . This method with launch the default SMS application on the device .


public static void shareViaSocialNetworks(Activity context, Entity entity, ShareOptions shareOptions, SocialNetworkShareListener listener, SocialNetwork...networks) {
		proxy.shareViaSocialNetworks(context, entity, shareOptions, listener, networks);
	}

public static void shareViaSocialNetworks ( Activity context , Entity entity , ShareOptions shareOptions , SocialNetworkShareListener listener , SocialNetwork ... networks ) { proxy . shareViaSocialNetworks ( context , entity , shareOptions , listener , networks ) ; }

Shares the given entity via a Social Network such as Twitter or Facebook.  This will prompt the user to select a network.
@param context The current context.
@param entity The entity being shared.
@param shareOptions Options for the share.  If text is available for the share it can be specified here.
@param listener A listener to handle events.

Shares the given entity via a Social Network such as Twitter or Facebook . This will prompt the user to select a network .


public static void getShare (Activity context, ShareGetListener listener, long id) {
		proxy.getShare(context, listener, id);
	}

public static void getShare ( Activity context , ShareGetListener listener , long id ) { proxy . getShare ( context , listener , id ) ; }

Retrieves a single share event based on ID.
@param context The current context.
@param listener A listener to handle the result.
@param id The ID of the share.

Retrieves a single share event based on ID .


public static void getShares (Activity context, ShareListListener listener, long...ids) {
		proxy.getShares(context, listener, ids);
	}

public static void getShares ( Activity context , ShareListListener listener , long ... ids ) { proxy . getShares ( context , listener , ids ) ; }

Retrieves multiple share events based on ID.
@param context The current context.
@param listener A listener to handle the result.
@param ids One or more IDs for the shares returned.

Retrieves multiple share events based on ID .


public static void getSharesByUser (Activity context, User user, int start, int end, ShareListListener listener) {
		proxy.getSharesByUser(context, user, start, end, listener);
	}

public static void getSharesByUser ( Activity context , User user , int start , int end , ShareListListener listener ) { proxy . getSharesByUser ( context , user , start , end , listener ) ; }

Retrieves all share events performed by the given user.
@param context The current context.
@param user The user who performed the share(s).
@param start The start index for the result set (0 indexed).
@param end The end index for the result set.
@param listener A listener to handle the result.

Retrieves all share events performed by the given user .


public static void getSharesByEntity (Activity context, String entityKey, int start, int end, ShareListListener listener) {
		proxy.getSharesByEntity(context, entityKey, start, end, listener);
	}

public static void getSharesByEntity ( Activity context , String entityKey , int start , int end , ShareListListener listener ) { proxy . getSharesByEntity ( context , entityKey , start , end , listener ) ; }

Retrieves all share events performed on the given entity.
@param context The current context.
@param entityKey The key of the entity that was shared.
@param start The start index for the result set (0 indexed).
@param end The end index for the result set.
@param listener A listener to handle the result.

Retrieves all share events performed on the given entity .


public static void getSharesByApplication (Activity context, int start, int end, ShareListListener listener) {
		proxy.getSharesByApplication(context, start, end, listener);
	}

public static void getSharesByApplication ( Activity context , int start , int end , ShareListListener listener ) { proxy . getSharesByApplication ( context , start , end , listener ) ; }

Retrieves all share events across all entities.
@param context The current context.
@param start The start index for the result set (0 indexed).
@param end The end index for the result set.
@param listener A listener to handle the result.

Retrieves all share events across all entities .


public static void like (Activity context, Entity entity, LikeAddListener listener) {
		proxy.like(context, entity, listener);
	}

public static void like ( Activity context , Entity entity , LikeAddListener listener ) { proxy . like ( context , entity , listener ) ; }

Records a like against the given entity for the current user. This method will also prompt the user to share their like.
@param context The current context.
@param entity The entity to be liked.
@param listener A listener to handle the result.

Records a like against the given entity for the current user . This method will also prompt the user to share their like .


public static void like (Activity context, Entity entity, LikeOptions likeOptions, LikeAddListener listener, SocialNetwork...networks) {
		proxy.like(context, entity, likeOptions, listener, networks);
	}

public static void like ( Activity context , Entity entity , LikeOptions likeOptions , LikeAddListener listener , SocialNetwork ... networks ) { proxy . like ( context , entity , likeOptions , listener , networks ) ; }

Records a like against the given entity for the current user.  This method will NOT prompt the user to share their like.
@param context The current context.
@param entity The entity to be liked.
@param likeOptions Optional parameters for the like.
@param listener A listener to handle the result.
@param networks 0 or more networks on which to share the like.

Records a like against the given entity for the current user . This method will NOT prompt the user to share their like .


public static void unlike (Activity context, String entityKey, LikeDeleteListener listener) {
		proxy.unlike(context, entityKey, listener);
	}

public static void unlike ( Activity context , String entityKey , LikeDeleteListener listener ) { proxy . unlike ( context , entityKey , listener ) ; }

Removes a like previously created for the current user.
@param context The current context.
@param entityKey The entity that was liked.
@param listener A listener to handle the result.

Removes a like previously created for the current user .


public static void getLike (Activity context, String entityKey, LikeGetListener listener) {
		proxy.getLike(context, entityKey, listener);
	}

public static void getLike ( Activity context , String entityKey , LikeGetListener listener ) { proxy . getLike ( context , entityKey , listener ) ; }

Retrieves a like for an entity and the current user.
@param context The current context.
@param entityKey The entity that was liked.
@param listener A listener to handle the result.

Retrieves a like for an entity and the current user .


public static void getLike (Activity context, long id, LikeGetListener listener) {
		proxy.getLike(context, id, listener);
	}

public static void getLike ( Activity context , long id , LikeGetListener listener ) { proxy . getLike ( context , id , listener ) ; }

Retrieves a like based on its ID.
@param context The current context.
@param id The id of the like.
@param listener A listener to handle the result.


public static void isLiked(Activity context, String entityKey, IsLikedListener listener) {
		proxy.getLike(context, entityKey, listener);
	}

public static void isLiked ( Activity context , String entityKey , IsLikedListener listener ) { proxy . getLike ( context , entityKey , listener ) ; }

Determines if the given entity has been liked by the current user.
@param context The current context.
@param entityKey The entity that was liked.
@param listener listener A listener to handle the result.

Determines if the given entity has been liked by the current user .


public static void getLikesByUser (Activity context, User user, int start, int end, LikeListListener listener) {
		proxy.getLikesByUser(context, user, start, end, listener);
	}

public static void getLikesByUser ( Activity context , User user , int start , int end , LikeListListener listener ) { proxy . getLikesByUser ( context , user , start , end , listener ) ; }

Lists all likes for the given user.
@param context The current context.
@param user The user for whom likes will be queried.
@param start The first index (for pagination), starting at 0
@param end The last index (for pagination)
@param listener A listener to handle the result.


public static void getLikesByEntity (Activity context, String entityKey, int start, int end, LikeListListener listener) {
		proxy.getLikesByEntity(context, entityKey, start, end, listener);
	}

public static void getLikesByEntity ( Activity context , String entityKey , int start , int end , LikeListListener listener ) { proxy . getLikesByEntity ( context , entityKey , start , end , listener ) ; }

Lists all likes for the given entity.
@param context The current context.
@param entityKey The entity for whom likes will be queried.
@param start The first index (for pagination), starting at 0
@param end The last index (for pagination)
@param listener A listener to handle the result.


@Deprecated
	@Override
	public synchronized Facebook getFacebook(Context context) {
		if(facebook == null) {
			facebook = new Facebook(config.getProperty(SocializeConfig.FACEBOOK_APP_ID));
		}
		return facebook;
	}

@ Deprecated @ Override public synchronized Facebook getFacebook ( Context context ) { if ( facebook == null ) { facebook = new Facebook ( config . getProperty ( SocializeConfig . FACEBOOK_APP_ID ) ) ; } return facebook ; }


protected void collectHeaderParameters(HttpRequest request, HttpParameters out) {
        HttpParameters headerParams = OAuth.oauthHeaderToParamsMap(request.getHeader(OAuth.HTTP_AUTHORIZATION_HEADER));
        out.putAll(headerParams, false);
    }

protected void collectHeaderParameters ( HttpRequest request , HttpParameters out ) { HttpParameters headerParams = OAuth . oauthHeaderToParamsMap ( request . getHeader ( OAuth . HTTP_AUTHORIZATION_HEADER ) ) ; out . putAll ( headerParams , false ) ; }

Collects OAuth Authorization header parameters as per OAuth Core 1.0 spec
section 9.1.1

Collects OAuth Authorization header 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 x-www-form-urlencoded body parameters as per OAuth Core 1.0 spec
section 9.1.1

Collects x - www - form - urlencoded body 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);
        }
    }

Collects HTTP GET query string parameters as per OAuth Core 1.0 spec
section 9.1.1

Collects HTTP GET query string parameters as per OAuth Core 1 . 0 spec section 9 . 1 . 1


private JsonWriter newJsonWriter(Writer writer) throws IOException {
    if (generateNonExecutableJson) {
      writer.write(JSON_NON_EXECUTABLE_PREFIX);
    }
    JsonWriter jsonWriter = new JsonWriter(writer);
    if (prettyPrinting) {
      jsonWriter.setIndent("  ");
    }
    jsonWriter.setSerializeNulls(serializeNulls);
    return jsonWriter;
  }

private
JsonWriter
newJsonWriter
(
Writer
writer
)
throws
IOException
{
if
(
generateNonExecutableJson
)
{
writer
.
write
(
JSON_NON_EXECUTABLE_PREFIX
)
;
}
JsonWriter
jsonWriter
=
new
JsonWriter
(
writer
)
;
if
(
prettyPrinting
)
{
jsonWriter
.
setIndent
(
"  "
)
;
}
jsonWriter
.
setSerializeNulls
(
serializeNulls
)
;
return
jsonWriter
;
}

Returns a new JSON writer configured for this GSON and with the non-execute
prefix if that is configured.

Returns a new JSON writer configured for this GSON and with the non - execute prefix if that is configured .


@SuppressWarnings("unchecked") // use runtime checks to guarantee that 'T' is what it is
  private <T> ObjectConstructor<T> newDefaultImplementationConstructor(Class<? super T> rawType) {
    if (Collection.class.isAssignableFrom(rawType)) {
      if (SortedSet.class.isAssignableFrom(rawType)) {
        return new ObjectConstructor<T>() {
          public T construct() {
            return (T) new TreeSet<Object>();
          }
        };
      } else if (Set.class.isAssignableFrom(rawType)) {
        return new ObjectConstructor<T>() {
          public T construct() {
            return (T) new LinkedHashSet<Object>();
          }
        };
      } else if (Queue.class.isAssignableFrom(rawType)) {
        return new ObjectConstructor<T>() {
          public T construct() {
            return (T) new LinkedList<Object>();
          }
        };
      } else {
        return new ObjectConstructor<T>() {
          public T construct() {
            return (T) new ArrayList<Object>();
          }
        };
      }
    }

    if (Map.class.isAssignableFrom(rawType)) {
      return new ObjectConstructor<T>() {
        public T construct() {
          return (T) new LinkedHashMap<Object, Object>();
        }
      };
      // TODO: SortedMap ?
    }

    return null;
  }

Constructors for common interface types like Map and List and their
subytpes.

Constructors for common interface types like Map and List and their subytpes .


public static String replaceNewLines(String src, int from, int to) {
		if(src != null && from > 0 && to < from) {

			String strFrom = "";
			String strTo = "";

			for (int i = 0; i < from; i++) {
				strFrom+="\n";
			}
			for (int i = 0; i < to; i++) {
				strTo+="\n";
			}

			while (src.contains(strFrom)) {
				src = src.replaceAll(strFrom, strTo);
			}
		}
		return src;
	}

public static String replaceNewLines ( String src , int from , int to ) { if ( src != null && from > 0 && to < from ) { String strFrom = "" ; String strTo = "" ; for ( int i = 0 ; i < from ; i ++ ) { strFrom += "\n" ; } for ( int i = 0 ; i < to ; i ++ ) { strTo += "\n" ; } while ( src . contains ( strFrom ) ) { src = src . replaceAll ( strFrom , strTo ) ; } } return src ; }

Replaces successive new line characters.
@param src The source String.
@param from Number of successive new lines (e.g. 3 would be \n\n\n)
@param to The number of new lines to replace with.
@return The cleaned string.

Replaces successive new line characters .


void reload() {
//begin-snippet-1

// The in the Activity which renders the ActionBar
Entity entity = Entity.newInstance("http://getsocialize.com", "Socialize");

// Setup a listener to retain a reference
MyActionBarListener listener = new MyActionBarListener();

// Use the listener when you show the action bar
// The "this" argument refers to the current Activity
ActionBarUtils.showActionBar(this, R.layout.actionbar, entity, null, listener);

// Later (After the action bar has loaded!), you can reference the view to refresh
ActionBarView view = listener.getActionBarView();

if (view != null) {
	Entity newEntity = new Entity(); // This would be your new entity
	view.setEntity(newEntity);
	view.refresh();
}

//end-snippet-1
	}


public String getSimpleLocation(Address address) {
		StringBuilder builder = new StringBuilder();
		String locality = address.getLocality();
		String countryName = address.getCountryName();

		if(!StringUtils.isEmpty(locality)) {
			builder.append(locality);
		}
		else if(!StringUtils.isEmpty(countryName)) {
			builder.append(countryName);
		}

		return builder.toString();
	}

public String getSimpleLocation ( Address address ) { StringBuilder builder = new StringBuilder ( ) ; String locality = address . getLocality ( ) ; String countryName = address . getCountryName ( ) ; if ( ! StringUtils . isEmpty ( locality ) ) { builder . append ( locality ) ; } else if ( ! StringUtils . isEmpty ( countryName ) ) { builder . append ( countryName ) ; } return builder . toString ( ) ; }

Returns a simple one-line address based on city and country
@param address
@return

Returns a simple one - line address based on city and country


protected void getUser(final Session session, final AuthProviderListener listener) {
		Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
			// callback after Graph API response with user object
			@Override
			public void onCompleted(GraphUser user, Response response) {
				if(response.getError() != null) {
					handleError(response.getError().getException(), listener);
				}
				else if (user != null) {
					handleResult(session, user, listener);
				}
			}
		});
	}


public static void getActionsByApplication (Activity context, int start, int end, ActionListListener listener) {
		proxy.getActionsByApplication(context, start, end, listener);
	}

public static void getActionsByApplication ( Activity context , int start , int end , ActionListListener listener ) { proxy . getActionsByApplication ( context , start , end , listener ) ; }

Gets the application-wide actions.
@param context The current context.
@param start The start index for pagination (0 based).
@param end The end index for pagination (0 based).
@param listener A listener to handle the result.