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

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

Gets the actions of a single user.
@param context The current context.
@param userId The user for whom the actions will be returned.
@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.


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

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

Gets the actions for a given entity.
@param context The current context.
@param entityKey The entity key.
@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.


public static void getActionsByUserAndEntity (Activity context, long userId, String entityKey, int start, int end, ActionListListener listener) {
		proxy.getActionsByUserAndEntity(context, userId, entityKey, start, end, listener);
	}

public static void getActionsByUserAndEntity ( Activity context , long userId , String entityKey , int start , int end , ActionListListener listener ) { proxy . getActionsByUserAndEntity ( context , userId , entityKey , start , end , listener ) ; }

Gets the actions of a single user on a single entity.
@param context The current context.
@param userId The user for whom the actions will be returned.
@param entityKey The entity key.
@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.

Gets the actions of a single user on a single entity .


private JsonWriter close(JsonScope empty, JsonScope nonempty, String closeBracket)
      throws IOException {
    JsonScope context = peek();
    if (context != nonempty && context != empty) {
      throw new IllegalStateException("Nesting problem: " + stack);
    }
    if (deferredName != null) {
      throw new IllegalStateException("Dangling name: " + deferredName);
    }

    stack.remove(stack.size() - 1);
    if (context == nonempty) {
      newline();
    }
    out.write(closeBracket);
    return this;
  }

private
JsonWriter
close
(
JsonScope
empty
,
JsonScope
nonempty
,
String
closeBracket
)
throws
IOException
{
JsonScope
context
=
peek
(
)
;
if
(
context
!=
nonempty
&&
context
!=
empty
)
{
throw
new
IllegalStateException
(
"Nesting problem: "
+
stack
)
;
}
if
(
deferredName
!=
)
{
throw
new
IllegalStateException
(
"Dangling name: "
+
deferredName
)
;
}
stack
.
remove
(
stack
.
size
(
)
1
)
;
if
(
context
==
nonempty
)
{
newline
(
)
;
}
out
.
write
(
closeBracket
)
;
return
this
;
}

Closes the current scope by appending any necessary whitespace and the
given bracket.

Closes the current scope by appending any necessary whitespace and the given bracket .


public JsonWriter name(String name) throws IOException {
    if (name == null) {
      throw new NullPointerException("name == null");
    }
    if (deferredName != null) {
      throw new IllegalStateException();
    }
    deferredName = name;
    return this;
  }

public
JsonWriter
name
(
String
name
)
throws
IOException
{
if
(
name
==
)
{
throw
new
NullPointerException
(
"name == null"
)
;
}
if
(
deferredName
!=
)
{
throw
new
IllegalStateException
(
)
;
}
deferredName
=
name
;
return
this
;
}

Encodes the property name.

@param name the name of the forthcoming value. May not be null.
@return this writer.


public JsonElement parse(Reader json) throws JsonIOException, JsonSyntaxException {
    try {
      JsonReader jsonReader = new JsonReader(json);
      JsonElement element = parse(jsonReader);
      if (!element.isJsonNull() && jsonReader.peek() != JsonToken.END_DOCUMENT) {
        throw new JsonSyntaxException("Did not consume the entire document.");
      }
      return element;
    } catch (MalformedJsonException e) {
      throw new JsonSyntaxException(e);
    } catch (IOException e) {
      throw new JsonIOException(e);
    } catch (NumberFormatException e) {
      throw new JsonSyntaxException(e);
    }
  }

public
JsonElement
parse
(
Reader
json
)
throws
JsonIOException
,
JsonSyntaxException
{
try
{
JsonReader
jsonReader
=
new
JsonReader
(
json
)
;
JsonElement
element
=
parse
(
jsonReader
)
;
if
(
!
element
.
isJsonNull
(
)
&&
jsonReader
.
peek
(
)
!=
JsonToken
.
END_DOCUMENT
)
{
throw
new
JsonSyntaxException
(
"Did not consume the entire document."
)
;
}
return
element
;
}
catch
(
MalformedJsonException
e
)
{
throw
new
JsonSyntaxException
(
e
)
;
}
catch
(
IOException
e
)
{
throw
new
JsonIOException
(
e
)
;
}
catch
(
NumberFormatException
e
)
{
throw
new
JsonSyntaxException
(
e
)
;
}
}

Parses the specified JSON string into a parse tree

@param json JSON text
@return a parse tree of {@link JsonElement}s corresponding to the specified JSON
@throws JsonParseException if the specified text is not valid JSON
@since 1.3


public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException {
    boolean lenient = json.isLenient();
    json.setLenient(true);
    try {
      return Streams.parse(json);
    } catch (StackOverflowError e) {
      throw new JsonParseException("Failed parsing JSON source: " + json + " to Json", e);
    } catch (OutOfMemoryError e) {
      throw new JsonParseException("Failed parsing JSON source: " + json + " to Json", e);
    } catch (JsonParseException e) {
      if (e.getCause() instanceof EOFException) {
        return JsonNull.INSTANCE;
      }
      throw e;
    } finally {
      json.setLenient(lenient);
    }
  }

public
JsonElement
parse
(
JsonReader
json
)
throws
JsonIOException
,
JsonSyntaxException
{
boolean
lenient
=
json
.
isLenient
(
)
;
json
.
setLenient
(
true
)
;
try
{
return
Streams
.
parse
(
json
)
;
}
catch
(
StackOverflowError
e
)
{
throw
new
JsonParseException
(
"Failed parsing JSON source: "
+
json
+
" to Json"
,
e
)
;
}
catch
(
OutOfMemoryError
e
)
{
throw
new
JsonParseException
(
"Failed parsing JSON source: "
+
json
+
" to Json"
,
e
)
;
}
catch
(
JsonParseException
e
)
{
if
(
e
.
getCause
(
)
instanceof
EOFException
)
{
return
JsonNull
.
INSTANCE
;
}
throw
e
;
}
finally
{
json
.
setLenient
(
lenient
)
;
}
}

Returns the next value from the JSON stream as a parse tree.

@throws JsonParseException if there is an IOException or if the specified
text is not valid JSON
@since 1.6

Returns the next value from the JSON stream as a parse tree .


public static void link (Activity context, String token, String secret, SocializeAuthListener listener) {
		proxy.link(context, token, secret, listener);
	}

public static void link ( Activity context , String token , String secret , SocializeAuthListener listener ) { proxy . link ( context , token , secret , listener ) ; }

Links the current user to their Twitter account using an existing Twitter oAuth token and secret.
@param context The current activity.
@param token The user's Twitter token.
@param secret The user's Twitter token secret.
@param listener A listener to handle the result.

Links the current user to their Twitter account using an existing Twitter oAuth token and secret .


public static void setCredentials(Context context, String consumerKey, String consumerSecret) {
		proxy.setCredentials(context, consumerKey, consumerSecret);
	}

public static void setCredentials ( Context context , String consumerKey , String consumerSecret ) { proxy . setCredentials ( context , consumerKey , consumerSecret ) ; }

Sets the Twitter App credentials for the application.  This sets the same configuration properties as twitter.consumer.key and twitter.consumer.secret
@param context The current context.
@param consumerKey The Twitter App Consumer Key
@param consumerSecret The Twitter App Consumer Secret

Sets the Twitter App credentials for the application . This sets the same configuration properties as twitter . consumer . key and twitter . consumer . secret


public static void tweetEntity(final Activity context, final Entity entity, final String text, final SocialNetworkShareListener listener) {
		if(proxy.isLinked(context)) {
			proxy.tweetEntity(context, entity, text, listener);
		}
		else {
			proxy.link(context, new SocializeAuthListener() {

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

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

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

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

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

"Tweets" an entity.  A "share" event will be recorded in Socialize and the entity URL generated by Socialize will be posted to the user's Twitter feed.
If the user is not currently linked to a Twitter account they will be prompted to authenticate.
@param context The current activity.
@param entity The entity to be tweeted.
@param text The text to be posted along with the tweet.
@param listener A listener to handle the result.

Tweets an entity . A share event will be recorded in Socialize and the entity URL generated by Socialize will be posted to the user s Twitter feed . If the user is not currently linked to a Twitter account they will be prompted to authenticate .


public static void get(final Activity context, final String resource, final Map<String, Object> params, final SocialNetworkPostListener listener) {
		if(proxy.isLinked(context)) {
			proxy.get(context, resource, params, listener);
		}
		else {
			proxy.link(context, new SocializeAuthListener() {

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

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

				@Override
				public void onAuthSuccess(SocializeSession session) {
					proxy.get(context, resource, params, listener);
				}

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

public static void get ( final Activity context , final String resource , final Map < String , Object > params , final SocialNetworkPostListener listener ) { if ( proxy . isLinked ( context ) ) { proxy . get ( context , resource , params , listener ) ; } else { proxy . link ( context , new SocializeAuthListener ( ) { @ Override public void onError ( SocializeException error ) { if ( listener != null ) { listener . onNetworkError ( context , SocialNetwork . TWITTER , error ) ; } } @ Override public void onCancel ( ) { if ( listener != null ) { listener . onCancel ( ) ; } } @ Override public void onAuthSuccess ( SocializeSession session ) { proxy . get ( context , resource , params , listener ) ; } @ Override public void onAuthFail ( SocializeException error ) { if ( listener != null ) { listener . onNetworkError ( context , SocialNetwork . TWITTER , error ) ; } } } ) ; } }

Performs a simple HTTP GET to the Twitter resource endpoint specified. If the user is not currently linked to a Twitter account they will be prompted to authenticate.
@param context The current Activity.
@param resource The resource to be called.  NOTE: This should NOT include the full url (e.g. http://api.twitter.com) but just the resource.
Changing the full URL endpoint can be done via the SocialNetworkPostListener onBeforePost callback.
@param params The parameters to be posted.
@param listener A listener to handle the result.

Performs a simple HTTP GET to the Twitter resource endpoint specified . If the user is not currently linked to a Twitter account they will be prompted to authenticate .


public static void tweet(final Activity context, final Tweet tweet, final SocialNetworkListener listener) {
		if(proxy.isLinked(context)) {
			proxy.tweet(context, tweet, listener);
		}
		else {
			proxy.link(context, new SocializeAuthListener() {

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

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

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

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

public static void tweet ( final Activity context , final Tweet tweet , final SocialNetworkListener listener ) { if ( proxy . isLinked ( context ) ) { proxy . tweet ( context , tweet , listener ) ; } else { proxy . link ( context , new SocializeAuthListener ( ) { @ Override public void onError ( SocializeException error ) { if ( listener != null ) { listener . onNetworkError ( context , SocialNetwork . TWITTER , error ) ; } } @ Override public void onCancel ( ) { if ( listener != null ) { listener . onCancel ( ) ; } } @ Override public void onAuthSuccess ( SocializeSession session ) { proxy . tweet ( context , tweet , listener ) ; } @ Override public void onAuthFail ( SocializeException error ) { if ( listener != null ) { listener . onNetworkError ( context , SocialNetwork . TWITTER , error ) ; } } } ) ; } }

Performs a simple "tweet". If the user is not currently linked to a Twitter account they will be prompted to authenticate.
@param context The current Activity.
@param tweet The Tweet to be tweeted.
@param listener A listener to handle the result.

Performs a simple tweet . If the user is not currently linked to a Twitter account they will be prompted to authenticate .


public static void tweetPhoto(final Activity context, final PhotoTweet photo, final SocialNetworkPostListener listener) {
		if(proxy.isLinked(context)) {
			proxy.tweetPhoto(context, photo, listener);
		}
		else {
			proxy.link(context, new SocializeAuthListener() {

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

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

				@Override
				public void onAuthSuccess(SocializeSession session) {
					proxy.tweetPhoto(context, photo, listener);
				}

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

public static void tweetPhoto ( final Activity context , final PhotoTweet photo , final SocialNetworkPostListener listener ) { if ( proxy . isLinked ( context ) ) { proxy . tweetPhoto ( context , photo , listener ) ; } else { proxy . link ( context , new SocializeAuthListener ( ) { @ Override public void onError ( SocializeException error ) { if ( listener != null ) { listener . onNetworkError ( context , SocialNetwork . TWITTER , error ) ; } } @ Override public void onCancel ( ) { if ( listener != null ) { listener . onCancel ( ) ; } } @ Override public void onAuthSuccess ( SocializeSession session ) { proxy . tweetPhoto ( context , photo , listener ) ; } @ Override public void onAuthFail ( SocializeException error ) { if ( listener != null ) { listener . onNetworkError ( context , SocialNetwork . TWITTER , error ) ; } } } ) ; } }

Publishes a photo to a user's Twitter feed.  If the user is not currently linked to a Twitter account they will be prompted to authenticate.
@param context The current Activity.
@param photo The image to be tweeted.
@param listener A listener to handle the result.

Publishes a photo to a user s Twitter feed . If the user is not currently linked to a Twitter account they will be prompted to authenticate .


public Bitmap getScaledBitmap(Bitmap bitmap, int scaleToWidth, int scaleToHeight, boolean recycleOriginal, int density) {

		bitmap.setDensity(density);
		Bitmap original = bitmap;

		if (scaleToWidth > 0 || scaleToHeight > 0) {

			int width = bitmap.getWidth();
			int height = bitmap.getHeight();

			// scale lowest and crop highes
			if (height != scaleToHeight || width != scaleToWidth) {

				float ratio = 1.0f;

				// Scale to smallest
				if (height > width) {

					ratio = (float) scaleToWidth / (float) width;
					width = scaleToWidth;
					height = Math.round((float) height * ratio);

					bitmap = bitmapBuilder.scale(bitmap, width, height);

					width = bitmap.getWidth();
					height = bitmap.getHeight();

					if (height > scaleToHeight) {
						// crop height
						int diff = height - scaleToHeight;
						int half = Math.round((float) diff / 2.0f);

						bitmap = bitmapBuilder.crop(bitmap, 0, half, width, scaleToHeight);
					}
				}
				else {

					ratio = (float) scaleToHeight / (float) height;
					height = scaleToHeight;
					width = Math.round((float) width * ratio);

					bitmap = bitmapBuilder.scale(bitmap, width, height);

					width = bitmap.getWidth();
					height = bitmap.getHeight();

					if (width > scaleToWidth) {
						// crop width
						int diff = width - scaleToWidth;
						int half = Math.round((float) diff / 2.0f);
						bitmap = bitmapBuilder.crop(bitmap, half, 0, scaleToWidth, height);
					}
				}

				if(recycleOriginal) {
					original.recycle();
				}
			}
		}

		return bitmap;
	}

public
Bitmap
getScaledBitmap
(
Bitmap
bitmap
,
int
scaleToWidth
,
int
scaleToHeight
,
boolean
recycleOriginal
,
int
density
)
{
bitmap
.
setDensity
(
density
)
;
Bitmap
original
=
bitmap
;
if
(
scaleToWidth
>
0
||
scaleToHeight
>
0
)
{
int
width
=
bitmap
.
getWidth
(
)
;
int
height
=
bitmap
.
getHeight
(
)
;
// scale lowest and crop highes
if
(
height
!=
scaleToHeight
||
width
!=
scaleToWidth
)
{
float
ratio
=
1.0f
;
// Scale to smallest
if
(
height
>
width
)
{
ratio
=
(
float
)
scaleToWidth
/
(
float
)
width
;
width
=
scaleToWidth
;
height
=
Math
.
round
(
(
float
)
height
*
ratio
)
;
bitmap
=
bitmapBuilder
.
scale
(
bitmap
,
width
,
height
)
;
width
=
bitmap
.
getWidth
(
)
;
height
=
bitmap
.
getHeight
(
)
;
if
(
height
>
scaleToHeight
)
{
// crop height
int
diff
=
height
scaleToHeight
;
int
half
=
Math
.
round
(
(
float
)
diff
/
2.0f
)
;
bitmap
=
bitmapBuilder
.
crop
(
bitmap
,
0
,
half
,
width
,
scaleToHeight
)
;
}
}
else
{
ratio
=
(
float
)
scaleToHeight
/
(
float
)
height
;
height
=
scaleToHeight
;
width
=
Math
.
round
(
(
float
)
width
*
ratio
)
;
bitmap
=
bitmapBuilder
.
scale
(
bitmap
,
width
,
height
)
;
width
=
bitmap
.
getWidth
(
)
;
height
=
bitmap
.
getHeight
(
)
;
if
(
width
>
scaleToWidth
)
{
// crop width
int
diff
=
width
scaleToWidth
;
int
half
=
Math
.
round
(
(
float
)
diff
/
2.0f
)
;
bitmap
=
bitmapBuilder
.
crop
(
bitmap
,
half
,
0
,
scaleToWidth
,
height
)
;
}
}
if
(
recycleOriginal
)
{
original
.
recycle
(
)
;
}
}
}
return
bitmap
;
}

Returns a scaled bitmap, cropped if necessary.
@param bitmap
@param scaleToWidth
@param scaleToHeight
@param recycleOriginal
@return

Returns a scaled bitmap cropped if necessary .


@SuppressWarnings("unchecked")
	public void putAsPostAsync(SocializeSession session, String endpoint, T object, SocializeActionListener listener) {
		AsyncPutter poster = new AsyncPutter(session, listener);
		SocializePutRequest<T> request = new SocializePutRequest<T>();
		request.setRequestType(RequestType.PUT_AS_POST);
		request.setEndpoint(endpoint);
		request.setObject(object);
		poster.execute(request);
	}

@ SuppressWarnings ( "unchecked" ) public void putAsPostAsync ( SocializeSession session , String endpoint , T object , SocializeActionListener listener ) { AsyncPutter poster = new AsyncPutter ( session , listener ) ; SocializePutRequest < T > request = new SocializePutRequest < T > ( ) ; request . setRequestType ( RequestType . PUT_AS_POST ) ; request . setEndpoint ( endpoint ) ; request . setObject ( object ) ; poster . execute ( request ) ; }

Does a POST, but expects a single object in return.
@param session
@param endpoint
@param object
@param listener

Does a POST but expects a single object in return .


public void setTextSize(int textSize) {
		if(textView != null) {
			textView.setTextSize(android.util.TypedValue.COMPLEX_UNIT_DIP, textSize);
		}

		this.textSize = textSize;
	}

public void setTextSize ( int textSize ) { if ( textView != null ) { textView . setTextSize ( android . util . TypedValue . COMPLEX_UNIT_DIP , textSize ) ; } this . textSize = textSize ; }

Set the text size in DIP
@param textSize


public void onImageChange(Bitmap bitmap, String localPath) {
		if(profileLayoutView != null) {
			profileLayoutView.onImageChange(bitmap);
		}

		// Set the image in the user settings
		try {
			UserUtils.getUserSettings(getContext()).setLocalImagePath(localPath);
		}
		catch (SocializeException e) {
			Log.e(SocializeLogger.LOG_TAG, "Error getting user settings", e);
		}
	}

public
void
onImageChange
(
Bitmap
bitmap
,
String
localPath
)
{
if
(
profileLayoutView
!=
)
{
profileLayoutView
.
onImageChange
(
bitmap
)
;
}
// Set the image in the user settings
try
{
UserUtils
.
getUserSettings
(
getContext
(
)
)
.
setLocalImagePath
(
localPath
)
;
}
catch
(
SocializeException
e
)
{
Log
.
e
(
SocializeLogger
.
LOG_TAG
,
"Error getting user settings"
,
e
)
;
}
}

Called when the user's profile image is changed.
@param bitmap The image.

Called when the user s profile image is changed .


public static void saveUserAsync(Context context, User user, UserSaveListener listener) {
		proxy.saveUserAsync(context, user, listener);
	}

public static void saveUserAsync ( Context context , User user , UserSaveListener listener ) { proxy . saveUserAsync ( context , user , listener ) ; }

Saves the given user.
@param context The current context.
@param user The user to be saved.
@param listener A listener to handle the result.


public static void getUser(Context context, long id, UserGetListener listener) {
		proxy.getUser(context, id, listener);
	}

public static void getUser ( Context context , long id , UserGetListener listener ) { proxy . getUser ( context , id , listener ) ; }

Retrieves a User based on the given ID.
@param context The current context.
@param id The id of the user.
@param listener A listener to handle the GET.

Retrieves a User based on the given ID .


public static void saveUserSettings (Context context, UserSettings userSettings, UserSaveListener listener) {
		proxy.saveUserSettings(context, userSettings, listener);
	}

public static void saveUserSettings ( Context context , UserSettings userSettings , UserSaveListener listener ) { proxy . saveUserSettings ( context , userSettings , listener ) ; }

Saves the profile for the given user.
@param context The current context.
@param userSettings The user settings to be saved.
@param listener A listener to handle the save.


@Deprecated
	public boolean setAutoPostPreferences(SocialNetwork...networks) {

		boolean tw = isAutoPostToTwitter();
		boolean fb = isAutoPostToFacebook();

		setAutoPostToFacebook(false);
		setAutoPostToTwitter(false);
		if(networks != null) {
			for (SocialNetwork network : networks) {
				if(network.equals(SocialNetwork.FACEBOOK)) {
					setAutoPostToFacebook(true);
				}
				else if(network.equals(SocialNetwork.TWITTER)) {
					setAutoPostToTwitter(true);
				}
			}
		}

		return tw != isAutoPostToTwitter() || fb != isAutoPostToFacebook();
	}

@ Deprecated public boolean setAutoPostPreferences ( SocialNetwork ... networks ) { boolean tw = isAutoPostToTwitter ( ) ; boolean fb = isAutoPostToFacebook ( ) ; setAutoPostToFacebook ( false ) ; setAutoPostToTwitter ( false ) ; if ( networks != null ) { for ( SocialNetwork network : networks ) { if ( network . equals ( SocialNetwork . FACEBOOK ) ) { setAutoPostToFacebook ( true ) ; } else if ( network . equals ( SocialNetwork . TWITTER ) ) { setAutoPostToTwitter ( true ) ; } } } return tw != isAutoPostToTwitter ( ) || fb != isAutoPostToFacebook ( ) ; }

Sets the auto post preferences for the user.
@param networks
@return true if the new settings differed from the old ones.

Sets the auto post preferences for the user .


@Deprecated
	public void authenticate(Activity context) {
		authenticate(context, FacebookFacade.DEFAULT_PERMISSIONS, true, false);
	}

@ Deprecated public void authenticate ( Activity context ) { authenticate ( context , FacebookFacade . DEFAULT_PERMISSIONS , true , false ) ; }

Authenticates with default permissions and Single Sign On.

Authenticates with default permissions and Single Sign On .


public void authenticateForRead(Activity context, boolean sso, String[] permissions) {
		authenticate(context, permissions, sso, true);
	}

public void authenticateForRead ( Activity context , boolean sso , String [ ] permissions ) { authenticate ( context , permissions , sso , true ) ; }


@SuppressWarnings("unchecked")
	public static final <E extends Object> E getStaticField(String fieldName, Class<?> clazz) throws Exception {

		try {
			Field field = clazz.getField(fieldName);

			if(field != null) {
				return (E) field.get(null);
			}

		} catch (Exception e) {
			throw e;
		}

		return null;
	}

@ SuppressWarnings ( "unchecked" ) public static final < E extends Object > E getStaticField ( String fieldName , Class < ? > clazz ) throws Exception { try { Field field = clazz . getField ( fieldName ) ; if ( field != null ) { return ( E ) field . get ( null ) ; } } catch ( Exception e ) { throw e ; } return null ; }

Gets the value of the given static field from the given class.
@param fieldName
@param clazz
@return
@throws Exception

Gets the value of the given static field from the given class .


public static final String getStaticFieldName(Object value, Class<?> clazz) throws Exception {
		Field[] fields = clazz.getFields();
		for (Field field : fields) {
			Object fVal = field.get(null);
			if(fVal != null && fVal.equals(value)) {
				return field.getName();
			}
		}
		return null;
	}

public static final String getStaticFieldName ( Object value , Class < ? > clazz ) throws Exception { Field [ ] fields = clazz . getFields ( ) ; for ( Field field : fields ) { Object fVal = field . get ( null ) ; if ( fVal != null && fVal . equals ( value ) ) { return field . getName ( ) ; } } return null ; }

Returns the name of the static field that corresponds to the given value
@param value
@param clazz
@return
@throws Exception


public static boolean onMessage(Context context, Intent intent) {
		assertInitialized(context);

		Bundle messageData = intent.getExtras();

		if(messageData != null) {
			String source = messageData.getString(C2DMCallback.SOURCE_KEY);
			if(source != null && source.trim().equalsIgnoreCase(C2DMCallback.SOURCE_SOCIALIZE)) {
				handler.onMessage(context, intent);
				return true;
			}
		}

		return false;
	}

public static boolean onMessage ( Context context , Intent intent ) { assertInitialized ( context ) ; Bundle messageData = intent . getExtras ( ) ; if ( messageData != null ) { String source = messageData . getString ( C2DMCallback . SOURCE_KEY ) ; if ( source != null && source . trim ( ) . equalsIgnoreCase ( C2DMCallback . SOURCE_SOCIALIZE ) ) { handler . onMessage ( context , intent ) ; return true ; } } return false ; }

Handles a GCM message.  Returns true ONLY if this message was intended for Socialize.
@param context
@param intent
@return

Handles a GCM message . Returns true ONLY if this message was intended for Socialize .


public static boolean handleBroadcastIntent(Context context, Intent intent) {
		return Socialize.getSocialize().handleBroadcastIntent(context, intent);
	}

public static boolean handleBroadcastIntent ( Context context , Intent intent ) { return Socialize . getSocialize ( ) . handleBroadcastIntent ( context , intent ) ; }

Handles a broadcast intent received by a Broadcast Receiver on Android.
Call this method if you already have a broadcast receiver defined but want to also utilize Socialize SmartAlerts.
@param context The current context.
@param intent The broadcast intent provided by Android.
@return Returns true if Socialize handled the intent.  This indicates the intent was designed to be handled by Socialize and you do not need to handle it yourself.

Handles a broadcast intent received by a Broadcast Receiver on Android . Call this method if you already have a broadcast receiver defined but want to also utilize Socialize SmartAlerts .


public byte[] encode(byte[] source, int off, int len, byte[] alphabet,
      int maxLineLength) {
    int lenDiv3 = (len + 2) / 3; // ceil(len / 3)
    int len43 = lenDiv3 * 4;
    byte[] outBuff = new byte[len43 // Main 4:3
        + (len43 / maxLineLength)]; // New lines

    int d = 0;
    int e = 0;
    int len2 = len - 2;
    int lineLength = 0;
    for (; d < len2; d += 3, e += 4) {

      // The following block of code is the same as
      // encode3to4( source, d + off, 3, outBuff, e, alphabet );
      // but inlined for faster encoding (~20% improvement)
      int inBuff =
          ((source[d + off] << 24) >>> 8)
              | ((source[d + 1 + off] << 24) >>> 16)
              | ((source[d + 2 + off] << 24) >>> 24);
      outBuff[e] = alphabet[(inBuff >>> 18)];
      outBuff[e + 1] = alphabet[(inBuff >>> 12) & 0x3f];
      outBuff[e + 2] = alphabet[(inBuff >>> 6) & 0x3f];
      outBuff[e + 3] = alphabet[(inBuff) & 0x3f];

      lineLength += 4;
      if (lineLength == maxLineLength) {
        outBuff[e + 4] = NEW_LINE;
        e++;
        lineLength = 0;
      } // end if: end of line
    } // end for: each piece of array

    if (d < len) {
      encode3to4(source, d + off, len - d, outBuff, e, alphabet);

      lineLength += 4;
      if (lineLength == maxLineLength) {
        // Add a last newline
        outBuff[e + 4] = NEW_LINE;
        e++;
      }
      e += 4;
    }

    assert (e == outBuff.length);
    return outBuff;
  }

Encodes a byte array into Base64 notation.

@param source The data to convert
@param off Offset in array where conversion should begin
@param len Length of data to convert
@param alphabet is the encoding alphabet
@param maxLineLength maximum length of one line.
@return the BASE64-encoded byte array

Encodes a byte array into Base64 notation .


public byte[] decode(byte[] source, int off, int len, byte[] decodabet)
      throws Base64DecoderException {
    int len34 = len * 3 / 4;
    byte[] outBuff = new byte[2 + len34]; // Upper limit on size of output
    int outBuffPosn = 0;

    byte[] b4 = new byte[4];
    int b4Posn = 0;
    int i = 0;
    byte sbiCrop = 0;
    byte sbiDecode = 0;
    for (i = 0; i < len; i++) {
      sbiCrop = (byte) (source[i + off] & 0x7f); // Only the low seven bits
      sbiDecode = decodabet[sbiCrop];

      if (sbiDecode >= WHITE_SPACE_ENC) { // White space Equals sign or better
        if (sbiDecode >= EQUALS_SIGN_ENC) {
          // An equals sign (for padding) must not occur at position 0 or 1
          // and must be the last byte[s] in the encoded value
          if (sbiCrop == EQUALS_SIGN) {
            int bytesLeft = len - i;
            byte lastByte = (byte) (source[len - 1 + off] & 0x7f);
            if (b4Posn == 0 || b4Posn == 1) {
              throw new Base64DecoderException(
                  "invalid padding byte '=' at byte offset " + i);
            } else if ((b4Posn == 3 && bytesLeft > 2)
                || (b4Posn == 4 && bytesLeft > 1)) {
              throw new Base64DecoderException(
                  "padding byte '=' falsely signals end of encoded value "
                      + "at offset " + i);
            } else if (lastByte != EQUALS_SIGN && lastByte != NEW_LINE) {
              throw new Base64DecoderException(
                  "encoded value has invalid trailing byte");
            }
            break;
          }

          b4[b4Posn++] = sbiCrop;
          if (b4Posn == 4) {
            outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet);
            b4Posn = 0;
          }
        }
      } else {
        throw new Base64DecoderException("Bad Base64 input character at " + i
            + ": " + source[i + off] + "(decimal)");
      }
    }

    // Because web safe encoding allows non padding base64 encodes, we
    // need to pad the rest of the b4 buffer with equal signs when
    // b4Posn != 0.  There can be at most 2 equal signs at the end of
    // four characters, so the b4 buffer must have two or three
    // characters.  This also catches the case where the input is
    // padded with EQUALS_SIGN
    if (b4Posn != 0) {
      if (b4Posn == 1) {
        throw new Base64DecoderException("single trailing character at offset "
            + (len - 1));
      }
      b4[b4Posn++] = EQUALS_SIGN;
      outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet);
    }

    byte[] out = new byte[outBuffPosn];
    System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
    return out;
  }

Decodes Base64 content using the supplied decodabet and returns
the decoded byte array.

@param source    The Base64 encoded data
@param off       The offset of where to begin decoding
@param len       The length of characters to decode
@param decodabet the decodabet for decoding Base64 content
@return decoded data

Decodes Base64 content using the supplied decodabet and returns the decoded byte array .


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

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

Records a view against the given entity for the current user.
@param context The current context.
@param e The entity to be viewed.
@param listener A listener to handle the result.

Records a view against the given entity for the current user .


public void onProfileUpdate() {
		commentAdapter.notifyDataSetChanged();

		if(commentEntrySlider != null) {
			commentEntrySlider.updateContent();
		}

		if(notifyBox != null) {
			try {
				UserSettings user = userUtils.getUserSettings(getContext());
				if(user.isNotificationsEnabled()) {
					notifyBox.setVisibility(View.VISIBLE);
				}
				else {
					notifyBox.setVisibility(View.GONE);
				}
			}
			catch (SocializeException e) {
				if(logger != null) {
					logger.error("Error getting user settings", e);
				}
				else {
					e.printStackTrace();
				}

				notifyBox.setVisibility(View.GONE);
			}
		}
	}

public
void
onProfileUpdate
(
)
{
commentAdapter
.
notifyDataSetChanged
(
)
;
if
(
commentEntrySlider
!=
)
{
commentEntrySlider
.
updateContent
(
)
;
}
if
(
notifyBox
!=
)
{
try
{
UserSettings
user
=
userUtils
.
getUserSettings
(
getContext
(
)
)
;
if
(
user
.
isNotificationsEnabled
(
)
)
{
notifyBox
.
setVisibility
(
View
.
VISIBLE
)
;
}
else
{
notifyBox
.
setVisibility
(
View
.
GONE
)
;
}
}
catch
(
SocializeException
e
)
{
if
(
logger
!=
)
{
logger
.
error
(
"Error getting user settings"
,
e
)
;
}
else
{
e
.
printStackTrace
(
)
;
}
notifyBox
.
setVisibility
(
View
.
GONE
)
;
}
}
}

Called when the current logged in user updates their profile.

Called when the current logged in user updates their profile .


public static HttpParameters decodeForm(String form) {
        HttpParameters params = new HttpParameters();
        if (isEmpty(form)) {
            return params;
        }
        for (String nvp : form.split("\\&")) {
            int equals = nvp.indexOf('=');
            String name;
            String value;
            if (equals < 0) {
                name = percentDecode(nvp);
                value = null;
            } else {
                name = percentDecode(nvp.substring(0, equals));
                value = percentDecode(nvp.substring(equals + 1));
            }

            params.put(name, value);
        }
        return params;
    }

public static HttpParameters decodeForm ( String form ) { HttpParameters params = new HttpParameters ( ) ; if ( isEmpty ( form ) ) { return params ; } for ( String nvp : form . split ( "\\&" ) ) { int equals = nvp . indexOf ( ' ' ) ; String name ; String value ; if ( equals < 0 ) { name = percentDecode ( nvp ) ; value = null ; } else { name = percentDecode ( nvp . substring ( 0 , equals ) ) ; value = percentDecode ( nvp . substring ( equals + 1 ) ) ; } params . put ( name , value ) ; } return params ; }


public static <T extends Map.Entry<String, String>> Map<String, String> toMap(Collection<T> from) {
        HashMap<String, String> map = new HashMap<String, String>();
        if (from != null) {
            for (Map.Entry<String, String> entry : from) {
                String key = entry.getKey();
                if (!map.containsKey(key)) {
                    map.put(key, entry.getValue());
                }
            }
        }
        return map;
    }

public static < T extends Map . Entry < String , String > > Map < String , String > toMap ( Collection < T > from ) { HashMap < String , String > map = new HashMap < String , String > ( ) ; if ( from != null ) { for ( Map . Entry < String , String > entry : from ) { String key = entry . getKey ( ) ; if ( ! map . containsKey ( key ) ) { map . put ( key , entry . getValue ( ) ) ; } } } return map ; }

Construct a Map containing a copy of the given parameters. If several
parameters have the same name, the Map will contain the first value,
only.

Construct a Map containing a copy of the given parameters . If several parameters have the same name the Map will contain the first value only .


public static String toHeaderElement(String name, String value) {
        return OAuth.percentEncode(name) + "=\"" + OAuth.percentEncode(value) + "\"";
    }

public static String toHeaderElement ( String name , String value ) { return OAuth . percentEncode ( name ) + "=\"" + OAuth . percentEncode ( value ) + "\"" ; }

Helper method to concatenate a parameter and its value to a pair that can
be used in an HTTP header. This method percent encodes both parts before
joining them.

@param name
the OAuth parameter name, e.g. oauth_token
@param value
the OAuth parameter value, e.g. 'hello oauth'
@return a name/value pair, e.g. oauth_token="hello%20oauth"

Helper method to concatenate a parameter and its value to a pair that can be used in an HTTP header . This method percent encodes both parts before joining them .


public boolean put(K strKey, E object, long ttl) {
		return put(strKey, object, ttl, false);
	}

public boolean put ( K strKey , E object , long ttl ) { return put ( strKey , object , ttl , false ) ; }

Adds an object to cache with the given time-to-live
@param strKey
@param object
@param ttl

Adds an object to cache with the given time - to - live


public boolean put(K strKey, E object, boolean eternal) {
		return put(strKey, object, defaultTTL, eternal);
	}

public boolean put ( K strKey , E object , boolean eternal ) { return put ( strKey , object , defaultTTL , eternal ) ; }

Adds an object to cache that optionally lives forever.
@param strKey
@param object
@param eternal
@return

Adds an object to cache that optionally lives forever .


protected synchronized boolean put(K k, E object, long ttl, boolean eternal) {

		// Check the key map first
		if(exists(k)) {
			TTLObject<K, E> ttlObject = getTTLObject(k);

			Key<K> key = keys.get(k);
			key.setTime(System.currentTimeMillis());

			ttlObject.setEternal(eternal);
			ttlObject.extendLife(ttl);
			ttlObject.setObject(object);

			if(eventListener != null) {
				eventListener.onPut(object);
			}

			return true;
		}
		else {
			TTLObject<K, E> t = new TTLObject<K, E>(object, k, ttl);

			t.setEternal(eternal);

			long addedSize = object.getSizeInBytes();
			long newSize = currentSizeInBytes + addedSize;
			boolean oversize = false;

			oversize = (hardByteLimit && maxCapacityBytes > 0 && newSize > maxCapacityBytes);

			if(!oversize) {
				Key<K> key = new Key<K>(k, System.currentTimeMillis());
				keys.put(k, key);
				objects.put(key, t);

				t.getObject().onPut(k);

				// Increment size
				currentSizeInBytes = newSize;

				if(eventListener != null) {
					eventListener.onPut(object);
				}

				return true;
			}
		}

		return false;
	}

protected
synchronized
boolean
put
(
K
k
,
E
object
,
long
ttl
,
boolean
eternal
)
{
// Check the key map first
if
(
exists
(
k
)
)
{
TTLObject
<
K
,
E
>
ttlObject
=
getTTLObject
(
k
)
;
Key
<
K
>
key
=
keys
.
get
(
k
)
;
key
.
setTime
(
System
.
currentTimeMillis
(
)
)
;
ttlObject
.
setEternal
(
eternal
)
;
ttlObject
.
extendLife
(
ttl
)
;
ttlObject
.
setObject
(
object
)
;
if
(
eventListener
!=
)
{
eventListener
.
onPut
(
object
)
;
}
return
true
;
}
else
{
TTLObject
<
K
,
E
>
t
=
new
TTLObject
<
K
,
E
>
(
object
,
k
,
ttl
)
;
t
.
setEternal
(
eternal
)
;
long
addedSize
=
object
.
getSizeInBytes
(
)
;
long
newSize
=
currentSizeInBytes
+
addedSize
;
boolean
oversize
=
false
;
oversize
=
(
hardByteLimit
&&
maxCapacityBytes
>
0
&&
newSize
>
maxCapacityBytes
)
;
if
(
!
oversize
)
{
Key
<
K
>
key
=
new
Key
<
K
>
(
k
,
System
.
currentTimeMillis
(
)
)
;
keys
.
put
(
k
,
key
)
;
objects
.
put
(
key
,
t
)
;
t
.
getObject
(
)
.
onPut
(
k
)
;
// Increment size
currentSizeInBytes
=
newSize
;
if
(
eventListener
!=
)
{
eventListener
.
onPut
(
object
)
;
}
return
true
;
}
}
return
false
;
}

Adds an object to cache with the given Time To Live in milliseconds
@param k
@param object
@param ttl milliseconds
@param eternal


public synchronized E getRaw(K strKey) {
		TTLObject<K, E> obj = getTTLObject(strKey);
		if(obj != null && !isExpired(obj)) {
			return obj.getObject();
		}
		return null;
	}

public synchronized E getRaw ( K strKey ) { TTLObject < K , E > obj = getTTLObject ( strKey ) ; if ( obj != null && ! isExpired ( obj ) ) { return obj . getObject ( ) ; } return null ; }

Ignores proxy and always returns raw object
@param strKey
@return


public synchronized E get(K key) {
		TTLObject<K, E> obj = getTTLObject(key);
		if(obj != null && !isExpired(obj)) {

			if(extendOnGet) {
				extendTTL(key);
			}

			if(eventListener != null) {
				eventListener.onGet(obj.getObject());
			}

			obj.getObject().onGet();

			return obj.getObject();

		}
		else if(obj != null) {
			// Expired
			destroy(obj.getKey());
			obj = null;
		}

		if (obj == null) {
			if(objectFactory != null) {
				E object = objectFactory.create(key);

				if(object != null) {
					if(!put(key, object) && logger != null) {
						// We couldn't put this record.. just log a warning
						logger.warn("Failed to put object into cache. Cache size exceeded");
					}
				}

				return object;
			}
		}

		return null;
	}

Gets an object from cache.  Returns null if the object does not exist, or has expired.
@param key
@return

Gets an object from cache . Returns null if the object does not exist or has expired .


public boolean exists(K k) {
		Key<K> key = keys.get(k);
		if(key != null) {
			return objects.get(key) != null;
		}
		return false;
	}

public boolean exists ( K k ) { Key < K > key = keys . get ( k ) ; if ( key != null ) { return objects . get ( key ) != null ; } return false ; }

Returns true if the object with the given key resides in the cache.
@param k
@return true if the object with the given key resides in the cache.

Returns true if the object with the given key resides in the cache .


public synchronized void extendTTL(K strKey) {
		TTLObject<K, E> object = getTTLObject(strKey);
		if(object != null) {
			object.setLifeExpectancy(System.currentTimeMillis() + object.getTtl());
		}
	}

public synchronized void extendTTL ( K strKey ) { TTLObject < K , E > object = getTTLObject ( strKey ) ; if ( object != null ) { object . setLifeExpectancy ( System . currentTimeMillis ( ) + object . getTtl ( ) ) ; } }

Extends the ttl of the object with the given key with the current system time.
@param strKey

Extends the ttl of the object with the given key with the current system time .


public void loadImageByData(final String name, final String encodedData, int width, int height, final ImageLoadListener listener) {
		ImageLoadRequest request = makeRequest();
		request.setUrl(name);
		request.setEncodedImageData(encodedData);
		request.setType(ImageLoadType.ENCODED);
		loadImage(request, listener);
	}

public void loadImageByData ( final String name , final String encodedData , int width , int height , final ImageLoadListener listener ) { ImageLoadRequest request = makeRequest ( ) ; request . setUrl ( name ) ; request . setEncodedImageData ( encodedData ) ; request . setType ( ImageLoadType . ENCODED ) ; loadImage ( request , listener ) ; }

Loads an image based on Base64 encoded bytes.
@param id The id to give the request
@param name The name to give the image in cache.
@param encodedData The encoded image data.
@param listener A listener to handle the callback.

Loads an image based on Base64 encoded bytes .


public void loadImageByUrl(final String url, int width, int height, final ImageLoadListener listener) {
		ImageLoadRequest request = makeRequest();
		request.setUrl(url);
		request.setType(ImageLoadType.URL);
		request.setScaleWidth(width);
		request.setScaleHeight(height);
		loadImage(request, listener);
	}

public void loadImageByUrl ( final String url , int width , int height , final ImageLoadListener listener ) { ImageLoadRequest request = makeRequest ( ) ; request . setUrl ( url ) ; request . setType ( ImageLoadType . URL ) ; request . setScaleWidth ( width ) ; request . setScaleHeight ( height ) ; loadImage ( request , listener ) ; }

Asynchronously loads the image at the given url and calls the listener when it is loaded.
@param id The id to give the request
@param url The url to be loaded
@param listener A listener to handle the callback.

Asynchronously loads the image at the given url and calls the listener when it is loaded .


public static Map<String, String> parseTags(final String tagString) throws IllegalArgumentException {
        // delimit by whitespace or '='
        Scanner scanner = new Scanner(tagString).useDelimiter("\\s+|=");

        Map<String, String> tagMap = new HashMap<String, String>();
        try {
            while (scanner.hasNext()) {
                String tagName = scanner.next();
                String tagValue = scanner.next();
                tagMap.put(tagName, tagValue);
            }
        } catch (NoSuchElementException e) {
            // The tag string is corrupted.
            throw new IllegalArgumentException("Invalid tag string '" + tagString + "'");
        } finally {
            scanner.close();
        }

        return tagMap;
    }

public
static
Map
<
String
,
String
>
parseTags
(
final
String
tagString
)
throws
IllegalArgumentException
{
// delimit by whitespace or '='
Scanner
scanner
=
new
Scanner
(
tagString
)
.
useDelimiter
(
"\\s+|="
)
;
Map
<
String
,
String
>
tagMap
=
new
HashMap
<
String
,
String
>
(
)
;
try
{
while
(
scanner
.
hasNext
(
)
)
{
String
tagName
=
scanner
.
next
(
)
;
String
tagValue
=
scanner
.
next
(
)
;
tagMap
.
put
(
tagName
,
tagValue
)
;
}
}
catch
(
NoSuchElementException
e
)
{
// The tag string is corrupted.
throw
new
IllegalArgumentException
(
"Invalid tag string '"
+
tagString
+
"'"
)
;
}
finally
{
scanner
.
close
(
)
;
}
return
tagMap
;
}

Convert a tag string into a tag map.

@param tagString a space-delimited string of key-value pairs. For example, {@code "key1=value1 key_n=value_n"}
@return a tag {@link Map}
@throws IllegalArgumentException if the tag string is corrupted.


public static String formatTags(final Map<String, String> tagMap) {
        StringBuilder stringBuilder = new StringBuilder();
        String delimeter = "";

        for (Map.Entry<String, String> tag : tagMap.entrySet()) {
            stringBuilder.append(delimeter)
                    .append(sanitize(tag.getKey()))
                    .append("=")
                    .append(sanitize(tag.getValue()));
            delimeter = " ";
        }

        return stringBuilder.toString();
    }

public
static
String
formatTags
(
final
Map
<
String
,
String
>
tagMap
)
{
StringBuilder
stringBuilder
=
new
StringBuilder
(
)
;
String
delimeter
=
""
;
for
(
Map
.
Entry
<
String
,
String
>
tag
:
tagMap
.
entrySet
(
)
)
{
stringBuilder
.
append
(
delimeter
)
.
append
(
sanitize
(
tag
.
getKey
(
)
)
)
.
append
(
"="
)
.
append
(
sanitize
(
tag
.
getValue
(
)
)
)
;
delimeter
=
" "
;
}
return
stringBuilder
.
toString
(
)
;
}

Convert a tag map into a space-delimited string.

@param tagMap
@return a space-delimited string of key-value pairs. For example, {@code "key1=value1 key_n=value_n"}

Convert a tag map into a space - delimited string .


public static String fixEncodedTagsInNameAfterPrefix(final String name) {
        if (name == null)
            return name;

        int tagStart = name.indexOf("TAG(");

        if (tagStart == -1)
            return name; // no tags in this name

        if (tagStart == 0)
            return name; // tag string is already correct

        // extract the "TAG(...)" string from the middle of the name and put it at the front.
        int tagEnd = name.lastIndexOf(')');
        if (tagEnd == -1) {
            throw new IllegalArgumentException("Tag definition missing closing parenthesis for metric '" + name + "'");
        }

        String tagString = name.substring(tagStart, tagEnd+1);
        return tagString + name.substring(0, tagStart) + name.substring(tagEnd+1);
    }

Call this function whenever a potentially tag-encoded name is prefixed.

@param name a metric name with encoded tag strings that has been prefixed.
@return a fixed metric name

Call this function whenever a potentially tag - encoded name is prefixed .


public static Builder named(String name) {
		/*
		A name can contain either a pure metric name, or a string returned by encodeTagsInName().
		If it's the latter, it looks like "TAG(tag1=value1 tag2=value2)metricname".
		 */
		if (!hasEncodedTagInName(name)) {
            return new Builder(name);
        }

        // parse out the tags
        int tagEnd = name.lastIndexOf(')');
        if (tagEnd == -1) {
            throw new IllegalArgumentException("Tag definition missing closing parenthesis for metric '" + name + "'");
        }

        String tagString = name.substring(4, tagEnd);
        name = name.substring(tagEnd+1);

        return new Builder(name).withTags(parseTags(tagString));
    }

Creates a Builder for a metric name.

@param name name can contain either a pure CodaHale metric name, or a string returned by {@code encodeTagsInName}.
If it's the latter, the tags are parsed out and passed to {@code withTags}.
@return a {@link Builder}


public String toTelnetPutString() {
		String tagString = formatTags(tags);

		return String.format("put %s %d %s %s%n", metric, timestamp, value, tagString);
	}

public
String
toTelnetPutString
(
)
{
String
tagString
=
formatTags
(
tags
)
;
return
String
.
format
(
"put %s %d %s %s%n"
,
metric
,
timestamp
,
value
,
tagString
)
;
}

Returns a put string version of this metric compatible with the telnet-style reporter.

Format:

put (metric-name) (timestamp) (value) (tags)

Example:

put sys.cpu.nice 1346846400 18 host=web01 dc=lga

@return a string version of this metric compatible with the telnet reporter.

Returns a put string version of this metric compatible with the telnet - style reporter .


@Override
    public String toHumanString() {
        if (unicode) {
            return domain;
        }
        final IDNA.Info idnaInfo = new IDNA.Info();
        final StringBuilder idnaOutput = new StringBuilder();
        IDNA.getUTS46Instance(IDNA.DEFAULT).nameToUnicode(domain, idnaOutput, idnaInfo);
        return idnaOutput.toString();
    }

@ Override public String toHumanString ( ) { if ( unicode ) { return domain ; } final IDNA . Info idnaInfo = new IDNA . Info ( ) ; final StringBuilder idnaOutput = new StringBuilder ( ) ; IDNA . getUTS46Instance ( IDNA . DEFAULT ) . nameToUnicode ( domain , idnaOutput , idnaInfo ) ; return idnaOutput . toString ( ) ; }

Converts the domain to a Unicode representation suitable for human interpretation. It does IDNA conversion.

@see Host#toHumanString()
@return unicode string

Converts the domain to a Unicode representation suitable for human interpretation . It does IDNA conversion .


public static String percentDecode(final String input) {
        if (input.isEmpty()) {
            return input;
        }
        try {
            final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            int idx = 0;
            while (idx < input.length()) {

                boolean isEOF = idx >= input.length();
                int c = (isEOF)? 0x00 : input.codePointAt(idx);

                while (!isEOF && c != '%') {
                    if (c <= 0x7F) { // String.getBytes is slow, so do not perform encoding
                                     // if not needed
                        bytes.write((byte) c);
                        idx++;
                    } else {
                        bytes.write(new String(Character.toChars(c)).getBytes(UTF_8));
                        idx += Character.charCount(c);
                    }
                    isEOF = idx >= input.length();
                    c = (isEOF)? 0x00 : input.codePointAt(idx);
                }

                if (c == '%' && (input.length() <= idx + 2 ||
                        !isASCIIHexDigit(input.charAt(idx + 1)) ||
                        !isASCIIHexDigit(input.charAt(idx + 2)))) {
                    if (c <= 0x7F) { // String.getBytes is slow, so do not perform encoding
                        // if not needed
                        bytes.write((byte) c);
                        idx++;
                    } else {
                        bytes.write(new String(Character.toChars(c)).getBytes(UTF_8));
                        idx += Character.charCount(c);
                    }
                } else {
                    while (c == '%' && input.length() > idx + 2 &&
                            isASCIIHexDigit(input.charAt(idx + 1)) &&
                            isASCIIHexDigit(input.charAt(idx + 2))) {
                        bytes.write(hexToInt(input.charAt(idx + 1), input.charAt(idx + 2)));
                        idx += 3;
                        c = (input.length() <= idx)? 0x00 : input.codePointAt(idx);
                    }
                }
            }
            return new String(bytes.toByteArray(), UTF_8);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

Percent-decodes a string.

Percent-encoded bytes are assumed to represent UTF-8 characters.

@see WHATWG URL Standard: Percent-encoded bytes

@param input
@return


public String queryParameter(final String name) {
        if (name == null) {
            throw new NullPointerException("name is null");
        }
        if (query == null || query.isEmpty()) {
            return null;
        }
        int start = 0;
        do {
            final int nextAmpersand = query.indexOf('&', start);
            final int end = (nextAmpersand == -1)? query.length() : nextAmpersand;
            int nextEquals = query.indexOf('=', start);
            if (nextEquals == -1 || nextEquals > end) {
                nextEquals = end;
            }
            final int thisNameLength = nextEquals - start;
            final int thisValueLength = end - nextEquals;
            if (thisNameLength == name.length() && query.regionMatches(start, name, 0, name.length())) {
                if (thisValueLength == 0) {
                    return "";
                }
                return query.substring(nextEquals + 1, end);
            }
            if (nextAmpersand == -1) {
                break;
            }
            start = nextAmpersand + 1;
        } while (true);
        return null;
    }

public
String
queryParameter
(
final
String
name
)
{
if
(
name
==
)
{
throw
new
NullPointerException
(
"name is null"
)
;
}
if
(
query
==
||
query
.
isEmpty
(
)
)
{
return
;
}
int
start
=
0
;
do
{
final
int
nextAmpersand
=
query
.
indexOf
(
'
'
,
start
)
;
final
int
end
=
(
nextAmpersand
==
1
)
query
.
length
(
)
:
nextAmpersand
;
int
nextEquals
=
query
.
indexOf
(
'
'
,
start
)
;
if
(
nextEquals
==
1
||
nextEquals
>
end
)
{
nextEquals
=
end
;
}
final
int
thisNameLength
=
nextEquals
start
;
final
int
thisValueLength
=
end
nextEquals
;
if
(
thisNameLength
==
name
.
length
(
)
&&
query
.
regionMatches
(
start
,
name
,
0
,
name
.
length
(
)
)
)
{
if
(
thisValueLength
==
0
)
{
return
""
;
}
return
query
.
substring
(
nextEquals
+
1
,
end
)
;
}
if
(
nextAmpersand
==
1
)
{
break
;
}
start
=
nextAmpersand
+
1
;
}
while
(
true
)
;
return
;
}

Gets the first query parameter value for a given name.

@see {@link #queryParameters(String)}

@param name Parameter name.
@return The first parameter value or null if there parameter is not present.

Gets the first query parameter value for a given name .


public List<String> queryParameters(final String name) {
        if (name == null) {
            throw new NullPointerException("name is null");
        }
        if (query == null || query.isEmpty()) {
            return null;
        }
        int start = 0;
        final List<String> result = new ArrayList<String>();
        do {
            final int nextAmpersand = query.indexOf('&', start);
            final int end = (nextAmpersand == -1) ? query.length() : nextAmpersand;
            int nextEquals = query.indexOf('=', start);
            if (nextEquals == -1 || nextEquals > end) {
                nextEquals = end;
            }
            final int thisNameLength = nextEquals - start;
            final int thisValueLength = end - nextEquals;
            if (thisNameLength == name.length() && query.regionMatches(start, name, 0, name.length())) {
                if (thisValueLength == 0) {
                    result.add("");
                } else {
                    result.add(query.substring(nextEquals + 1, end));
                }
            }
            if (nextAmpersand == -1) {
                break;
            }
            start = nextAmpersand + 1;
        } while (true);
        return result;
    }

public
List
<
String
>
queryParameters
(
final
String
name
)
{
if
(
name
==
)
{
throw
new
NullPointerException
(
"name is null"
)
;
}
if
(
query
==
||
query
.
isEmpty
(
)
)
{
return
;
}
int
start
=
0
;
final
List
<
String
>
result
=
new
ArrayList
<
String
>
(
)
;
do
{
final
int
nextAmpersand
=
query
.
indexOf
(
'
'
,
start
)
;
final
int
end
=
(
nextAmpersand
==
1
)
query
.
length
(
)
:
nextAmpersand
;
int
nextEquals
=
query
.
indexOf
(
'
'
,
start
)
;
if
(
nextEquals
==
1
||
nextEquals
>
end
)
{
nextEquals
=
end
;
}
final
int
thisNameLength
=
nextEquals
start
;
final
int
thisValueLength
=
end
nextEquals
;
if
(
thisNameLength
==
name
.
length
(
)
&&
query
.
regionMatches
(
start
,
name
,
0
,
name
.
length
(
)
)
)
{
if
(
thisValueLength
==
0
)
{
result
.
add
(
""
)
;
}
else
{
result
.
add
(
query
.
substring
(
nextEquals
+
1
,
end
)
)
;
}
}
if
(
nextAmpersand
==
1
)
{
break
;
}
start
=
nextAmpersand
+
1
;
}
while
(
true
)
;
return
result
;
}

Gets all query parameter values for a given name.

@param name Parameter name.
@return A {@link java.util.List} with all parameter values or null if the parameter is not present.

Gets all query parameter values for a given name .


public String relativize(final URL url) {
        if (this.isOpaque() || url.isOpaque()) {
            return url.toString();
        }
        if (!this.scheme().equals(url.scheme())) {
            return url.toString();
        }
        if (this.authority() == null ^ url.authority() == null) {
            return url.toString();
        }
        if (this.authority() != null && !this.authority().equals(url.authority())) {
            return url.toString();
        }

        String prefixPath = (this.path().endsWith("/"))? this.path : this.path() + "/";

        if (!url.path().startsWith(prefixPath) && !this.path().equals(url.path())) {
            return url.toString();
        }

        StringBuilder output = new StringBuilder();
        if (!this.path().equals(url.path())) {
            output.append(url.path().replaceFirst(prefixPath, ""));
        }
        if (url.query() != null) {
            output.append('?').append(url.query());
        }
        if (url.fragment() != null) {
            output.append('#').append(url.fragment());
        }
        return output.toString();
    }

public String relativize ( final URL url ) { if ( this . isOpaque ( ) || url . isOpaque ( ) ) { return url . toString ( ) ; } if ( ! this . scheme ( ) . equals ( url . scheme ( ) ) ) { return url . toString ( ) ; } if ( this . authority ( ) == null ^ url . authority ( ) == null ) { return url . toString ( ) ; } if ( this . authority ( ) != null && ! this . authority ( ) . equals ( url . authority ( ) ) ) { return url . toString ( ) ; } String prefixPath = ( this . path ( ) . endsWith ( "/" ) ) ? this . path : this . path ( ) + "/" ; if ( ! url . path ( ) . startsWith ( prefixPath ) && ! this . path ( ) . equals ( url . path ( ) ) ) { return url . toString ( ) ; } StringBuilder output = new StringBuilder ( ) ; if ( ! this . path ( ) . equals ( url . path ( ) ) ) { output . append ( url . path ( ) . replaceFirst ( prefixPath , "" ) ) ; } if ( url . query ( ) != null ) { output . append ( ' ' ) . append ( url . query ( ) ) ; } if ( url . fragment ( ) != null ) { output . append ( ' ' ) . append ( url . fragment ( ) ) ; } return output . toString ( ) ; }

Returns a relative URL reference for the given URL.

Behaves as @{link java.net.URI#relativize(URL)}.

@param url Absolute URL.
@return Relative reference.

Returns a relative URL reference for the given URL .


public static URL buildHierarchical(final String scheme, final String host) throws GalimatiasParseException {
        if (!URLUtils.isRelativeScheme(scheme)) {
            throw new GalimatiasParseException("Scheme is not relative: " + scheme);
        }
        return new URLParser(scheme + "://" + host).parse();
    }

public
static
URL
buildHierarchical
(
final
String
scheme
,
final
String
host
)
throws
GalimatiasParseException
{
if
(
!
URLUtils
.
isRelativeScheme
(
scheme
)
)
{
throw
new
GalimatiasParseException
(
"Scheme is not relative: "
+
scheme
)
;
}
return
new
URLParser
(
scheme
+
"://"
+
host
)
.
parse
(
)
;
}

Gets a URL object from a relative scheme and a host.

@param scheme
@param host
@return
@throws GalimatiasParseException

Gets a URL object from a relative scheme and a host .


public static URL buildOpaque(final String scheme) throws GalimatiasParseException {
        if (URLUtils.isRelativeScheme(scheme)) {
            throw new GalimatiasParseException("Scheme is relative: " + scheme);
        }
        return new URLParser(scheme + ":").parse();
    }

public
static
URL
buildOpaque
(
final
String
scheme
)
throws
GalimatiasParseException
{
if
(
URLUtils
.
isRelativeScheme
(
scheme
)
)
{
throw
new
GalimatiasParseException
(
"Scheme is relative: "
+
scheme
)
;
}
return
new
URLParser
(
scheme
+
":"
)
.
parse
(
)
;
}

Gets a URL object from a non-relative scheme.

@param scheme
@return
@throws GalimatiasParseException

Gets a URL object from a non - relative scheme .


public String toHumanString() {
        final StringBuilder output = new StringBuilder();

        output.append(scheme).append(':');

        if (isHierarchical) {
            output.append("//");
            final String userInfo = userInfo();
            if (!userInfo.isEmpty()) {
                output.append(URLUtils.percentDecode(userInfo)).append('@');
            }
            if (host != null) {
                if (host instanceof IPv6Address) {
                    output.append(host.toHostString());
                } else {
                    output.append(host.toHumanString());
                }
            }
            if (port != -1) {
                output.append(':').append(port);
            }
            if (path != null) {
                output.append(URLUtils.percentDecode(path));
            }
        } else {
            output.append(URLUtils.percentDecode(schemeData));
        }

        if (query != null) {
            output.append('?').append(URLUtils.percentDecode(query));
        }

        if (fragment != null) {
            output.append('#').append(URLUtils.percentDecode(fragment));
        }

        return output.toString();
    }

public String toHumanString ( ) { final StringBuilder output = new StringBuilder ( ) ; output . append ( scheme ) . append ( ' ' ) ; if ( isHierarchical ) { output . append ( "//" ) ; final String userInfo = userInfo ( ) ; if ( ! userInfo . isEmpty ( ) ) { output . append ( URLUtils . percentDecode ( userInfo ) ) . append ( ' ' ) ; } if ( host != null ) { if ( host instanceof IPv6Address ) { output . append ( host . toHostString ( ) ) ; } else { output . append ( host . toHumanString ( ) ) ; } } if ( port != - 1 ) { output . append ( ' ' ) . append ( port ) ; } if ( path != null ) { output . append ( URLUtils . percentDecode ( path ) ) ; } } else { output . append ( URLUtils . percentDecode ( schemeData ) ) ; } if ( query != null ) { output . append ( ' ' ) . append ( URLUtils . percentDecode ( query ) ) ; } if ( fragment != null ) { output . append ( ' ' ) . append ( URLUtils . percentDecode ( fragment ) ) ; } return output . toString ( ) ; }

Serializes the URL to a human-readable representation. That is,
percent-decoded and with IDN domains in its Unicode representation.

@return

Serializes the URL to a human - readable representation . That is percent - decoded and with IDN domains in its Unicode representation .


private <T, U> U queryStreamWithOrdinalParams(
            String sql,
            PreparedStatementSetter pss,
            RowMapper<T> mapper,
            Function<? super Stream<T>, U> handleStream) {
        SQLExceptionTranslator excTranslator = jdbcTemplate.getExceptionTranslator();
        ResultSetExtractor<U> extractor
            = new StreamResultSetExtractor(sql, mapper, handleStream, excTranslator);
        return jdbcTemplate.query(sql, pss, extractor);
    }

private < T , U > U queryStreamWithOrdinalParams ( String sql , PreparedStatementSetter pss , RowMapper < T > mapper , Function < ? super Stream < T > , U > handleStream ) { SQLExceptionTranslator excTranslator = jdbcTemplate . getExceptionTranslator ( ) ; ResultSetExtractor < U > extractor = new StreamResultSetExtractor ( sql , mapper , handleStream , excTranslator ) ; return jdbcTemplate . query ( sql , pss , extractor ) ; }

Executes a quey for stream with ordinal parameters.

Executes a quey for stream with ordinal parameters .


private <T, U> U queryStreamWithNamedParams(
            String sql,
            SqlParameterSource sps,
            RowMapper<T> mapper,
            Function<? super Stream<T>, U> handleStream) {
        SQLExceptionTranslator excTranslator = jdbcTemplate.getExceptionTranslator();
        ResultSetExtractor<U> extractor
            = new StreamResultSetExtractor(sql, mapper, handleStream, excTranslator);
        return namedJdbcTemplate.query(sql, sps, extractor);
    }

private < T , U > U queryStreamWithNamedParams ( String sql , SqlParameterSource sps , RowMapper < T > mapper , Function < ? super Stream < T > , U > handleStream ) { SQLExceptionTranslator excTranslator = jdbcTemplate . getExceptionTranslator ( ) ; ResultSetExtractor < U > extractor = new StreamResultSetExtractor ( sql , mapper , handleStream , excTranslator ) ; return namedJdbcTemplate . query ( sql , sps , extractor ) ; }

Executes a query for stream with named parameters.

Executes a query for stream with named parameters .


public static Field[] get(Class<?> clazz) {
        Field[] fields = CACHED_FIELDS.get(clazz);
        if (fields == null) {
            fields = clazz.getFields();
            CACHED_FIELDS.putIfAbsent(clazz, fields);
        }

        return fields;
    }

public static Field [ ] get ( Class < ? > clazz ) { Field [ ] fields = CACHED_FIELDS . get ( clazz ) ; if ( fields == null ) { fields = clazz . getFields ( ) ; CACHED_FIELDS . putIfAbsent ( clazz , fields ) ; } return fields ; }

Get fields of the given class.
@param clazz the class
@return the fields of the given class


private Optional<T> fetchRow() {
        if (this.row != null) {
            // already fetched
            return Optional.of(this.row);
        }

        this.hasReachedEos = hasReachedEos || ! wrapSqlException(() -> rs.next());
        if (this.hasReachedEos) {
            return Optional.empty();
        }

        this.row = wrapSqlException(() -> mapper.mapRow(rs, 1));
        return Optional.ofNullable(this.row);
    }

private
Optional
<
T
>
fetchRow
(
)
{
if
(
this
.
row
!=
)
{
// already fetched
return
Optional
.
of
(
this
.
row
)
;
}
this
.
hasReachedEos
=
hasReachedEos
||
!
wrapSqlException
(
(
)
->
rs
.
next
(
)
)
;
if
(
this
.
hasReachedEos
)
{
return
Optional
.
empty
(
)
;
}
this
.
row
=
wrapSqlException
(
(
)
->
mapper
.
mapRow
(
rs
,
1
)
)
;
return
Optional
.
ofNullable
(
this
.
row
)
;
}


protected static LocalDateTime getAsLocalDateTime(ResultSet rs, int index) throws SQLException {
        Timestamp timestamp = rs.getTimestamp(index);
        if (timestamp != null) {
            return timestamp.toLocalDateTime();
        }
        return null;
    }

protected static LocalDateTime getAsLocalDateTime ( ResultSet rs , int index ) throws SQLException { Timestamp timestamp = rs . getTimestamp ( index ) ; if ( timestamp != null ) { return timestamp . toLocalDateTime ( ) ; } return null ; }

Get the column value as LocalDateTime.
@param rs    ResultSet
@param index column index
@return column value
@throws SQLException in case of extraction failure


protected static LocalDate getAsLocalDate(ResultSet rs, int index) throws SQLException {
        Date date = rs.getDate(index);
        if (date != null) {
            return date.toLocalDate();
        }
        return null;
    }

protected static LocalDate getAsLocalDate ( ResultSet rs , int index ) throws SQLException { Date date = rs . getDate ( index ) ; if ( date != null ) { return date . toLocalDate ( ) ; } return null ; }

Get the column value as LocalDate.
@param rs    ResultSet
@param index column index
@return column value
@throws SQLException in case of extraction failure


protected static LocalTime getAsLocalTime(ResultSet rs, int index) throws SQLException {
        Time time = rs.getTime(index);
        if (time != null) {
            return time.toLocalTime();
        }
        return null;
    }

protected static LocalTime getAsLocalTime ( ResultSet rs , int index ) throws SQLException { Time time = rs . getTime ( index ) ; if ( time != null ) { return time . toLocalTime ( ) ; } return null ; }

Get the column value as LocalTime.
@param rs    ResultSet
@param index column index
@return column value
@throws SQLException in case of extraction failure


protected static ZonedDateTime getAsZonedDateTime(ResultSet rs, int index, ZoneId zoneId) throws SQLException {
        Timestamp timestamp = rs.getTimestamp(index);
        if (timestamp != null) {
            return timestamp.toLocalDateTime().atZone(zoneId);
        }
        return null;
    }

protected static ZonedDateTime getAsZonedDateTime ( ResultSet rs , int index , ZoneId zoneId ) throws SQLException { Timestamp timestamp = rs . getTimestamp ( index ) ; if ( timestamp != null ) { return timestamp . toLocalDateTime ( ) . atZone ( zoneId ) ; } return null ; }

Get the column value as ZonedDateTime.
@param rs     ResultSet
@param index  column index
@param zoneId zoneId
@return column value
@throws SQLException in case of extraction failure


protected static OffsetDateTime getAsOffsetDateTime(ResultSet rs, int index, ZoneId zoneId) throws SQLException {
        Timestamp timestamp = rs.getTimestamp(index);
        if (timestamp != null) {
            return timestamp.toLocalDateTime().atZone(zoneId).toOffsetDateTime();
        }
        return null;
    }

protected static OffsetDateTime getAsOffsetDateTime ( ResultSet rs , int index , ZoneId zoneId ) throws SQLException { Timestamp timestamp = rs . getTimestamp ( index ) ; if ( timestamp != null ) { return timestamp . toLocalDateTime ( ) . atZone ( zoneId ) . toOffsetDateTime ( ) ; } return null ; }

Get the column value as OffsetDateTime.
@param rs     ResultSet
@param index  column index
@param zoneId zoneId
@return column value
@throws SQLException in case of extraction failure

Get the column value as OffsetDateTime .


protected static OffsetTime getAsOffsetTime(ResultSet rs, int index, ZoneId zoneId) throws SQLException {
        Time time = rs.getTime(index);
        if (time != null) {
            return time.toLocalTime().atOffset(zoneId.getRules().getOffset(Instant.now()));
        }
        return null;
    }

protected static OffsetTime getAsOffsetTime ( ResultSet rs , int index , ZoneId zoneId ) throws SQLException { Time time = rs . getTime ( index ) ; if ( time != null ) { return time . toLocalTime ( ) . atOffset ( zoneId . getRules ( ) . getOffset ( Instant . now ( ) ) ) ; } return null ; }

Get the column value as OffsetTime.
@param rs     ResultSet
@param index  column index
@param zoneId zoneId
@return column value
@throws SQLException in case of extraction failure


protected Object getColumnValue(ResultSet rs, int index, Class<?> requiredType) throws SQLException {
        return Jsr310JdbcUtils.getResultSetValue(rs, index, requiredType, zoneId);
    }

protected Object getColumnValue ( ResultSet rs , int index , Class < ? > requiredType ) throws SQLException { return Jsr310JdbcUtils . getResultSetValue ( rs , index , requiredType , zoneId ) ; }

Get the column value.

@param rs           ResultSet
@param index        column index
@param requiredType the required value type
@return column value
@throws SQLException in case of extraction failure


public CdnPathBuilder crop(int width, int height) {
        dimensionsGuard(width, height);
        sb.append("/-/crop/")
                .append(width)
                .append("x")
                .append(height);
        return this;
    }

public CdnPathBuilder crop ( int width , int height ) { dimensionsGuard ( width , height ) ; sb . append ( "/-/crop/" ) . append ( width ) . append ( "x" ) . append ( height ) ; return this ; }

Adds top-left-aligned crop.

@param width Crop width
@param height Crop height


public CdnPathBuilder cropCenter(int width, int height) {
        dimensionsGuard(width, height);
        sb.append("/-/crop/")
                .append(width)
                .append("x")
                .append(height)
                .append("/center");
        return this;
    }

public CdnPathBuilder cropCenter ( int width , int height ) { dimensionsGuard ( width , height ) ; sb . append ( "/-/crop/" ) . append ( width ) . append ( "x" ) . append ( height ) . append ( "/center" ) ; return this ; }

Adds center-aligned crop.

@param width Crop width
@param height Crop height


public CdnPathBuilder cropColor(int width, int height, Color color) {
        dimensionsGuard(width, height);
        sb.append("/-/crop/")
                .append(width)
                .append("x")
                .append(height)
                .append("/")
                .append(colorToHex(color));
        return this;
    }

public CdnPathBuilder cropColor ( int width , int height , Color color ) { dimensionsGuard ( width , height ) ; sb . append ( "/-/crop/" ) . append ( width ) . append ( "x" ) . append ( height ) . append ( "/" ) . append ( colorToHex ( color ) ) ; return this ; }

Adds top-left-aligned crop with a filled background.

@param width Crop width
@param height Crop height
@param color Background color

Adds top - left - aligned crop with a filled background .


public CdnPathBuilder resizeWidth(int width) {
        dimensionGuard(width);
        sb.append("/-/resize/")
                .append(width)
                .append("x");
        return this;
    }

public CdnPathBuilder resizeWidth ( int width ) { dimensionGuard ( width ) ; sb . append ( "/-/resize/" ) . append ( width ) . append ( "x" ) ; return this ; }

Resizes width, keeping the aspect ratio.

@param width New width

Resizes width keeping the aspect ratio .


public CdnPathBuilder resize(int width, int height) {
        dimensionsGuard(width, height);
        sb.append("/-/resize/")
                .append(width)
                .append("x")
                .append(height);
        return this;
    }

public CdnPathBuilder resize ( int width , int height ) { dimensionsGuard ( width , height ) ; sb . append ( "/-/resize/" ) . append ( width ) . append ( "x" ) . append ( height ) ; return this ; }

Resizes width and height

@param width New width
@param height New height


public CdnPathBuilder scaleCrop(int width, int height) {
        dimensionsGuard(width, height);
        sb.append("/-/scale_crop/")
                .append(width)
                .append("x")
                .append(height);
        return this;
    }

public CdnPathBuilder scaleCrop ( int width , int height ) { dimensionsGuard ( width , height ) ; sb . append ( "/-/scale_crop/" ) . append ( width ) . append ( "x" ) . append ( height ) ; return this ; }

Scales the image until one of the dimensions fits,
then crops the bottom or right side.

@param width New width
@param height New height

Scales the image until one of the dimensions fits then crops the bottom or right side .


public CdnPathBuilder scaleCropCenter(int width, int height) {
        dimensionsGuard(width, height);
        sb.append("/-/scale_crop/")
                .append(width)
                .append("x")
                .append(height)
                .append("/center");
        return this;
    }

public CdnPathBuilder scaleCropCenter ( int width , int height ) { dimensionsGuard ( width , height ) ; sb . append ( "/-/scale_crop/" ) . append ( width ) . append ( "x" ) . append ( height ) . append ( "/center" ) ; return this ; }

Scales the image until one of the dimensions fits,
centers it, then crops the rest.

@param width New width
@param height New height

Scales the image until one of the dimensions fits centers it then crops the rest .


public CdnPathBuilder blur(int strength) {
        if (strength < 0 || strength > 5000) {
            strength = 10;
        }
        sb.append("/-/blur/")
                .append(strength);
        return this;
    }

public CdnPathBuilder blur ( int strength ) { if ( strength < 0 || strength > 5000 ) { strength = 10 ; } sb . append ( "/-/blur/" ) . append ( strength ) ; return this ; }

Performs Gaussian blur on result image.

@param strength Strength is standard deviation (aka blur radius) multiplied by ten. Strength
can be up to 5000. Default is 10.

Performs Gaussian blur on result image .


public CdnPathBuilder sharp(int strength) {
        if (strength < 0 || strength > 20) {
            strength = 5;
        }
        sb.append("/-/sharp/")
                .append(strength);
        return this;
    }

public CdnPathBuilder sharp ( int strength ) { if ( strength < 0 || strength > 20 ) { strength = 5 ; } sb . append ( "/-/sharp/" ) . append ( strength ) ; return this ; }

Performs sharpening on result image. This can be useful after scaling down.

@param strength Strength can be from 0 to 20. Default is 5.

Performs sharpening on result image . This can be useful after scaling down .


public CdnPathBuilder preview(int width, int height) {
        dimensionsGuard(width, height);
        sb.append("/-/preview/")
                .append(width)
                .append("x")
                .append(height);
        return this;
    }

public CdnPathBuilder preview ( int width , int height ) { dimensionsGuard ( width , height ) ; sb . append ( "/-/preview/" ) . append ( width ) . append ( "x" ) . append ( height ) ; return this ; }

Reduces an image proportionally in order to fit it into given dimensions.

@param width New width
@param height New height

Reduces an image proportionally in order to fit it into given dimensions .


public Project getProject() {
        URI url = Urls.apiProject();
        RequestHelper requestHelper = getRequestHelper();
        ProjectData projectData = requestHelper.executeQuery(new HttpGet(url), true, ProjectData.class);
        return new Project(this, projectData);
    }

public Project getProject ( ) { URI url = Urls . apiProject ( ) ; RequestHelper requestHelper = getRequestHelper ( ) ; ProjectData projectData = requestHelper . executeQuery ( new HttpGet ( url ) , true , ProjectData . class ) ; return new Project ( this , projectData ) ; }

Requests project info from the API.

@return Project resource


public File getFile(String fileId) {
        URI url = Urls.apiFile(fileId);
        RequestHelper requestHelper = getRequestHelper();
        FileData fileData = requestHelper.executeQuery(new HttpGet(url), true, FileData.class);
        return new File(this, fileData);
    }

public File getFile ( String fileId ) { URI url = Urls . apiFile ( fileId ) ; RequestHelper requestHelper = getRequestHelper ( ) ; FileData fileData = requestHelper . executeQuery ( new HttpGet ( url ) , true , FileData . class ) ; return new File ( this , fileData ) ; }

Requests file data.

@param fileId Resource UUID
@return File resource


public void deleteFile(String fileId) {
        URI url = Urls.apiFile(fileId);
        RequestHelper requestHelper = getRequestHelper();
        requestHelper.executeCommand(new HttpDelete(url), true);
    }

public void deleteFile ( String fileId ) { URI url = Urls . apiFile ( fileId ) ; RequestHelper requestHelper = getRequestHelper ( ) ; requestHelper . executeCommand ( new HttpDelete ( url ) , true ) ; }

Marks a file as deleted.

@param fileId Resource UUID


public void saveFile(String fileId) {
        URI url = Urls.apiFileStorage(fileId);
        RequestHelper requestHelper = getRequestHelper();
        requestHelper.executeCommand(new HttpPost(url), true);
    }

public void saveFile ( String fileId ) { URI url = Urls . apiFileStorage ( fileId ) ; RequestHelper requestHelper = getRequestHelper ( ) ; requestHelper . executeCommand ( new HttpPost ( url ) , true ) ; }

Marks a file as saved.

This has to be done for all files you want to keep.
Unsaved files are eventually purged.

@param fileId Resource UUID


public HttpResponse executeCommand(HttpUriRequest request, boolean apiHeaders) {
        if (apiHeaders) {
            setApiHeaders(request);
        }

        try {
            CloseableHttpResponse response = client.getHttpClient().execute(request);
            try {
                checkResponseStatus(response);
                return response;
            } finally {
                response.close();
            }
        } catch (IOException e) {
            throw new UploadcareNetworkException(e);
        }
    }

public HttpResponse executeCommand ( HttpUriRequest request , boolean apiHeaders ) { if ( apiHeaders ) { setApiHeaders ( request ) ; } try { CloseableHttpResponse response = client . getHttpClient ( ) . execute ( request ) ; try { checkResponseStatus ( response ) ; return response ; } finally { response . close ( ) ; } } catch ( IOException e ) { throw new UploadcareNetworkException ( e ) ; } }

Executes the request et the Uploadcare API and return the HTTP Response object.

The existence of this method(and it's return type) enables the end user to extend the
functionality of the
Uploadcare API client by creating a subclass of {@link com.uploadcare.api.Client}.

@param request    request to be sent to the API
@param apiHeaders TRUE if the default API headers should be set
@return HTTP Response object

Executes the request et the Uploadcare API and return the HTTP Response object .


private void checkResponseStatus(HttpResponse response) throws IOException {

        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode >= 200 && statusCode < 300) {
            return;
        } else if (statusCode == 401 || statusCode == 403) {
            throw new UploadcareAuthenticationException(
                    streamToString(response.getEntity().getContent()));
        } else if (statusCode == 400 || statusCode == 404) {
            throw new UploadcareInvalidRequestException(
                    streamToString(response.getEntity().getContent()));
        } else {
            throw new UploadcareApiException(
                    "Unknown exception during an API call, response:" + streamToString(
                            response.getEntity().getContent()));
        }
    }

Verifies that the response status codes are within acceptable boundaries and throws
corresponding exceptions
otherwise.

@param response The response object to be checked

Verifies that the response status codes are within acceptable boundaries and throws corresponding exceptions otherwise .


public static URI uploadFromUrl(String sourceUrl, String pubKey, String store) {
        URIBuilder builder = new URIBuilder(URI.create(UPLOAD_BASE));
        builder.setPath("/from_url/")
                .setParameter("source_url", sourceUrl)
                .setParameter("pub_key", pubKey)
                .setParameter("store", store);
        return trustedBuild(builder);
    }

public static URI uploadFromUrl ( String sourceUrl , String pubKey , String store ) { URIBuilder builder = new URIBuilder ( URI . create ( UPLOAD_BASE ) ) ; builder . setPath ( "/from_url/" ) . setParameter ( "source_url" , sourceUrl ) . setParameter ( "pub_key" , pubKey ) . setParameter ( "store" , store ) ; return trustedBuild ( builder ) ; }

Creates a URL for URL upload.

@param sourceUrl URL to upload from
@param pubKey Public key
@param store Store the file upon uploading.

@see com.uploadcare.upload.UrlUploader


@Override
    public void inject(Object target) {
        checkState(mObjectGraph != null, "object graph must be assigned prior to calling inject");
        mObjectGraph.inject(target);
    }

Injects a target object using this ActionBarActivity's object graph.

@param target the target object

Injects a target object using this ActionBarActivity s object graph .


public static Builder newBuilder(Context context, int themeResId) {
        if (Build.VERSION.SDK_INT >= 21) {
            return new APi21Builder(context, themeResId);
        }
        return new Api20Builder(context, themeResId);
    }

public static Builder newBuilder ( Context context , int themeResId ) { if ( Build . VERSION . SDK_INT >= 21 ) { return new APi21Builder ( context , themeResId ) ; } return new Api20Builder ( context , themeResId ) ; }

Create new Builder.

@param context    context.
@param themeResId theme res id.
@return {@link Builder}.


@Nullable
    public Class<?> findClass(final String className)
    {
        Objects.requireNonNull(className);

        try {
            return (Class<?>) findClass.invoke(loader, className);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new ParserTransformException("unable to find class by name ("
                + className + ')', e);
        }
    }

@
Nullable
public
Class
<
>
findClass
(
final
String
className
)
{
Objects
.
requireNonNull
(
className
)
;
try
{
return
(
Class
<
>
)
findClass
.
invoke
(
loader
,
className
)
;
}
catch
(
IllegalAccessException
|
InvocationTargetException
e
)
{
throw
new
ParserTransformException
(
"unable to find class by name ("
+
className
+
'
'
,
e
)
;
}
}

Returns the class with the given name if it has already been loaded by
the given class loader

If the class has not been loaded yet, this method returns {@code
null}.

@param className the full name of the class to be loaded
@return the class instance, if found


public Class<?> loadClass(final String className, final byte[] bytecode)
    {
        Objects.requireNonNull(className);
        Objects.requireNonNull(bytecode);

        try {
            return (Class<?>) loadClass.invoke(loader, className, bytecode, 0,
                bytecode.length);
        } catch (InvocationTargetException | IllegalAccessException e) {
            throw new ParserTransformException("unable to load class by name",
                e);
        }
    }

public
Class
<
>
loadClass
(
final
String
className
,
final
byte
[
]
bytecode
)
{
Objects
.
requireNonNull
(
className
)
;
Objects
.
requireNonNull
(
bytecode
)
;
try
{
return
(
Class
<
>
)
loadClass
.
invoke
(
loader
,
className
,
bytecode
,
0
,
bytecode
.
length
)
;
}
catch
(
InvocationTargetException
|
IllegalAccessException
e
)
{
throw
new
ParserTransformException
(
"unable to load class by name"
,
e
)
;
}
}

Loads the class defined with the given name and bytecode using the given
class loader

Since package and class idendity includes the ClassLoader instance
used to load a class, we use reflection on the given class loader to
define generated classes.

If we used our own class loader (in order to be able to access the
protected "defineClass" method), we would likely still be able to load
generated classes; however, they would not have access to package-private
classes and members of their super classes.

@param className the full name of the class to be loaded
@param bytecode the bytecode of the class to load
@return the class instance


private int doSearch(final CharBuffer buffer, final int matchedLength,
        final int currentLength, final boolean ignoreCase)
    {
        /*
         * Try and see if there is a possible match here; there is if "fullword"
         * is true, in this case the next "matchedLength" argument to a possible
         * child call will be the current length.
         */
        final int nextLength = fullWord ? currentLength : matchedLength;

        /*
         * If there is nothing left in the buffer, we have a match.
         */
        if (!buffer.hasRemaining())
            return nextLength;

        /*
         * OK, there is at least one character remaining, so pick it up and see
         * whether it is in the list of our children...
         */
        char c = buffer.get();
        int index = Arrays.binarySearch(nextChars, c);
        if (index < 0 && ignoreCase) {
            final boolean isUpper = Character.isUpperCase(c);
            final boolean isLower = Character.isLowerCase(c);
            if (isUpper != isLower) {
               c = isUpper ? Character.toLowerCase(c)
                   : Character.toUpperCase(c);
               index = Arrays.binarySearch(nextChars, c);
            }
        }

        /*
         * If not, we return the last good match; if yes, we call this same
         * method on the matching child node with the (possibly new) matched
         * length as an argument and a depth increased by 1.
         */
        if (index < 0)
            return nextLength;
        return nextNodes[index].doSearch(buffer, nextLength, currentLength + 1,
            ignoreCase);
    }

Core search method

This method uses a {@link CharBuffer} to perform searches, and changes
this buffer's position as the match progresses. The two other arguments
are the depth of the current search (ie the number of nodes visited
since root) and the index of the last node where a match was found (ie
the last node where {@link #fullWord} was true.

@param buffer the charbuffer
@param matchedLength the last matched length (-1 if no match yet)
@param currentLength the current length walked by the trie
@return the length of the match found, -1 otherwise


public TrieBuilder addWord(@Nonnull final String word)
    {
        Objects.requireNonNull(word);

        final int length = word.length();

        if (length == 0)
            throw new IllegalArgumentException("a trie cannot have empty "
                + "strings (use EMPTY instead)");
        nrWords++;
        maxLength = Math.max(maxLength, length);
        nodeBuilder.addWord(word);
        return this;
    }

public
TrieBuilder
addWord
(
@
Nonnull
final
String
word
)
{
Objects
.
requireNonNull
(
word
)
;
final
int
length
=
word
.
length
(
)
;
if
(
length
==
0
)
throw
new
IllegalArgumentException
(
"a trie cannot have empty "
+
"strings (use EMPTY instead)"
)
;
nrWords
++
;
maxLength
=
Math
.
max
(
maxLength
,
length
)
;
nodeBuilder
.
addWord
(
word
)
;
return
this
;
}

Add one word to the trie

@param word the word to add
@return this
@throws IllegalArgumentException word is empty


public boolean append(final char c)
    {
        if (get() == null)
            return set(new StringBuilder().append(c));
        get().append(c);
        return true;
    }

public boolean append ( final char c ) { if ( get ( ) == null ) return set ( new StringBuilder ( ) . append ( c ) ) ; get ( ) . append ( c ) ; return true ; }

Appends the given char.
If this instance is currently uninitialized the given char is used for initialization.

@param c the char to append
@return true

Appends the given char . If this instance is currently uninitialized the given char is used for initialization .


public final T getAndSet(final T value)
    {
        final T ret = this.value;
        this.value = value;
        return ret;
    }

public final T getAndSet ( final T value ) { final T ret = this . value ; this . value = value ; return ret ; }

Replaces this references value with the given one.

@param value the new value
@return the previous value

Replaces this references value with the given one .


public static boolean isAssignableTo(final String classInternalName,
        final Class<?> type)
    {
        Objects.requireNonNull(classInternalName, "classInternalName");
        Objects.requireNonNull(type, "type");

        final Class<?> c = CACHE.loadClass(classInternalName);
        //final Class<?> c = getClassForInternalName(classInternalName);
        return type.isAssignableFrom(c);
    }

Determines whether the class with the given descriptor is assignable to
the given type.

@param classInternalName the class descriptor
@param type the type
@return true if the class with the given descriptor is assignable to the
given type

Determines whether the class with the given descriptor is assignable to the given type .


private void copyParseInfo(final FileSystem zipfs)
        throws IOException
    {
        final Path path = zipfs.getPath(INFO_PATH);
        try (

            final BufferedWriter writer = Files.newBufferedWriter(path, UTF_8);
        ) {
            sb.setLength(0);
            sb.append(startTime).append(';')
                .append(prematchIndices.size()).append(';')
                .append(nextMatcherId).append(';')
                .append(nrLines).append(';')
                .append(nrChars).append(';')
                .append(nrCodePoints).append(';')
                .append(nextNodeId).append('\n');
            writer.append(sb);
            writer.flush();
        }
    }

private void copyParseInfo ( final FileSystem zipfs ) throws IOException { final Path path = zipfs . getPath ( INFO_PATH ) ; try ( final BufferedWriter writer = Files . newBufferedWriter ( path , UTF_8 ) ; ) { sb . setLength ( 0 ) ; sb . append ( startTime ) . append ( ' ' ) . append ( prematchIndices . size ( ) ) . append ( ' ' ) . append ( nextMatcherId ) . append ( ' ' ) . append ( nrLines ) . append ( ' ' ) . append ( nrChars ) . append ( ' ' ) . append ( nrCodePoints ) . append ( ' ' ) . append ( nextNodeId ) . append ( ' ' ) ; writer . append ( sb ) ; writer . flush ( ) ; } }


public static void hash(@Nonnull final InstructionGroup group,
        @Nonnull final String className)
    {
        final InstructionGroupHasher groupHasher
            = new InstructionGroupHasher(group, className);
        final String name = groupHasher.hashAndGetName();
        group.setName(name);
    }

public static void hash ( @ Nonnull final InstructionGroup group , @ Nonnull final String className ) { final InstructionGroupHasher groupHasher = new InstructionGroupHasher ( group , className ) ; final String name = groupHasher . hashAndGetName ( ) ; group . setName ( name ) ; }

Generate a hash of the group, use it to name it

@param group the instruction group
@param className this group's parent class name

Generate a hash of the group use it to name it


@Cached
    @DontLabel
    public Rule ignoreCase(final char c)
    {
        return Character.isLowerCase(c) == Character.isUpperCase(c)
            ? ch(c) : new CharIgnoreCaseMatcher(c);
    }

@ Cached @ DontLabel public Rule ignoreCase ( final char c ) { return Character . isLowerCase ( c ) == Character . isUpperCase ( c ) ? ch ( c ) : new CharIgnoreCaseMatcher ( c ) ; }

Match a given character in a case-insensitive manner

@param c the character to match
@return a rule

Match a given character in a case - insensitive manner


@Cached
    @DontLabel
    public Rule unicodeChar(final int codePoint)
    {
        if (!Character.isValidCodePoint(codePoint))
            throw new InvalidGrammarException("invalid code point "
                + codePoint);
        return new CodePointMatcher(codePoint);
    }

@
Cached
@
DontLabel
public
Rule
unicodeChar
(
final
int
codePoint
)
{
if
(
!
Character
.
isValidCodePoint
(
codePoint
)
)
throw
new
InvalidGrammarException
(
"invalid code point "
+
codePoint
)
;
return
new
CodePointMatcher
(
codePoint
)
;
}

Match one Unicode character

@param codePoint the code point
@return a rule