private static int getLongestLineLen(final String message) {
		String newLine = System.getProperty("line.separator");
		String[] lines = message.split(newLine);
		int maxLen = 0;
		for (String line : lines) {
			maxLen = Math.max(maxLen, line.length());
		}
		return maxLen;
	}

private static int getLongestLineLen ( final String message ) { String newLine = System . getProperty ( "line.separator" ) ; String [ ] lines = message . split ( newLine ) ; int maxLen = 0 ; for ( String line : lines ) { maxLen = Math . max ( maxLen , line . length ( ) ) ; } return maxLen ; }

For a given multiline message determines the character count of the longest line.
@param message The message after line-wrap has been applied but before any bubble wrapping.
@return The count of characters in the longest line.

For a given multiline message determines the character count of the longest line .


public boolean log(String message) {
        if (message == null) return false;

        boolean ok;
        try {
            ok = loggly.log(token, tags, message).isExecuted();
        } catch (Exception e) {
            e.printStackTrace();
            ok = false;
        }
        return ok;
    }

public boolean log ( String message ) { if ( message == null ) return false ; boolean ok ; try { ok = loggly . log ( token , tags , message ) . isExecuted ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; ok = false ; } return ok ; }

Posts a log message to Loggly
@param message message to be logged
@return {@code true} if successful; {@code false} otherwise


public void log(String message, final Callback callback) {
        if (message == null) return;

        loggly.log(token,
                tags,
                message,
                new retrofit2.Callback<LogglyResponse>() {
                    @Override
                    public void onResponse(Call<LogglyResponse> call, Response<LogglyResponse> response) {
                        callback.success();
                    }

                    @Override
                    public void onFailure(Call<LogglyResponse> call, Throwable throwable) {
                        callback.failure(throwable.getMessage());
                    }
                });
    }

public void log ( String message , final Callback callback ) { if ( message == null ) return ; loggly . log ( token , tags , message , new retrofit2 . Callback < LogglyResponse > ( ) { @ Override public void onResponse ( Call < LogglyResponse > call , Response < LogglyResponse > response ) { callback . success ( ) ; } @ Override public void onFailure ( Call < LogglyResponse > call , Throwable throwable ) { callback . failure ( throwable . getMessage ( ) ) ; } } ) ; }

Posts a log message asynchronously to Loggly
@param message message to be logged
@param callback callback to be invoked on completion of the post


public void logBulk(Collection<String> messages, final Callback callback) {
        if (messages == null) return;

        String parcel = joinStrings(messages);
        if (parcel.isEmpty()) return;

        loggly.logBulk(token,
                tags,
                parcel,
                new retrofit2.Callback<LogglyResponse>() {
                    @Override
                    public void onResponse(Call<LogglyResponse> call, Response<LogglyResponse> response) {
                        callback.success();
                    }

                    @Override
                    public void onFailure(Call<LogglyResponse> call, Throwable throwable) {
                        callback.failure(throwable.getMessage());
                    }
                });
    }

public void logBulk ( Collection < String > messages , final Callback callback ) { if ( messages == null ) return ; String parcel = joinStrings ( messages ) ; if ( parcel . isEmpty ( ) ) return ; loggly . logBulk ( token , tags , parcel , new retrofit2 . Callback < LogglyResponse > ( ) { @ Override public void onResponse ( Call < LogglyResponse > call , Response < LogglyResponse > response ) { callback . success ( ) ; } @ Override public void onFailure ( Call < LogglyResponse > call , Throwable throwable ) { callback . failure ( throwable . getMessage ( ) ) ; } } ) ; }

Posts several log messages in bulk to Loggly asynchronously
@param messages messages to be logged
@param callback callback to be invoked on completion of the post


private String joinStrings(Collection<String> messages) {
        StringBuilder b = new StringBuilder();
        for (String s : messages) {
            if (s == null || s.isEmpty()) {
                continue;
            }

            // Preserve new-lines in this event by replacing them
            // with "\r". Otherwise, they're processed as event
            // delimiters, resulting in unintentional multiple events.
            b.append(s.replaceAll("[\r\n]", "\r")).append('\n');
        }
        return b.toString();
    }

Combines a collection of messages to be sent to Loggly.
In order to preserve event boundaries, the new lines in
each message are replaced with '\r', which get stripped
by Loggly.
@param messages messages to be combined
@return a single string containing all the messages

Combines a collection of messages to be sent to Loggly . In order to preserve event boundaries the new lines in each message are replaced with \ r which get stripped by Loggly .


public static void main(String... args) {

        if (args.length == 0 || args[0].trim().isEmpty()) {
            System.err.println("missing argument: loggly token\nsee http://loggly.com/docs/customer-token-authentication-token/");
            System.exit(1);
        }

        final String TOKEN = args[0];
        final ILogglyClient loggly = new LogglyClient(TOKEN);

        System.out.println("posting single event to Loggly asynchronously...");
        loggly.log("Hello!\nThis is a\nmulti-line event!\n",
                new LogglyClient.Callback() {
                    public void success() {
                        System.out.println("callback succeeded");
                    }

                    public void failure(String error) {
                        System.err.println("callback failed: " + error);
                    }
                });

        System.out.println("posting bulk events to Loggly asynchronously...");
        loggly.logBulk(Arrays.asList("E1", "E2"),
                new LogglyClient.Callback() {
                    public void success() {
                        System.out.println("bulk callback succeeded");
                    }

                    public void failure(String error) {
                        System.err.println("bulk callback failed: " + error);
                    }
                });

        System.out.println("posting single event to Loggly...");
        boolean ok = loggly.log("Hello!\nThis is a\nmulti-line event!\n");
        System.out.println(ok ? "ok" : "err");

        System.out.println("posting single JSON event to Loggly...");
        final String json = "{ \"timestamp\": \"2015-01-01T12:34:00Z\", \"message\": \"Event 100\", \"count\": 100 }";
        ok = loggly.log(json);
        System.out.println(ok ? "ok" : "err");

        System.out.println("posting bulk events to Loggly...");
        ok = loggly.logBulk("This is a\nmulti-line event 1", "Event 2", "Event 3");
        System.out.println(ok ? "ok" : "err");

        System.out.println("setting log tags to 'foo', 'bar', and 'baz'...");
        loggly.setTags("foo", "bar,baz");
        ok = loggly.log("This should be tagged with 'foo', 'bar', and 'baz'");
        System.out.println(ok ? "ok" : "err");
    }

Runs a demo of the Loggly client

@param args command-line arguments. The first and only argument
should be your Loggly customer token.
http://loggly.com/docs/customer-token-authentication-token/


public SortedMap<String,Schema> getSchemas() throws SQLException {
		synchronized(getSchemasLock) {
			if(getSchemasCache==null) {
				SortedMap<String,Schema> newSchemas = new TreeMap<>(DatabaseMetaData.getCollator());
				try (ResultSet results = metaData.getMetaData().getSchemas()) {
					ResultSetMetaData resultsMeta = results.getMetaData();
					while(results.next()) {
						int colCount = resultsMeta.getColumnCount();
						//System.err.println("DEBUG: Catalog: getSchemas(): colCount=" + colCount);
						//for(int i=1; i<=colCount; i++) {
						//	resultsMeta.getColumnName(i);
						//	System.err.println("DEBUG: Catalog: getSchemas(): resultsMeta.getColumnName("+i+")=" + resultsMeta.getColumnName(i));
						//}
						//System.err.println("DEBUG: Catalog: getSchemas(): results.getString(\"table_catalog\")=" + results.getString("table_catalog"));
						//System.err.println("DEBUG: Catalog: getSchemas(): results.getString(\"TABLE_CATALOG\")=" + results.getString("TABLE_CATALOG"));
						if(
							colCount==1 // PostgreSQL 8.3 only returns one column
							|| results.getString("TABLE_CATALOG") == null // PostgreSQL 9.4 driver returns null
							|| name.equals(results.getString("TABLE_CATALOG")) // Other driver
						) {
							Schema newSchema = new Schema(this, results.getString("TABLE_SCHEM"));
							if(newSchemas.put(newSchema.getName(), newSchema)!=null) throw new AssertionError("Duplicate schema: "+newSchema);
						}
					}
				}
				getSchemasCache = AoCollections.optimalUnmodifiableSortedMap(newSchemas);
			}
			return getSchemasCache;
		}
	}

Gets all schemas for this catalog keyed by unique name.

@see  java.sql.DatabaseMetaData#getSchemas()

Gets all schemas for this catalog keyed by unique name .


public Schema getSchema(String name) throws NoRowException, SQLException {
		Schema schema = getSchemas().get(name);
		if(schema==null) throw new NoRowException("name=" + name);
		return schema;
	}

public Schema getSchema ( String name ) throws NoRowException , SQLException { Schema schema = getSchemas ( ) . get ( name ) ; if ( schema == null ) throw new NoRowException ( "name=" + name ) ; return schema ; }

Gets the schema of the provided name.

@throws  NoRowException if the schema doesn't exist


@Override
	public void contextInitialized(ServletContextEvent sce) {
		try {
			ServletContext sc;
			synchronized(servletContextLock) {
				servletContext = sce.getServletContext();
				sc = servletContext;
			}
			// Find the top level directory
			String gitToplevelPath = sc.getInitParameter(GIT_TOPLEVEL_CONTEXT_PARAM);
			File gitToplevelRaw;
			if(gitToplevelPath == null || gitToplevelPath.isEmpty()) {
				// Default to web root
				String rootRealPath = sc.getRealPath("/");
				if(rootRealPath == null) throw new IllegalStateException("Unable to find web root and " + GIT_TOPLEVEL_CONTEXT_PARAM + " context parameter not provided");
				gitToplevelRaw = new File(rootRealPath);
			} else {
				if(gitToplevelPath.startsWith("~/")) {
					gitToplevelRaw = new File(System.getProperty("user.home"), gitToplevelPath.substring(2));
				} else {
					gitToplevelRaw = new File(gitToplevelPath);
				}
			}
			if(DEBUG) sc.log("gitToplevelRaw: " + gitToplevelRaw);
			Path gtl;
			synchronized(gitToplevelLock) {
				gitToplevel = gitToplevelRaw.getCanonicalFile().toPath();
				gtl = gitToplevel;
			}
			if(DEBUG) sc.log("gitToplevel: " + gtl);
			// Make sure root exists and is readable
			if(!Files.isDirectory(gtl, LinkOption.NOFOLLOW_LINKS)) throw new IOException("Git toplevel is not a directory: " + gtl);
			if(!Files.isReadable(gtl)) throw new IOException("Unable to read Git toplevel directory: " + gtl);
			// Recursively watch for any changes in the directory
			if(DEBUG) sc.log("Starting watcher");
			WatchService w;
			synchronized(watcherLock) {
				watcher = gtl.getFileSystem().newWatchService();
				w = watcher;
			}
			resync();
			if(DEBUG) sc.log("Starting watchThread");
			synchronized(watcherThreadLock) {
				watcherThread = new Thread(watcherRunnable);
				watcherThread.start();
			}
			if(DEBUG) sc.log("Starting changeThread");
			synchronized(changedThreadLock) {
				changedThread = new Thread(changedRunnable);
				changedThread.start();
			}
			sc.setAttribute(APPLICATION_SCOPE_KEY, this);
		} catch(IOException e) {
			throw new WrappedException(e);
		}
	}


private void resync() throws IOException {
		Path gtl;
		synchronized(gitToplevelLock) {
			gtl = gitToplevel;
		}
		WatchService w;
		synchronized(watcherLock) {
			w = watcher;
		}
		if(gtl != null && w != null) {
			synchronized(registered) {
				Set<Path> extraKeys = new HashSet<>(registered.keySet());
				resync(w, gtl, extraKeys);
				for(Path extraKey : extraKeys) {
					if(DEBUG) log("Canceling watch key: " + extraKey);
					registered.remove(extraKey).cancel();
				}
			}
		}
	}

private
void
resync
(
)
throws
IOException
{
Path
gtl
;
synchronized
(
gitToplevelLock
)
{
gtl
=
gitToplevel
;
}
WatchService
w
;
synchronized
(
watcherLock
)
{
w
=
watcher
;
}
if
(
gtl
!=
&&
w
!=
)
{
synchronized
(
registered
)
{
Set
<
Path
>
extraKeys
=
new
HashSet
<>
(
registered
.
keySet
(
)
)
;
resync
(
w
,
gtl
,
extraKeys
)
;
for
(
Path
extraKey
:
extraKeys
)
{
if
(
DEBUG
)
log
(
"Canceling watch key: "
+
extraKey
)
;
registered
.
remove
(
extraKey
)
.
cancel
(
)
;
}
}
}
}

Resyncs the entire directory recursively, registering and canceling any
discrepancies found.

Resyncs the entire directory recursively registering and canceling any discrepancies found .


public SortedMap<String,Table> getTables() throws SQLException {
		synchronized(getTablesLock) {
			if(getTablesCache==null) {
				SortedMap<String,Table> newTables = new TreeMap<>(DatabaseMetaData.getCollator());
				try (ResultSet results = catalog.getMetaData().getMetaData().getTables(catalog.getName(), name, null, null)) {
					while(results.next()) {
						Table newTable = new Table(this, results.getString("TABLE_NAME"), results.getString("TABLE_TYPE"));
						if(newTables.put(newTable.getName(), newTable)!=null) throw new AssertionError("Duplicate table: "+newTable);
					}
				}
				getTablesCache = AoCollections.optimalUnmodifiableSortedMap(newTables);
			}
			return getTablesCache;
		}
	}

public
SortedMap
<
String
,
Table
>
getTables
(
)
throws
SQLException
{
synchronized
(
getTablesLock
)
{
if
(
getTablesCache
==
)
{
SortedMap
<
String
,
Table
>
newTables
=
new
TreeMap
<>
(
DatabaseMetaData
.
getCollator
(
)
)
;
try
(
ResultSet
results
=
catalog
.
getMetaData
(
)
.
getMetaData
(
)
.
getTables
(
catalog
.
getName
(
)
,
name
,
,
)
)
{
while
(
results
.
next
(
)
)
{
Table
newTable
=
new
Table
(
this
,
results
.
getString
(
"TABLE_NAME"
)
,
results
.
getString
(
"TABLE_TYPE"
)
)
;
if
(
newTables
.
put
(
newTable
.
getName
(
)
,
newTable
)
!=
)
throw
new
AssertionError
(
"Duplicate table: "
+
newTable
)
;
}
}
getTablesCache
=
AoCollections
.
optimalUnmodifiableSortedMap
(
newTables
)
;
}
return
getTablesCache
;
}
}

Gets all tables for this schema keyed by unique name.

@see  java.sql.DatabaseMetaData#getTables()

Gets all tables for this schema keyed by unique name .


public Table getTable(String name) throws NoRowException, SQLException {
		Table table = getTables().get(name);
		if(table==null) throw new NoRowException();
		return table;
	}

public Table getTable ( String name ) throws NoRowException , SQLException { Table table = getTables ( ) . get ( name ) ; if ( table == null ) throw new NoRowException ( ) ; return table ; }

Gets the table of the provided name.

@throws  NoRowException if the table doesn't exist


private void writeToImpl(Writer out, long writeStart, long writeEnd) throws IOException {
		try ( // TODO: If copying to another SegmentedBufferedWriter or AutoTempFileWriter, we have a chance here for disk-to-disk block level copying instead of going through all the conversions.
			RandomAccessFile raf = new RandomAccessFile(tempFile.getFile(), "r")) {
			byte[] bytes = BufferManager.getBytes();
			try {
				char[] chars = BufferManager.getChars();
				try {
					long index = writeStart;
					raf.seek(index<<1);
					while(index<writeEnd) {
						// Read a block
						long blockSizeLong = (writeEnd - index)<<1;
						int blockSize = blockSizeLong > BufferManager.BUFFER_SIZE ? BufferManager.BUFFER_SIZE : (int)blockSizeLong;
						assert (blockSize&1) == 0 : "Must be an even number for UTF-16 conversion";
						raf.readFully(bytes, 0, blockSize);
						// Convert to characters
						for(
							int bpos=0, cpos=0;
							bpos<blockSize;
							bpos+=2, cpos++
						) {
							chars[cpos] = IoUtils.bufferToChar(bytes, bpos);
						}
						// Write to output
						out.write(chars, 0, blockSize>>1);
						// Update location
						index += blockSize>>1;
					}
				} finally {
					BufferManager.release(chars, false);
				}
			} finally {
				BufferManager.release(bytes, false);
			}
		}
	}

Implementation of writeTo

@param out
@param writeStart  The absolute index to write from
@param writeEnd    The absolute index one past last character to write
@throws IOException


public SortedMap<String,Catalog> getCatalogs() throws SQLException {
		synchronized(getCatalogsLock) {
			if(getCatalogsCache==null) {
				SortedMap<String,Catalog> newCatalogs = new TreeMap<>(englishCollator);
				try (ResultSet results = metaData.getCatalogs()) {
					while(results.next()) {
						Catalog newCatalog = new Catalog(this, results.getString(1));
						if(newCatalogs.put(newCatalog.getName(), newCatalog)!=null) throw new AssertionError("Duplicate catalog: "+newCatalog);
					}
				}
				getCatalogsCache = AoCollections.optimalUnmodifiableSortedMap(newCatalogs);
			}
			return getCatalogsCache;
		}
	}

public
SortedMap
<
String
,
Catalog
>
getCatalogs
(
)
throws
SQLException
{
synchronized
(
getCatalogsLock
)
{
if
(
getCatalogsCache
==
)
{
SortedMap
<
String
,
Catalog
>
newCatalogs
=
new
TreeMap
<>
(
englishCollator
)
;
try
(
ResultSet
results
=
metaData
.
getCatalogs
(
)
)
{
while
(
results
.
next
(
)
)
{
Catalog
newCatalog
=
new
Catalog
(
this
,
results
.
getString
(
1
)
)
;
if
(
newCatalogs
.
put
(
newCatalog
.
getName
(
)
,
newCatalog
)
!=
)
throw
new
AssertionError
(
"Duplicate catalog: "
+
newCatalog
)
;
}
}
getCatalogsCache
=
AoCollections
.
optimalUnmodifiableSortedMap
(
newCatalogs
)
;
}
return
getCatalogsCache
;
}
}

Gets all catalogs for this database keyed by unique name.

@see  java.sql.DatabaseMetaData#getCatalogs()

Gets all catalogs for this database keyed by unique name .


public Catalog getCatalog(String name) throws NoRowException, SQLException {
		Catalog catalog = getCatalogs().get(name);
		if(catalog==null) throw new NoRowException();
		return catalog;
	}

public Catalog getCatalog ( String name ) throws NoRowException , SQLException { Catalog catalog = getCatalogs ( ) . get ( name ) ; if ( catalog == null ) throw new NoRowException ( ) ; return catalog ; }

Gets the catalog of the provided name.

@throws  NoRowException if the catalog doesn't exist


private char[] getBuffer(int additional) throws IOException {
		long newLen = (long)length + additional;
		if(newLen > MAX_LENGTH) throw new IOException("Maximum buffer length is " + MAX_LENGTH + ", " + newLen + " requested");
		char[] buf = this.buffer;
		int bufLen = buf.length;
		if(newLen > bufLen) {
			// Find the next power of two that will hold all of the contents
			int newBufLen = bufLen==0 ? BufferManager.BUFFER_SIZE : (bufLen << 1);
			while(newBufLen < newLen) {
				newBufLen <<= 1;
			}
			char[] newBuf =
				(newBufLen == BufferManager.BUFFER_SIZE)
				? BufferManager.getChars()
				: new char[newBufLen];
			System.arraycopy(buf, 0, newBuf, 0, length);
			// Recycle buffer
			if(bufLen == BufferManager.BUFFER_SIZE) {
				BufferManager.release(buf, false);
			}
			buf = newBuf;
			this.buffer = buf;
		}
		return buf;
	}

Grows as-needed to fit the provided new capacity.

@returns the possibly new buffer.

Grows as - needed to fit the provided new capacity .


private void log(Encoder encoder) throws IOException {
		if(encoder==null) log.write("null");
		else {
			String className = encoder.getClass().getName();
			// Some shortcuts from the ao-encoding project, classnames used here to avoid hard dependency
			if("com.aoindustries.encoding.JavaScriptInXhtmlAttributeEncoder".equals(className)) {
				log.write("javaScriptInXhtmlAttributeEncoder");
			} else if("com.aoindustries.encoding.JavaScriptInXhtmlEncoder".equals(className)) {
				log.write("javaScriptInXhtmlEncoder");
			} else if("com.aoindustries.encoding.TextInXhtmlAttributeEncoder".equals(className)) {
				log.write("textInXhtmlAttributeEncoder");
			} else {
				log.write(className);
			}
		}
	}

Provides detailed logging for a media encoder.

Provides detailed logging for a media encoder .


private void log(Writer writer) throws IOException {
		if(writer==null) {
			log.write("null");
		} else if(writer instanceof LoggingWriter) {
			LoggingWriter loggingWriter = (LoggingWriter)writer;
			log.write("writer[");
			log.write(Long.toString(loggingWriter.getId()));
			log.write(']');
		} else if(writer instanceof EncoderWriter) {
			EncoderWriter encoderWriter = (EncoderWriter)writer;
			log.write("new EncoderWriter(");
			log(encoderWriter.getEncoder());
			log.write(", ");
			log(encoderWriter.getOut());
			log.write(')');
		} else {
			String classname = writer.getClass().getName();
			if(classname.equals("org.apache.jasper.runtime.BodyContentImpl")) log.write("bodyContent");
			else if(classname.equals("org.apache.jasper.runtime.JspWriterImpl")) log.write("jspWriter");
			else log.write(classname);
		}
	}

Provides detailed logging for a writer .


public static <F> LexicalPosition<F> zeroWithFile(
    final F file)
  {
    return LexicalPosition.of(0, 0, Optional.of(file));
  }

public static < F > LexicalPosition < F > zeroWithFile ( final F file ) { return LexicalPosition . of ( 0 , 0 , Optional . of ( file ) ) ; }

Construct a lexical position at line 0, column 0, with the given file.

@param file The type name
@param <F>  The type of file names

@return A lexical position

Construct a lexical position at line 0 column 0 with the given file .


private void append(int segmentIndex, int off, int len, StringBuilder buffer) {
		switch(segmentTypes[segmentIndex]) {
			case SegmentedWriter.TYPE_STRING :
				buffer.append(
					(String)segmentValues[segmentIndex],
					off,
					off + len
				);
				break;
			case SegmentedWriter.TYPE_CHAR_NEWLINE :
				assert off==0;
				assert len==1;
				buffer.append('\n');
				break;
			case SegmentedWriter.TYPE_CHAR_QUOTE :
				assert off==0;
				assert len==1;
				buffer.append('"');
				break;
			case SegmentedWriter.TYPE_CHAR_APOS :
				assert off==0;
				assert len==1;
				buffer.append('\'');
				break;
			case SegmentedWriter.TYPE_CHAR_OTHER :
				assert off==0;
				assert len==1;
				buffer.append(((Character)segmentValues[segmentIndex]).charValue());
				break;
			default :
				throw new AssertionError();
		}
	}

private void append ( int segmentIndex , int off , int len , StringBuilder buffer ) { switch ( segmentTypes [ segmentIndex ] ) { case SegmentedWriter . TYPE_STRING : buffer . append ( ( String ) segmentValues [ segmentIndex ] , off , off + len ) ; break ; case SegmentedWriter . TYPE_CHAR_NEWLINE : assert off == 0 ; assert len == 1 ; buffer . append ( ' ' ) ; break ; case SegmentedWriter . TYPE_CHAR_QUOTE : assert off == 0 ; assert len == 1 ; buffer . append ( ' ' ) ; break ; case SegmentedWriter . TYPE_CHAR_APOS : assert off == 0 ; assert len == 1 ; buffer . append ( ' ' ) ; break ; case SegmentedWriter . TYPE_CHAR_OTHER : assert off == 0 ; assert len == 1 ; buffer . append ( ( ( Character ) segmentValues [ segmentIndex ] ) . charValue ( ) ) ; break ; default : throw new AssertionError ( ) ; } }

Appends the given range of a segment. to the buffer.

Appends the given range of a segment . to the buffer .


private void writeSegment(int segmentIndex, int off, int len, Encoder encoder, Writer out) throws IOException {
		switch(segmentTypes[segmentIndex]) {
			case SegmentedWriter.TYPE_STRING :
				encoder.write(
					(String)segmentValues[segmentIndex],
					off,
					len,
					out
				);
				break;
			case SegmentedWriter.TYPE_CHAR_NEWLINE :
				assert off==0;
				assert len==1;
				encoder.write('\n', out);
				break;
			case SegmentedWriter.TYPE_CHAR_QUOTE :
				assert off==0;
				assert len==1;
				encoder.write('"', out);
				break;
			case SegmentedWriter.TYPE_CHAR_APOS :
				assert off==0;
				assert len==1;
				encoder.write('\'', out);
				break;
			case SegmentedWriter.TYPE_CHAR_OTHER :
				assert off==0;
				assert len==1;
				encoder.write((Character)segmentValues[segmentIndex], out);
				break;
			default :
				throw new AssertionError();
		}
	}

private void writeSegment ( int segmentIndex , int off , int len , Encoder encoder , Writer out ) throws IOException { switch ( segmentTypes [ segmentIndex ] ) { case SegmentedWriter . TYPE_STRING : encoder . write ( ( String ) segmentValues [ segmentIndex ] , off , len , out ) ; break ; case SegmentedWriter . TYPE_CHAR_NEWLINE : assert off == 0 ; assert len == 1 ; encoder . write ( ' ' , out ) ; break ; case SegmentedWriter . TYPE_CHAR_QUOTE : assert off == 0 ; assert len == 1 ; encoder . write ( ' ' , out ) ; break ; case SegmentedWriter . TYPE_CHAR_APOS : assert off == 0 ; assert len == 1 ; encoder . write ( ' ' , out ) ; break ; case SegmentedWriter . TYPE_CHAR_OTHER : assert off == 0 ; assert len == 1 ; encoder . write ( ( Character ) segmentValues [ segmentIndex ] , out ) ; break ; default : throw new AssertionError ( ) ; } }

Writes the given range of a segment to the given writer using the given encoder.

Writes the given range of a segment to the given writer using the given encoder .


private static char charAt(byte type, Object value, int charIndex) {
		switch(type) {
			case SegmentedWriter.TYPE_STRING :
				return ((String)value).charAt(charIndex);
			case SegmentedWriter.TYPE_CHAR_NEWLINE :
				assert charIndex==0;
				return '\n';
			case SegmentedWriter.TYPE_CHAR_QUOTE :
				assert charIndex==0;
				return '"';
			case SegmentedWriter.TYPE_CHAR_APOS :
				assert charIndex==0;
				return '\'';
			case SegmentedWriter.TYPE_CHAR_OTHER :
				assert charIndex==0;
				return (Character)value;
			default :
				throw new AssertionError();
		}
	}

private static char charAt ( byte type , Object value , int charIndex ) { switch ( type ) { case SegmentedWriter . TYPE_STRING : return ( ( String ) value ) . charAt ( charIndex ) ; case SegmentedWriter . TYPE_CHAR_NEWLINE : assert charIndex == 0 ; return ' ' ; case SegmentedWriter . TYPE_CHAR_QUOTE : assert charIndex == 0 ; return ' ' ; case SegmentedWriter . TYPE_CHAR_APOS : assert charIndex == 0 ; return ' ' ; case SegmentedWriter . TYPE_CHAR_OTHER : assert charIndex == 0 ; return ( Character ) value ; default : throw new AssertionError ( ) ; } }

Gets the character at the given index in a segment.
This is the absolute index, the offset is not added-in.

Gets the character at the given index in a segment . This is the absolute index the offset is not added - in .


private Map<String,Class<?>> getSqlDataTypes() throws SQLException {
		if(sqlDataTypes == null) {
			// Load custom types from ServiceLoader
			Map<String,Class<?>> newMap = new LinkedHashMap<>();
			Iterator<SQLData> iter = ServiceLoader.load(SQLData.class).iterator();
			while(iter.hasNext()) {
				SQLData sqlData = iter.next();
				newMap.put(sqlData.getSQLTypeName(), sqlData.getClass());
			}
			sqlDataTypes = newMap;
		}
		return sqlDataTypes;
	}

private
Map
<
String
,
Class
<
>
>
getSqlDataTypes
(
)
throws
SQLException
{
if
(
sqlDataTypes
==
)
{
// Load custom types from ServiceLoader
Map
<
String
,
Class
<
>
>
newMap
=
new
LinkedHashMap
<>
(
)
;
Iterator
<
SQLData
>
iter
=
ServiceLoader
.
load
(
SQLData
.
class
)
.
iterator
(
)
;
while
(
iter
.
hasNext
(
)
)
{
SQLData
sqlData
=
iter
.
next
(
)
;
newMap
.
put
(
sqlData
.
getSQLTypeName
(
)
,
sqlData
.
getClass
(
)
)
;
}
sqlDataTypes
=
newMap
;
}
return
sqlDataTypes
;
}

Loads the custom types when first needed and caches the results.

Loads the custom types when first needed and caches the results .


public SortedMap<String,Column> getColumnMap() throws SQLException {
		synchronized(getColumnMapLock) {
			if(getColumnMapCache==null) {
				SortedMap<String,Column> newColumnMap = new TreeMap<>(DatabaseMetaData.getCollator());
				try (ResultSet results = schema.getCatalog().getMetaData().getMetaData().getColumns(schema.getCatalog().getName(), schema.getName(), name, null)) {
					while(results.next()) {
						Column newColumn = new Column(
							this,
							results.getString("COLUMN_NAME"),
							results.getInt("DATA_TYPE"),
							results.getString("TYPE_NAME"),
							getInteger(results, "COLUMN_SIZE"),
							getInteger(results, "DECIMAL_DIGITS"),
							results.getInt("NULLABLE"),
							results.getString("COLUMN_DEF"),
							getInteger(results, "CHAR_OCTET_LENGTH"),
							results.getInt("ORDINAL_POSITION"),
							results.getString("IS_NULLABLE"),
							results.getString("IS_AUTOINCREMENT")
						);
						if(newColumnMap.put(newColumn.getName(), newColumn)!=null) throw new AssertionError("Duplicate column: "+newColumn);
					}
				}
				getColumnMapCache = AoCollections.optimalUnmodifiableSortedMap(newColumnMap);
			}
			return getColumnMapCache;
		}
	}

public
SortedMap
<
String
,
Column
>
getColumnMap
(
)
throws
SQLException
{
synchronized
(
getColumnMapLock
)
{
if
(
getColumnMapCache
==
)
{
SortedMap
<
String
,
Column
>
newColumnMap
=
new
TreeMap
<>
(
DatabaseMetaData
.
getCollator
(
)
)
;
try
(
ResultSet
results
=
schema
.
getCatalog
(
)
.
getMetaData
(
)
.
getMetaData
(
)
.
getColumns
(
schema
.
getCatalog
(
)
.
getName
(
)
,
schema
.
getName
(
)
,
name
,
)
)
{
while
(
results
.
next
(
)
)
{
Column
newColumn
=
new
Column
(
this
,
results
.
getString
(
"COLUMN_NAME"
)
,
results
.
getInt
(
"DATA_TYPE"
)
,
results
.
getString
(
"TYPE_NAME"
)
,
getInteger
(
results
,
"COLUMN_SIZE"
)
,
getInteger
(
results
,
"DECIMAL_DIGITS"
)
,
results
.
getInt
(
"NULLABLE"
)
,
results
.
getString
(
"COLUMN_DEF"
)
,
getInteger
(
results
,
"CHAR_OCTET_LENGTH"
)
,
results
.
getInt
(
"ORDINAL_POSITION"
)
,
results
.
getString
(
"IS_NULLABLE"
)
,
results
.
getString
(
"IS_AUTOINCREMENT"
)
)
;
if
(
newColumnMap
.
put
(
newColumn
.
getName
(
)
,
newColumn
)
!=
)
throw
new
AssertionError
(
"Duplicate column: "
+
newColumn
)
;
}
}
getColumnMapCache
=
AoCollections
.
optimalUnmodifiableSortedMap
(
newColumnMap
)
;
}
return
getColumnMapCache
;
}
}

Gets all columns for this schema keyed by unique name.

@see  java.sql.DatabaseMetaData#getColumns(java.lang.String, java.lang.String, java.lang.String, java.lang.String)

Gets all columns for this schema keyed by unique name .


public Column getColumn(String name) throws NoRowException, SQLException {
		Column column = getColumnMap().get(name);
		if(column==null) throw new NoRowException();
		return column;
	}

public Column getColumn ( String name ) throws NoRowException , SQLException { Column column = getColumnMap ( ) . get ( name ) ; if ( column == null ) throw new NoRowException ( ) ; return column ; }

Gets the column of the provided name.

@throws  NoRowException if the column doesn't exist


public List<Column> getColumns() throws SQLException {
		synchronized(getColumnsLock) {
			if(getColumnsCache==null) {
				SortedMap<String,Column> columnMap = getColumnMap();
				List<Column> newColumns = new ArrayList<>(columnMap.size());
				for(int i=0; i<columnMap.size(); i++) newColumns.add(null);
				for(Column column : columnMap.values()) {
					int ordinalPosition = column.getOrdinalPosition();
					if(newColumns.set(ordinalPosition-1, column)!=null) throw new SQLException("Duplicate ordinal position: "+ordinalPosition);
				}
				for(int i=0; i<newColumns.size(); i++) {
					if(newColumns.get(i)==null) throw new SQLException("Missing ordinal position: "+(i+1));
				}
				getColumnsCache = AoCollections.optimalUnmodifiableList(newColumns);
			}
			return getColumnsCache;
		}
	}

public
List
<
Column
>
getColumns
(
)
throws
SQLException
{
synchronized
(
getColumnsLock
)
{
if
(
getColumnsCache
==
)
{
SortedMap
<
String
,
Column
>
columnMap
=
getColumnMap
(
)
;
List
<
Column
>
newColumns
=
new
ArrayList
<>
(
columnMap
.
size
(
)
)
;
for
(
int
i
=
0
;
i
<
columnMap
.
size
(
)
;
i
++
)
newColumns
.
(
)
;
for
(
Column
column
:
columnMap
.
values
(
)
)
{
int
ordinalPosition
=
column
.
getOrdinalPosition
(
)
;
if
(
newColumns
.
set
(
ordinalPosition
1
,
column
)
!=
)
throw
new
SQLException
(
"Duplicate ordinal position: "
+
ordinalPosition
)
;
}
for
(
int
i
=
0
;
i
<
newColumns
.
size
(
)
;
i
++
)
{
if
(
newColumns
.
get
(
i
)
==
)
throw
new
SQLException
(
"Missing ordinal position: "
+
(
i
+
1
)
)
;
}
getColumnsCache
=
AoCollections
.
optimalUnmodifiableList
(
newColumns
)
;
}
return
getColumnsCache
;
}
}

Gets all columns for this schema in their ordinal position order.
Column with ordinal position one is at index zero.

@see  #getColumnMap()

Gets all columns for this schema in their ordinal position order . Column with ordinal position one is at index zero .


public Column getColumn(int ordinalPosition) throws NoRowException, SQLException {
		try {
			return getColumns().get(ordinalPosition-1);
		} catch(IndexOutOfBoundsException exc) {
			throw new NoRowException(exc);
		}
	}

public Column getColumn ( int ordinalPosition ) throws NoRowException , SQLException { try { return getColumns ( ) . get ( ordinalPosition - 1 ) ; } catch ( IndexOutOfBoundsException exc ) { throw new NoRowException ( exc ) ; } }

Gets the column of the provided ordinal position, where positions start at one.

@throws  NoRowException if the column doesn't exist

Gets the column of the provided ordinal position where positions start at one .


public Set<? extends Table> getImportedTables() throws SQLException {
		synchronized(getImportedTablesLock) {
			if(getImportedTablesCache==null) {
				Set<Table> newImportedTables = new LinkedHashSet<>();
				Catalog catalog = schema.getCatalog();
				DatabaseMetaData metaData = catalog.getMetaData();
				try (ResultSet results = schema.getCatalog().getMetaData().getMetaData().getImportedKeys(schema.getCatalog().getName(), schema.getName(), name)) {
					while(results.next()) {
						String pkCat = results.getString("PKTABLE_CAT");
						Catalog pkCatalog = pkCat==null ? catalog : metaData.getCatalog(pkCat);
						newImportedTables.add(
							pkCatalog
							.getSchema(results.getString("PKTABLE_SCHEM"))
							.getTable(results.getString("PKTABLE_NAME"))
						);
					}
				}
				getImportedTablesCache = AoCollections.optimalUnmodifiableSet(newImportedTables);
			}
			return getImportedTablesCache;
		}
	}

public Set < ? extends Table > getImportedTables ( ) throws SQLException { synchronized ( getImportedTablesLock ) { if ( getImportedTablesCache == null ) { Set < Table > newImportedTables = new LinkedHashSet <> ( ) ; Catalog catalog = schema . getCatalog ( ) ; DatabaseMetaData metaData = catalog . getMetaData ( ) ; try ( ResultSet results = schema . getCatalog ( ) . getMetaData ( ) . getMetaData ( ) . getImportedKeys ( schema . getCatalog ( ) . getName ( ) , schema . getName ( ) , name ) ) { while ( results . next ( ) ) { String pkCat = results . getString ( "PKTABLE_CAT" ) ; Catalog pkCatalog = pkCat == null ? catalog : metaData . getCatalog ( pkCat ) ; newImportedTables . add ( pkCatalog . getSchema ( results . getString ( "PKTABLE_SCHEM" ) ) . getTable ( results . getString ( "PKTABLE_NAME" ) ) ) ; } } getImportedTablesCache = AoCollections . optimalUnmodifiableSet ( newImportedTables ) ; } return getImportedTablesCache ; } }

Gets the set of tables that this table depends on.

This is based on getImportedKeys

Gets the set of tables that this table depends on .


public Set<? extends Table> getExportedTables() throws SQLException {
		synchronized(getExportedTablesLock) {
			if(getExportedTablesCache==null) {
				Set<Table> newExportedTables = new LinkedHashSet<>();
				Catalog catalog = schema.getCatalog();
				DatabaseMetaData metaData = catalog.getMetaData();
				try (ResultSet results = schema.getCatalog().getMetaData().getMetaData().getExportedKeys(schema.getCatalog().getName(), schema.getName(), name)) {
					while(results.next()) {
						String fkCat = results.getString("FKTABLE_CAT");
						Catalog fkCatalog = fkCat==null ? catalog : metaData.getCatalog(fkCat);
						newExportedTables.add(
							fkCatalog
							.getSchema(results.getString("FKTABLE_SCHEM"))
							.getTable(results.getString("FKTABLE_NAME"))
						);
					}
				}
				getExportedTablesCache = AoCollections.optimalUnmodifiableSet(newExportedTables);
			}
			return getExportedTablesCache;
		}
	}

public Set < ? extends Table > getExportedTables ( ) throws SQLException { synchronized ( getExportedTablesLock ) { if ( getExportedTablesCache == null ) { Set < Table > newExportedTables = new LinkedHashSet <> ( ) ; Catalog catalog = schema . getCatalog ( ) ; DatabaseMetaData metaData = catalog . getMetaData ( ) ; try ( ResultSet results = schema . getCatalog ( ) . getMetaData ( ) . getMetaData ( ) . getExportedKeys ( schema . getCatalog ( ) . getName ( ) , schema . getName ( ) , name ) ) { while ( results . next ( ) ) { String fkCat = results . getString ( "FKTABLE_CAT" ) ; Catalog fkCatalog = fkCat == null ? catalog : metaData . getCatalog ( fkCat ) ; newExportedTables . add ( fkCatalog . getSchema ( results . getString ( "FKTABLE_SCHEM" ) ) . getTable ( results . getString ( "FKTABLE_NAME" ) ) ) ; } } getExportedTablesCache = AoCollections . optimalUnmodifiableSet ( newExportedTables ) ; } return getExportedTablesCache ; } }

Gets the set of tables that depend on this table.

This is based on getExportedKeys

Gets the set of tables that depend on this table .


private void addSegment(byte type, Object value, int off, int len) {
		assert !isClosed;
		assert len>0 : "Empty segments should never be added";
		final int arraylen = segmentValues.length;
		if(segmentCount==arraylen) {
			// Need to grow
			if(arraylen==0) {
				this.segmentTypes = new byte[START_LEN];
				this.segmentValues = new Object[START_LEN];
				this.segmentOffsets = new int[START_LEN];
				this.segmentLengths = new int[START_LEN];
			} else {
				// Double capacity and copy
				int newLen = arraylen<<1;
				byte[] newTypes = new byte[newLen];
				System.arraycopy(segmentTypes, 0, newTypes, 0, arraylen);
				this.segmentTypes = newTypes;
				Object[] newValues = new Object[newLen];
				System.arraycopy(segmentValues, 0, newValues, 0, arraylen);
				this.segmentValues = newValues;
				int[] newOffsets = new int[newLen];
				System.arraycopy(segmentOffsets, 0, newOffsets, 0, arraylen);
				this.segmentOffsets = newOffsets;
				int[] newLengths = new int[newLen];
				System.arraycopy(segmentLengths, 0, newLengths, 0, arraylen);
				this.segmentLengths = newLengths;
			}
		}
		segmentTypes[segmentCount] = type;
		segmentValues[segmentCount] = value;
		segmentOffsets[segmentCount] = off;
		segmentLengths[segmentCount++] = len;
	}

private
void
addSegment
(
byte
type
,
Object
value
,
int
off
,
int
len
)
{
assert
!
isClosed
;
assert
len
>
0
:
"Empty segments should never be added"
;
final
int
arraylen
=
segmentValues
.
length
;
if
(
segmentCount
==
arraylen
)
{
// Need to grow
if
(
arraylen
==
0
)
{
this
.
segmentTypes
=
new
byte
[
START_LEN
]
;
this
.
segmentValues
=
new
Object
[
START_LEN
]
;
this
.
segmentOffsets
=
new
int
[
START_LEN
]
;
this
.
segmentLengths
=
new
int
[
START_LEN
]
;
}
else
{
// Double capacity and copy
int
newLen
=
arraylen
<<
1
;
byte
[
]
newTypes
=
new
byte
[
newLen
]
;
System
.
arraycopy
(
segmentTypes
,
0
,
newTypes
,
0
,
arraylen
)
;
this
.
segmentTypes
=
newTypes
;
Object
[
]
newValues
=
new
Object
[
newLen
]
;
System
.
arraycopy
(
segmentValues
,
0
,
newValues
,
0
,
arraylen
)
;
this
.
segmentValues
=
newValues
;
int
[
]
newOffsets
=
new
int
[
newLen
]
;
System
.
arraycopy
(
segmentOffsets
,
0
,
newOffsets
,
0
,
arraylen
)
;
this
.
segmentOffsets
=
newOffsets
;
int
[
]
newLengths
=
new
int
[
newLen
]
;
System
.
arraycopy
(
segmentLengths
,
0
,
newLengths
,
0
,
arraylen
)
;
this
.
segmentLengths
=
newLengths
;
}
}
segmentTypes
[
segmentCount
]
=
type
;
segmentValues
[
segmentCount
]
=
value
;
segmentOffsets
[
segmentCount
]
=
off
;
segmentLengths
[
segmentCount
++
]
=
len
;
}


private void log(char ch) throws IOException {
		if(ch=='\t') log.write("'\\t'");
		else if(ch=='\b') log.write("'\\b'");
		else if(ch=='\n') log.write("'\\n'");
		else if(ch=='\r') log.write("'\\r'");
		else if(ch=='\f') log.write("'\\f'");
		else if(ch=='\'') log.write("'\\'");
		else if(ch=='\\') log.write("'\\\\'");
		else if(ch=='"') log.write("'\\\"'");
		else if(ch<' ') {
			log.write("'\\u");
			String hex = Integer.toHexString(ch);
			for(int l=hex.length(); l<4; l++) log.write('0');
			log.write(hex);
			log.write('\'');
		} else {
			log.write('\'');
			log.write(ch);
			log.write('\'');
		}
	}

private void log ( char ch ) throws IOException { if ( ch == ' ' ) log . write ( "'\\t'" ) ; else if ( ch == ' ' ) log . write ( "'\\b'" ) ; else if ( ch == ' ' ) log . write ( "'\\n'" ) ; else if ( ch == ' ' ) log . write ( "'\\r'" ) ; else if ( ch == ' ' ) log . write ( "'\\f'" ) ; else if ( ch == ' ' ) log . write ( "'\\'" ) ; else if ( ch == ' ' ) log . write ( "'\\\\'" ) ; else if ( ch == ' ' ) log . write ( "'\\\"'" ) ; else if ( ch < ' ' ) { log . write ( "'\\u" ) ; String hex = Integer . toHexString ( ch ) ; for ( int l = hex . length ( ) ; l < 4 ; l ++ ) log . write ( ' ' ) ; log . write ( hex ) ; log . write ( ' ' ) ; } else { log . write ( ' ' ) ; log . write ( ch ) ; log . write ( ' ' ) ; } }

Writes a character, unicode escaping as needed.

Writes a character unicode escaping as needed .


private void log(String value) throws IOException {
		if(value==null) {
			log.write("(String)null");
		} else {
			log.write('"');
			for(int i=0, len=value.length(); i<len; i++) {
				char ch = value.charAt(i);
				if(ch=='\t') log.write("\\t");
				else if(ch=='\b') log.write("\\b");
				else if(ch=='\n') log.write("\\n");
				else if(ch=='\r') log.write("\\r");
				else if(ch=='\f') log.write("\\f");
				else if(ch=='\\') log.write("\\\\");
				else if(ch=='"') log.write("\\\"");
				else if(ch<' ') {
					log.write("\\u");
					String hex = Integer.toHexString(ch);
					for(int l=hex.length(); l<4; l++) log.write('0');
					log.write(hex);
				} else {
					log.write(ch);
				}
			}
			log.write('"');
		}
	}

private void log ( String value ) throws IOException { if ( value == null ) { log . write ( "(String)null" ) ; } else { log . write ( ' ' ) ; for ( int i = 0 , len = value . length ( ) ; i < len ; i ++ ) { char ch = value . charAt ( i ) ; if ( ch == ' ' ) log . write ( "\\t" ) ; else if ( ch == ' ' ) log . write ( "\\b" ) ; else if ( ch == ' ' ) log . write ( "\\n" ) ; else if ( ch == ' ' ) log . write ( "\\r" ) ; else if ( ch == ' ' ) log . write ( "\\f" ) ; else if ( ch == ' ' ) log . write ( "\\\\" ) ; else if ( ch == ' ' ) log . write ( "\\\"" ) ; else if ( ch < ' ' ) { log . write ( "\\u" ) ; String hex = Integer . toHexString ( ch ) ; for ( int l = hex . length ( ) ; l < 4 ; l ++ ) log . write ( ' ' ) ; log . write ( hex ) ; } else { log . write ( ch ) ; } } log . write ( ' ' ) ; } }

Writes a String, unicode escaping as needed.

Writes a String unicode escaping as needed .


public static ContentValues putAll(ContentValues target, Object... values) {
        int length = values.length;
        checkArgument(length % 2 == 0, "values length must be a multiple of two");
        for (int i = 0; i < length; i += 2) {
            String key = (String) values[i];
            Object val = values[i + 1];
            if (val == null) {
                target.putNull(key);
            } else if (val instanceof String) {
                target.put(key, (String) val);
            } else if (val instanceof Long) {
                target.put(key, (Long) val);
            } else if (val instanceof Integer) {
                target.put(key, (Integer) val);
            } else if (val instanceof Boolean) {
                target.put(key, (Boolean) val);
            } else if (val instanceof Double) {
                target.put(key, (Double) val);
            } else if (val instanceof Float) {
                target.put(key, (Float) val);
            } else if (val instanceof byte[]) {
                target.put(key, (byte[]) val);
            } else if (val instanceof Byte) {
                target.put(key, (Byte) val);
            } else if (val instanceof Short) {
                target.put(key, (Short) val);
            } else {
                throw new IllegalArgumentException(
                        "ContentValues does not support values of type " + val.getClass().getName()
                                + " (provided for key '" + key + "')");
            }
        }

Put all of the values into the existing set.

@param values length must be a multiple of two: {@code String key, Object value, ...}
@throws IllegalArgumentException if a value type is not supported

Put all of the values into the existing set .


public void moveCameraToLastLocation(GoogleMap map, float zoom) {
        mProvider.getLastLocation().subscribe(location -> map.moveCamera(CameraUpdateFactory
                .newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), zoom)));
    }

public void moveCameraToLastLocation ( GoogleMap map , float zoom ) { mProvider . getLastLocation ( ) . subscribe ( location -> map . moveCamera ( CameraUpdateFactory . newLatLngZoom ( new LatLng ( location . getLatitude ( ) , location . getLongitude ( ) ) , zoom ) ) ) ; }

Move and zoom to the most recently reported location.

@see CameraUpdateFactory#newLatLngZoom(LatLng, float)

Move and zoom to the most recently reported location .


public void animateCameraToIncludePosition(GoogleMap map, LatLng position, long delay) {
        if (!map.getProjection().getVisibleRegion().latLngBounds.contains(position)) {
            if (delay > 0) {
                new Handler(Looper.getMainLooper())
                        .postDelayed(() -> doAnimateCameraToIncludePosition(map, position), delay);
            } else {
                doAnimateCameraToIncludePosition(map, position);
            }
        }
    }

public void animateCameraToIncludePosition ( GoogleMap map , LatLng position , long delay ) { if ( ! map . getProjection ( ) . getVisibleRegion ( ) . latLngBounds . contains ( position ) ) { if ( delay > 0 ) { new Handler ( Looper . getMainLooper ( ) ) . postDelayed ( ( ) -> doAnimateCameraToIncludePosition ( map , position ) , delay ) ; } else { doAnimateCameraToIncludePosition ( map , position ) ; } } }

If the position is not visible on the map, animate the camera to include it, after the delay.

If the position is not visible on the map animate the camera to include it after the delay .


public static Animator circleToRect(View circle, View rect) {
        return circleRect(circle, rect, true);
    }

public static Animator circleToRect ( View circle , View rect ) { return circleRect ( circle , rect , true ) ; }

Get an Animator that reveals the rectangular View from the circular View.

@param circle to start reveal from
@param rect   to reveal, probably should already be {@link View#INVISIBLE invisible}

Get an Animator that reveals the rectangular View from the circular View .


public static Animator circleFromRect(View circle, View rect) {
        return circleRect(circle, rect, false);
    }

public static Animator circleFromRect ( View circle , View rect ) { return circleRect ( circle , rect , false ) ; }

Get an Animator that "unreveals" the rectangular View to the circular View.

@param circle to end "unreveal" at
@param rect   to "unreveal", will be {@link View#INVISIBLE invisible} when the animation
ends

Get an Animator that unreveals the rectangular View to the circular View .


public static Transition arcMotion(Context context) {
        if (sArc == null) {
            sArc = TransitionInflater.from(context).inflateTransition(
                    R.transition.sprockets_arc_motion);
        }
        return sArc;
    }

public static Transition arcMotion ( Context context ) { if ( sArc == null ) { sArc = TransitionInflater . from ( context ) . inflateTransition ( R . transition . sprockets_arc_motion ) ; } return sArc ; }


public static StyleSpan bold(int i) {
        if (sBolds == null) {
            sBolds = new ArrayList<>();
            sBolds.add(bold());
        }
        if (i < sBolds.size()) {
            return sBolds.get(i);
        } else {
            StyleSpan bold = new StyleSpan(Typeface.BOLD);
            sBolds.add(bold);
            return bold;
        }
    }

public static StyleSpan bold ( int i ) { if ( sBolds == null ) { sBolds = new ArrayList <> ( ) ; sBolds . add ( bold ( ) ) ; } if ( i < sBolds . size ( ) ) { return sBolds . get ( i ) ; } else { StyleSpan bold = new StyleSpan ( Typeface . BOLD ) ; sBolds . add ( bold ) ; return bold ; } }

Get a cached bold span.

@param i starts at zero
@since 2.6.0


public static ViewPropertyAnimator scaleIn(View view) {
        return scale(view, 1.0f, enterScreen(), R.integer.anim_duration_enter);
    }

public static ViewPropertyAnimator scaleIn ( View view ) { return scale ( view , 1.0f , enterScreen ( ) , R . integer . anim_duration_enter ) ; }

Scale in the View to full size.

@since 4.0.0


public static ViewPropertyAnimator scaleOut(View view) {
        return scale(view, 0.0f, exitScreen(), R.integer.anim_duration_exit);
    }

public static ViewPropertyAnimator scaleOut ( View view ) { return scale ( view , 0.0f , exitScreen ( ) , R . integer . anim_duration_exit ) ; }

Scale out the View to zero size.

@since 4.0.0


public static ViewPropertyAnimator scaleShowNext(ViewSwitcher view, Runnable endAction) {
        return scale(view, view::showNext, endAction);
    }

public static ViewPropertyAnimator scaleShowNext ( ViewSwitcher view , Runnable endAction ) { return scale ( view , view :: showNext , endAction ) ; }

Scale out the ViewSwitcher, show the next View, scale it back in, and run the action.

@since 4.0.0

Scale out the ViewSwitcher show the next View scale it back in and run the action .


public static int getCount(Context context, Uri uri) {
        String[] proj = {"COUNT(*)"};
        return Cursors.firstInt(context.getContentResolver().query(uri, proj, null, null, null));
    }

public static int getCount ( Context context , Uri uri ) { String [ ] proj = { "COUNT(*)" } ; return Cursors . firstInt ( context . getContentResolver ( ) . query ( uri , proj , null , null , null ) ) ; }

Get the number of rows at the URI.

@return {@link Integer#MIN_VALUE} if the URI could not be queried
@since 2.3.0


public static String concatAddressLines(Address address, String delimiter) {
        StringBuilder s = new StringBuilder(256);
        for (int i = 0, max = address.getMaxAddressLineIndex(); i <= max; i++) {
            if (i > 0) {
                s.append(delimiter);
            }
            s.append(address.getAddressLine(i));
        }
        return s.toString();
    }

public static String concatAddressLines ( Address address , String delimiter ) { StringBuilder s = new StringBuilder ( 256 ) ; for ( int i = 0 , max = address . getMaxAddressLineIndex ( ) ; i <= max ; i ++ ) { if ( i > 0 ) { s . append ( delimiter ) ; } s . append ( address . getAddressLine ( i ) ) ; } return s . toString ( ) ; }

Get a single line address which uses the delimiter between the original lines.

Get a single line address which uses the delimiter between the original lines .


public static GoogleApiClient connect(GoogleApiClient client, ConnectedListener connected,
                                          OnConnectionFailedListener failed) {
        client.registerConnectionCallbacks(new ConnectionListener(connected));
        client.registerConnectionFailedListener(failed);
        client.connect();
        return client;
    }

public static GoogleApiClient connect ( GoogleApiClient client , ConnectedListener connected , OnConnectionFailedListener failed ) { client . registerConnectionCallbacks ( new ConnectionListener ( connected ) ) ; client . registerConnectionFailedListener ( failed ) ; client . connect ( ) ; return client ; }

Register the listeners and then connect the client.

Register the listeners and then connect the client .


@SuppressLint("CommitTransaction")
    private static FragmentTransaction transit(FragmentManager fm, int transit) {
        return fm != null ? fm.beginTransaction().setTransition(transit) : null;
    }

@ SuppressLint ( "CommitTransaction" ) private static FragmentTransaction transit ( FragmentManager fm , int transit ) { return fm != null ? fm . beginTransaction ( ) . setTransition ( transit ) : null ; }

Begin a transaction that uses the transition.

@return null if the FragmentManager is null

Begin a transaction that uses the transition .


@Override
    public int getForegroundColor() {
        return Color.argb(mAlpha, Color.red(mColor), Color.green(mColor), Color.blue(mColor));
    }

@ Override public int getForegroundColor ( ) { return Color . argb ( mAlpha , Color . red ( mColor ) , Color . green ( mColor ) , Color . blue ( mColor ) ) ; }

Get the result of applying the alpha to the color.

Get the result of applying the alpha to the color .


public static void setOnClickListeners(OnClickListener listener, View... views) {
        for (View view : views) {
            view.setOnClickListener(listener);
        }
    }

public static void setOnClickListeners ( OnClickListener listener , View ... views ) { for ( View view : views ) { view . setOnClickListener ( listener ) ; } }

Set the listener on all of the Views.

@since 4.0.0


public static String getLevelName(int level) {
        switch (level) {
            case VERBOSE:
                return "VERBOSE";
            case DEBUG:
                return "DEBUG";
            case INFO:
                return "INFO";
            case WARN:
                return "WARN";
            case ERROR:
                return "ERROR";
            case ASSERT:
                return "ASSERT";
            default:
                return "?";
        }
    }

public static String getLevelName ( int level ) { switch ( level ) { case VERBOSE : return "VERBOSE" ; case DEBUG : return "DEBUG" ; case INFO : return "INFO" ; case WARN : return "WARN" ; case ERROR : return "ERROR" ; case ASSERT : return "ASSERT" ; default : return "?" ; } }

Get the name of the level.

@param level one of the Android {@link android.util.Log Log} constants


public static ActivityOptions makeScaleUpAnimation(View source) {
        return ActivityOptions.makeScaleUpAnimation(
                source, 0, 0, source.getWidth(), source.getHeight());
    }

public static ActivityOptions makeScaleUpAnimation ( View source ) { return ActivityOptions . makeScaleUpAnimation ( source , 0 , 0 , source . getWidth ( ) , source . getHeight ( ) ) ; }

Scale the new Activity from the View to its full size.

@see ActivityOptions#makeScaleUpAnimation(View, int, int, int, int)

Scale the new Activity from the View to its full size .


public static void show(View view) {
        view.postDelayed(() -> Managers.inputMethod(view.getContext()).showSoftInput(view, 0),
                300L); // give InputMethodManager some time to recognise that the View is focused
    }

Show the current input method for the focused View which can receive input.

Show the current input method for the focused View which can receive input .


public static void hide(View view) {
        Managers.inputMethod(view.getContext()).hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

public static void hide ( View view ) { Managers . inputMethod ( view . getContext ( ) ) . hideSoftInputFromWindow ( view . getWindowToken ( ) , 0 ) ; }

Hide the input method for the View's window.

Hide the input method for the View s window .


public static boolean hasPosition(Cursor cursor, int position) {
        return !cursor.isClosed() && position >= 0 && position < cursor.getCount();
    }

public static boolean hasPosition ( Cursor cursor , int position ) { return ! cursor . isClosed ( ) && position >= 0 && position < cursor . getCount ( ) ; }

True if the cursor has a row at the position.

@since 4.0.0

True if the cursor has a row at the position .


public static int count(Cursor cursor, boolean close) {
        int count = cursor.getCount();
        close(cursor, close);
        return count;
    }

public static int count ( Cursor cursor , boolean close ) { int count = cursor . getCount ( ) ; close ( cursor , close ) ; return count ; }

Get the number of rows in the cursor.

@param close true to close the cursor or false to leave it open


public static int firstInt(Cursor cursor, boolean close) {
        int i = cursor.moveToFirst() ? cursor.getInt(0) : Integer.MIN_VALUE;
        close(cursor, close);
        return i;
    }

public static int firstInt ( Cursor cursor , boolean close ) { int i = cursor . moveToFirst ( ) ? cursor . getInt ( 0 ) : Integer . MIN_VALUE ; close ( cursor , close ) ; return i ; }

Get the int value in the first row and column.

@param close true to close the cursor or false to leave it open
@return {@link Integer#MIN_VALUE} if the cursor is empty
@since 2.5.0

Get the int value in the first row and column .


public static long firstLong(Cursor cursor, boolean close) {
        long l = cursor.moveToFirst() ? cursor.getLong(0) : Long.MIN_VALUE;
        close(cursor, close);
        return l;
    }

public static long firstLong ( Cursor cursor , boolean close ) { long l = cursor . moveToFirst ( ) ? cursor . getLong ( 0 ) : Long . MIN_VALUE ; close ( cursor , close ) ; return l ; }

Get the long value in the first row and column.

@param close true to close the cursor or false to leave it open
@return {@link Long#MIN_VALUE} if the cursor is empty

Get the long value in the first row and column .


@Nullable
    public static String firstString(Cursor cursor, boolean close) {
        String s = cursor.moveToFirst() ? cursor.getString(0) : null;
        close(cursor, close);
        return s;
    }

@ Nullable public static String firstString ( Cursor cursor , boolean close ) { String s = cursor . moveToFirst ( ) ? cursor . getString ( 0 ) : null ; close ( cursor , close ) ; return s ; }

Get the String value in the first row and column.

@param close true to close the cursor or false to leave it open
@return null if the cursor is empty

Get the String value in the first row and column .


public static int[] allInts(Cursor cursor, boolean close) {
        int[] i = EMPTY_INT_ARRAY;
        if (cursor.moveToFirst()) {
            i = new int[cursor.getCount()];
            do {
                i[cursor.getPosition()] = cursor.getInt(0);
            } while (cursor.moveToNext());
        }
        close(cursor, close);
        return i;
    }

public static int [ ] allInts ( Cursor cursor , boolean close ) { int [ ] i = EMPTY_INT_ARRAY ; if ( cursor . moveToFirst ( ) ) { i = new int [ cursor . getCount ( ) ] ; do { i [ cursor . getPosition ( ) ] = cursor . getInt ( 0 ) ; } while ( cursor . moveToNext ( ) ) ; } close ( cursor , close ) ; return i ; }

Get all int values in the first column.

@param close true to close the cursor or false to leave it open
@since 2.5.0

Get all int values in the first column .


public static long[] allLongs(Cursor cursor, boolean close) {
        long[] l = EMPTY_LONG_ARRAY;
        if (cursor.moveToFirst()) {
            l = new long[cursor.getCount()];
            do {
                l[cursor.getPosition()] = cursor.getLong(0);
            } while (cursor.moveToNext());
        }
        close(cursor, close);
        return l;
    }

public static long [ ] allLongs ( Cursor cursor , boolean close ) { long [ ] l = EMPTY_LONG_ARRAY ; if ( cursor . moveToFirst ( ) ) { l = new long [ cursor . getCount ( ) ] ; do { l [ cursor . getPosition ( ) ] = cursor . getLong ( 0 ) ; } while ( cursor . moveToNext ( ) ) ; } close ( cursor , close ) ; return l ; }

Get all long values in the first column.

@param close true to close the cursor or false to leave it open

Get all long values in the first column .


public static String[] allStrings(Cursor cursor, boolean close) {
        String[] s = EMPTY_STRING_ARRAY;
        if (cursor.moveToFirst()) {
            s = new String[cursor.getCount()];
            do {
                s[cursor.getPosition()] = cursor.getString(0);
            } while (cursor.moveToNext());
        }
        close(cursor, close);
        return s;
    }

public static String [ ] allStrings ( Cursor cursor , boolean close ) { String [ ] s = EMPTY_STRING_ARRAY ; if ( cursor . moveToFirst ( ) ) { s = new String [ cursor . getCount ( ) ] ; do { s [ cursor . getPosition ( ) ] = cursor . getString ( 0 ) ; } while ( cursor . moveToNext ( ) ) ; } close ( cursor , close ) ; return s ; }

Get all String values in the first column.

@param close true to close the cursor or false to leave it open

Get all String values in the first column .


@BindingAdapter(value = {"sprockets_placeholder", "sprockets_load", "sprockets_resize",
            "sprockets_transform"}, requireAll = false)
    public static void load(ImageView view, Drawable placeholder, Uri load, boolean resize,
                            String transform) {
        RequestCreator req = Picasso.with(view.getContext()).load(load).placeholder(placeholder);
        if (resize) {
            req.fit().centerCrop(); // view width/height isn't available yet
        }
        if (TextUtils.equals(transform, "circle")) {
            req.transform(Transformations.circle());
        }
        req.into(view);
    }

Set a placeholder before loading an image, optionally resizing and transforming it. All
attributes are optional.

@param transform can be "circle"

Set a placeholder before loading an image optionally resizing and transforming it . All attributes are optional .


public static int getOrientation(RecyclerView view) {
        LayoutManager layout = view.getLayoutManager();
        if (layout instanceof LinearLayoutManager) {
            return ((LinearLayoutManager) layout).getOrientation();
        } else if (layout instanceof StaggeredGridLayoutManager) {
            return ((StaggeredGridLayoutManager) layout).getOrientation();
        }
        return -1;
    }

public static int getOrientation ( RecyclerView view ) { LayoutManager layout = view . getLayoutManager ( ) ; if ( layout instanceof LinearLayoutManager ) { return ( ( LinearLayoutManager ) layout ) . getOrientation ( ) ; } else if ( layout instanceof StaggeredGridLayoutManager ) { return ( ( StaggeredGridLayoutManager ) layout ) . getOrientation ( ) ; } return - 1 ; }

Get the orientation of the RecyclerView's LayoutManager.

@return -1 if the RecyclerView doesn't have a LayoutManager
@see RecyclerView#VERTICAL
@see RecyclerView#HORIZONTAL

Get the orientation of the RecyclerView s LayoutManager .


public static int getSpanCount(RecyclerView view) {
        LayoutManager layout = view.getLayoutManager();
        if (layout != null) {
            if (layout instanceof GridLayoutManager) {
                return ((GridLayoutManager) layout).getSpanCount();
            } else if (layout instanceof StaggeredGridLayoutManager) {
                return ((StaggeredGridLayoutManager) layout).getSpanCount();
            }
            return 1; // assuming LinearLayoutManager
        }
        return 0;
    }

public
static
int
getSpanCount
(
RecyclerView
view
)
{
LayoutManager
layout
=
view
.
getLayoutManager
(
)
;
if
(
layout
!=
)
{
if
(
layout
instanceof
GridLayoutManager
)
{
return
(
(
GridLayoutManager
)
layout
)
.
getSpanCount
(
)
;
}
else
if
(
layout
instanceof
StaggeredGridLayoutManager
)
{
return
(
(
StaggeredGridLayoutManager
)
layout
)
.
getSpanCount
(
)
;
}
return
1
;
// assuming LinearLayoutManager
}
return
0
;
}

Get the number of spans laid out by the RecyclerView's LayoutManager.

@return 0 if the RecyclerView doesn't have a LayoutManager

Get the number of spans laid out by the RecyclerView s LayoutManager .


public static RelativeLayout.LayoutParams addRule(View view, int verb, int anchor) {
        RelativeLayout.LayoutParams params = getParams(view);
        params.addRule(verb, anchor);
        view.requestLayout();
        return params;
    }

public static RelativeLayout . LayoutParams addRule ( View view , int verb , int anchor ) { RelativeLayout . LayoutParams params = getParams ( view ) ; params . addRule ( verb , anchor ) ; view . requestLayout ( ) ; return params ; }

Add the rule to the View's RelativeLayout params and request a layout of the View.

Add the rule to the View s RelativeLayout params and request a layout of the View .


public boolean wasRead() {
        int pos = getPosition();
        if (pos < 0 || pos >= mRead.length) {
            return false;
        }
        boolean read = mRead[pos];
        if (!read) {
            mRead[pos] = true;
        }
        return read;
    }

public boolean wasRead ( ) { int pos = getPosition ( ) ; if ( pos < 0 || pos >= mRead . length ) { return false ; } boolean read = mRead [ pos ] ; if ( ! read ) { mRead [ pos ] = true ; } return read ; }

True if this method has been previously called for the current row. False if the cursor is
before the first row or after the last row.

True if this method has been previously called for the current row . False if the cursor is before the first row or after the last row .


public static Looper mineOrMain() {
        Looper looper = Looper.myLooper();
        return looper != null ? looper : Looper.getMainLooper();
    }

public static Looper mineOrMain ( ) { Looper looper = Looper . myLooper ( ) ; return looper != null ? looper : Looper . getMainLooper ( ) ; }

Get this thread's Looper, if it's a Looper thread. Otherwise get the main thread Looper.

Get this thread s Looper if it s a Looper thread . Otherwise get the main thread Looper .


@SuppressWarnings("unchecked")
    public static <E> List<E> values(SparseArray<E> array) {
        return (List<E>) values(array, null, null, null, null);
    }

@ SuppressWarnings ( "unchecked" ) public static < E > List < E > values ( SparseArray < E > array ) { return ( List < E > ) values ( array , null , null , null , null ) ; }


@SuppressWarnings("unchecked")
    public static <E> List<E> values(LongSparseArray<E> array) {
        return (List<E>) values(null, null, null, null, array);
    }

@ SuppressWarnings ( "unchecked" ) public static < E > List < E > values ( LongSparseArray < E > array ) { return ( List < E > ) values ( null , null , null , null , array ) ; }


private void checkAdapter() {
        PagerAdapter adapter = mPager.getAdapter();
        if (mAdapter != adapter) {
            if (mAdapter != null) {
                mAdapter.unregisterDataSetObserver(mObserver);
            }
            mAdapter = adapter;
            if (mAdapter != null) {
                mAdapter.registerDataSetObserver(mObserver);
            }
            reset();
        }
    }

private void checkAdapter ( ) { PagerAdapter adapter = mPager . getAdapter ( ) ; if ( mAdapter != adapter ) { if ( mAdapter != null ) { mAdapter . unregisterDataSetObserver ( mObserver ) ; } mAdapter = adapter ; if ( mAdapter != null ) { mAdapter . registerDataSetObserver ( mObserver ) ; } reset ( ) ; } }

Check if the pager has a new adapter and switch to it if it does.

Check if the pager has a new adapter and switch to it if it does .


private void checkDrawable() {
        Drawable drawable = mView.getDrawable();
        if (mDrawable != drawable) {
            /* get the latest View size and ensure that it's been measured */
            mViewWidth = mView.getWidth();
            mViewHeight = mView.getHeight();
            if (mViewWidth > 0 && mViewHeight > 0) {
                mDrawable = drawable; // don't save until now so above is repeated until measured
                if (mDrawable != null) {
                    mDrawableWidth = mDrawable.getIntrinsicWidth();
                    mDrawableHeight = mDrawable.getIntrinsicHeight();
                    if (mDrawableWidth > 0 && mDrawableHeight > 0) { // e.g. colors don't have size
                        float widthRatio = (float) mViewWidth / mDrawableWidth;
                        float heightRatio = (float) mViewHeight / mDrawableHeight;
                        mScale = widthRatio > heightRatio ? widthRatio : heightRatio;
                    } else { // nothing to scale, ensure matrix is skipped
                        mScale = 0.0f;
                    }
                }
            } else { // don't update matrix until View is measured
                mScale = 0.0f;
            }
            reset();
        }
    }

Check if the ImageView has a new Drawable and calculate the new scaling if it does.

Check if the ImageView has a new Drawable and calculate the new scaling if it does .


private void updateMatrix(int position, float offset) {
        if (mDrawable != null && mScale > 0.0f) {
            if (mPageCount == -1 && mAdapter != null) { // cache page count and translation values
                mPageCount = mAdapter.getCount();
                if (mPageCount > 1) {
                    mPageX = (mDrawableWidth * mScale - mViewWidth) / (mPageCount - 1);
                    mPageY = (mDrawableHeight * mScale - mViewHeight) / (mPageCount - 1);
                }
            }
            mMatrix.setTranslate(-mPageX * position - mPageX * offset,
                    -mPageY * position - mPageY * offset);
            mMatrix.preScale(mScale, mScale);
            mView.setScaleType(MATRIX);
            mView.setImageMatrix(mMatrix);
        }
    }

Scale the image and translate it according to the pager position and offset.

Scale the image and translate it according to the pager position and offset .


private int updDel(int op, Uri uri, ContentValues vals, String sel, String[] args) {
        /* get the IDs of records that will be affected */
        Sql sql = elements(op, uri, new String[]{"rowid"}, sel, args, null);
        long[] ids = Cursors.allLongs(sql.mResult);
        /* update or delete the records and then notify about any changes */
        SQLiteDatabase db = mHelper.getWritableDatabase();
        int rows = op == UPDATE ? db.update(sql.table(), vals, sql.sel(), sql.args())
                : db.delete(sql.table(), !TextUtils.isEmpty(sql.sel()) ? sql.sel() : "1",
                        sql.args());
        if (rows > 0) {
            for (long id : ids) {
                notifyChange(ContentUris.withAppendedId(sql.notifyUri(), id), uri);
            }
        }
        return rows;
    }

Update or delete records and get the number of rows affected.

Update or delete records and get the number of rows affected .


private Sql elements(int op, Uri uri, String[] proj, String sel, String[] args, String order) {
        MutableSql sql = translate(uri);
        if (sql == null) {
            sql = Sql.create();
        }
        if (sql.table() == null) {
            sql.table(uri.getPathSegments().get(0));
        }
        if (sql.notifyUri() == null && op != SELECT) {
            sql.notifyUri(uri.buildUpon().path(sql.table()).clearQuery().fragment(null).build());
        }
        if (op != INSERT) { // run the query and return the cursor
            String from = sql.join() != null ? sql.table() + ' ' + sql.join() : sql.table();
            if ((sql.sel() == null || sql.args() == null) && uri.getPathSegments().size() == 2) {
                try { // filter on ID if URI in /table/id format
                    long id = ContentUris.parseId(uri);
                    if (id > 0) {
                        if (sql.sel() == null) {
                            sql.sel("rowid = ?");
                        }
                        if (sql.args() == null) {
                            sql.args(String.valueOf(id));
                        }
                    }
                } catch (NumberFormatException e) { // last segment not a number
                }
            }
            if (sel != null) { // append caller values
                sql.sel(DatabaseUtils.concatenateWhere(sql.sel(), sel));
            }
            if (args != null) {
                sql.args(DatabaseUtils.appendSelectionArgs(sql.args(), args));
            }
            String groupBy = uri.getQueryParameter(GROUP_BY);
            if (groupBy != null) { // prefer caller's value
                sql.groupBy(groupBy);
            }
            String having = uri.getQueryParameter(HAVING);
            if (having != null) {
                sql.having(having);
            }
            if (order != null) {
                sql.orderBy(order);
            }
            String limit = uri.getQueryParameter(LIMIT);
            if (limit != null) {
                sql.limit(limit);
            }
            sql.mResult = mHelper.getReadableDatabase()
                    .query(from, proj, sql.sel(), sql.args(), sql.groupBy(), sql.having(),
                            sql.orderBy(), sql.limit());
        }
        return sql;
    }

Get the updated SQL elements for the URI and, when not inserting, a cursor with the query
results.

Get the updated SQL elements for the URI and when not inserting a cursor with the query results .


public static int getByteCount(int width, int height, Config config) {
        int bytes = 0;
        switch (config) {
            case ALPHA_8:
                bytes = 1;
                break;
            case RGB_565:
                bytes = 2;
                break;
            case ARGB_4444:
                bytes = 2;
                break;
            case ARGB_8888:
                bytes = 4;
                break;
        }
        return width * height * bytes;
    }

public static int getByteCount ( int width , int height , Config config ) { int bytes = 0 ; switch ( config ) { case ALPHA_8 : bytes = 1 ; break ; case RGB_565 : bytes = 2 ; break ; case ARGB_4444 : bytes = 2 ; break ; case ARGB_8888 : bytes = 4 ; break ; } return width * height * bytes ; }

Get the number of bytes that would be used to store a bitmap with the size, in pixels, and
storage config.

Get the number of bytes that would be used to store a bitmap with the size in pixels and storage config .


@Nullable
    public static Bitmap mutable(Bitmap source) {
        if (source.isMutable()) {
            return source;
        }
        Config config = source.getConfig();
        Bitmap bm = source.copy(config != null ? config : ARGB_8888, true);
        if (bm != null) {
            source.recycle();
        }
        return bm;
    }

@ Nullable public static Bitmap mutable ( Bitmap source ) { if ( source . isMutable ( ) ) { return source ; } Config config = source . getConfig ( ) ; Bitmap bm = source . copy ( config != null ? config : ARGB_8888 , true ) ; if ( bm != null ) { source . recycle ( ) ; } return bm ; }

If the bitmap is immutable, get a mutable copy of it. After a copy is created, the source
bitmap will be recycled. If the bitmap is already mutable, it will be returned.

@return null if a copy could not be made

If the bitmap is immutable get a mutable copy of it . After a copy is created the source bitmap will be recycled . If the bitmap is already mutable it will be returned .


public static boolean hasActivity(Context context, Intent intent) {
        return context.getPackageManager().resolveActivity(intent, MATCH_DEFAULT_ONLY) != null;
    }

public static boolean hasActivity ( Context context , Intent intent ) { return context . getPackageManager ( ) . resolveActivity ( intent , MATCH_DEFAULT_ONLY ) != null ; }

True if the Intent can be resolved to an Activity.

True if the Intent can be resolved to an Activity .


public static Intent mailto(List<String> to, List<String> cc, List<String> bcc, String subject,
                                String body) {
        return new Intent(ACTION_SENDTO, Uris.mailto(to, cc, bcc, subject, body));
    }

public static Intent mailto ( List < String > to , List < String > cc , List < String > bcc , String subject , String body ) { return new Intent ( ACTION_SENDTO , Uris . mailto ( to , cc , bcc , subject , body ) ) ; }

Get an Activity Intent that launches an email app with the headers. Any null or empty
parameters are skipped. The subject and body will be encoded.

@since 4.0.0

Get an Activity Intent that launches an email app with the headers . Any null or empty parameters are skipped . The subject and body will be encoded .


public void setDefaultContentView() {
        setContentView(R.layout.sprockets_panes, R.id.panes, R.id.pane1, R.id.pane2);
    }

public void setDefaultContentView ( ) { setContentView ( R . layout . sprockets_panes , R . id . panes , R . id . pane1 , R . id . pane2 ) ; }


@Nullable
    @SuppressWarnings("unchecked")
    public <T extends Fragment> T findFragmentByPane(@IntRange(from = 1, to = 2) int pane) {
        String tag = Elements.get(sPanes, pane - 1);
        return tag != null ? (T) getFragmentManager().findFragmentByTag(tag) : null;
    }

@ Nullable @ SuppressWarnings ( "unchecked" ) public < T extends Fragment > T findFragmentByPane ( @ IntRange ( from = 1 , to = 2 ) int pane ) { String tag = Elements . get ( sPanes , pane - 1 ) ; return tag != null ? ( T ) getFragmentManager ( ) . findFragmentByTag ( tag ) : null ; }

Get the fragment that is displayed in the pane.

@return null if a fragment hasn't been added to the pane yet

Get the fragment that is displayed in the pane .


public static Bundle of(String key1, int value1, String key2, int value2) {
        Bundle b = new Bundle(2);
        b.putInt(key1, value1);
        b.putInt(key2, value2);
        return b;
    }

public static Bundle of ( String key1 , int value1 , String key2 , int value2 ) { Bundle b = new Bundle ( 2 ) ; b . putInt ( key1 , value1 ) ; b . putInt ( key2 , value2 ) ; return b ; }


public static Intent newIntent(Context context, String action, Uri data, ContentValues values) {
        return newIntent(context, action, data, values, null, null);
    }

public static Intent newIntent ( Context context , String action , Uri data , ContentValues values ) { return newIntent ( context , action , data , values , null , null ) ; }

Get an Intent to insert or update rows of the content.

@param action must be {@link Intent#ACTION_INSERT ACTION_INSERT} or
{@link Intent#ACTION_EDIT ACTION_EDIT}
@since 4.0.0

Get an Intent to insert or update rows of the content .


public static Intent newUpdateIntent(Context context, Uri data, ContentValues values,
                                         String selection, String[] selectionArgs) {
        return newIntent(context, ACTION_EDIT, data, values, selection, selectionArgs);
    }

public static Intent newUpdateIntent ( Context context , Uri data , ContentValues values , String selection , String [ ] selectionArgs ) { return newIntent ( context , ACTION_EDIT , data , values , selection , selectionArgs ) ; }

Get an Intent to update the selected rows of the content.

@since 4.0.0

Get an Intent to update the selected rows of the content .


public static Intent newDeleteIntent(Context context, Uri data) {
        return newIntent(context, ACTION_DELETE, data, null, null, null);
    }

public static Intent newDeleteIntent ( Context context , Uri data ) { return newIntent ( context , ACTION_DELETE , data , null , null , null ) ; }

Get an Intent to delete rows of the content.

@since 4.0.0

Get an Intent to delete rows of the content .


public static Intent newDeleteIntent(Context context, Uri data, String selection,
                                         String[] selectionArgs) {
        return newIntent(context, ACTION_DELETE, data, null, selection, selectionArgs);
    }

public static Intent newDeleteIntent ( Context context , Uri data , String selection , String [ ] selectionArgs ) { return newIntent ( context , ACTION_DELETE , data , null , selection , selectionArgs ) ; }

Get an Intent to delete the selected rows of the content.

@since 4.0.0

Get an Intent to delete the selected rows of the content .


public static int getActionBarSize(Context context) {
        TypedArray a = context.obtainStyledAttributes(sActionBarSize);
        int size = a.getDimensionPixelSize(0, 0);
        a.recycle();
        return size;
    }

public static int getActionBarSize ( Context context ) { TypedArray a = context . obtainStyledAttributes ( sActionBarSize ) ; int size = a . getDimensionPixelSize ( 0 , 0 ) ; a . recycle ( ) ; return size ; }

Get the ActionBar height in the Context's theme.

Get the ActionBar height in the Context s theme .


@Nullable
    public static Drawable getActionBarBackground(Context context) {
        int[] attrs = {android.R.attr.actionBarStyle};
        TypedArray a = context.obtainStyledAttributes(attrs);
        int id = a.getResourceId(0, 0);
        a.recycle();
        if (id > 0) {
            attrs[0] = android.R.attr.background;
            a = context.obtainStyledAttributes(id, attrs);
            Drawable background = a.getDrawable(0);
            a.recycle();
            return background;
        }
        return null;
    }

@ Nullable public static Drawable getActionBarBackground ( Context context ) { int [ ] attrs = { android . R . attr . actionBarStyle } ; TypedArray a = context . obtainStyledAttributes ( attrs ) ; int id = a . getResourceId ( 0 , 0 ) ; a . recycle ( ) ; if ( id > 0 ) { attrs [ 0 ] = android . R . attr . background ; a = context . obtainStyledAttributes ( id , attrs ) ; Drawable background = a . getDrawable ( 0 ) ; a . recycle ( ) ; return background ; } return null ; }

Get the ActionBar background in the Context's theme.

@return null if a background is not defined

Get the ActionBar background in the Context s theme .


public static boolean isConnected(Context context) {
        NetworkInfo info = Managers.connectivity(context).getActiveNetworkInfo();
        return info != null && info.isConnected();
    }

public static boolean isConnected ( Context context ) { NetworkInfo info = Managers . connectivity ( context ) . getActiveNetworkInfo ( ) ; return info != null && info . isConnected ( ) ; }


public void diff_cleanupEfficiency(LinkedList<Diff> diffs) {
    if (diffs.isEmpty()) {
      return;
    }
    boolean changes = false;
    Stack<Diff> equalities = new Stack<Diff>();  // Stack of equalities.
    String lastequality = null; // Always equal to equalities.lastElement().text
    ListIterator<Diff> pointer = diffs.listIterator();
    // Is there an insertion operation before the last equality.
    boolean pre_ins = false;
    // Is there a deletion operation before the last equality.
    boolean pre_del = false;
    // Is there an insertion operation after the last equality.
    boolean post_ins = false;
    // Is there a deletion operation after the last equality.
    boolean post_del = false;
    Diff thisDiff = pointer.next();
    Diff safeDiff = thisDiff;  // The last Diff that is known to be unsplitable.
    while (thisDiff != null) {
      if (thisDiff.operation == Operation.EQUAL) {
        // Equality found.
        if (thisDiff.text.length() < Diff_EditCost && (post_ins || post_del)) {
          // Candidate found.
          equalities.push(thisDiff);
          pre_ins = post_ins;
          pre_del = post_del;
          lastequality = thisDiff.text;
        } else {
          // Not a candidate, and can never become one.
          equalities.clear();
          lastequality = null;
          safeDiff = thisDiff;
        }
        post_ins = post_del = false;
      } else {
        // An insertion or deletion.
        if (thisDiff.operation == Operation.DELETE) {
          post_del = true;
        } else {
          post_ins = true;
        }
        /*
         * Five types to be split:
         * ABXYCD
         * AXCD
         * ABXC
         * AXCD
         * ABXC
         */
        if (lastequality != null
            && ((pre_ins && pre_del && post_ins && post_del)
                || ((lastequality.length() < Diff_EditCost / 2)
                    && ((pre_ins ? 1 : 0) + (pre_del ? 1 : 0)
                        + (post_ins ? 1 : 0) + (post_del ? 1 : 0)) == 3))) {
          //System.out.println("Splitting: '" + lastequality + "'");
          // Walk back to offending equality.
          while (thisDiff != equalities.lastElement()) {
            thisDiff = pointer.previous();
          }
          pointer.next();

          // Replace equality with a delete.
          pointer.set(new Diff(Operation.DELETE, lastequality));
          // Insert a corresponding an insert.
          pointer.add(thisDiff = new Diff(Operation.INSERT, lastequality));

          equalities.pop();  // Throw away the equality we just deleted.
          lastequality = null;
          if (pre_ins && pre_del) {
            // No changes made which could affect previous entry, keep going.
            post_ins = post_del = true;
            equalities.clear();
            safeDiff = thisDiff;
          } else {
            if (!equalities.empty()) {
              // Throw away the previous equality (it needs to be reevaluated).
              equalities.pop();
            }
            if (equalities.empty()) {
              // There are no previous questionable equalities,
              // walk back to the last known safe diff.
              thisDiff = safeDiff;
            } else {
              // There is an equality we can fall back to.
              thisDiff = equalities.lastElement();
            }
            while (thisDiff != pointer.previous()) {
              // Intentionally empty loop.
            }
            post_ins = post_del = false;
          }

          changes = true;
        }
      }
      thisDiff = pointer.hasNext() ? pointer.next() : null;
    }

    if (changes) {
      diff_cleanupMerge(diffs);
    }
  }

Reduce the number of edits by eliminating operationally trivial equalities.
@param diffs LinkedList of Diff objects.

Reduce the number of edits by eliminating operationally trivial equalities .


public LinkedList<Patch> patch_make(String text1, LinkedList<Diff> diffs) {
    if (text1 == null || diffs == null) {
      throw new IllegalArgumentException("Null inputs. (patch_make)");
    }

    LinkedList<Patch> patches = new LinkedList<Patch>();
    if (diffs.isEmpty()) {
      return patches;  // Get rid of the null case.
    }
    Patch patch = new Patch();
    int char_count1 = 0;  // Number of characters into the text1 string.
    int char_count2 = 0;  // Number of characters into the text2 string.
    // Start with text1 (prepatch_text) and apply the diffs until we arrive at
    // text2 (postpatch_text). We recreate the patches one by one to determine
    // context info.
    String prepatch_text = text1;
    String postpatch_text = text1;
    for (Diff aDiff : diffs) {
      if (patch.diffs.isEmpty() && aDiff.operation != Operation.EQUAL) {
        // A new patch starts here.
        patch.start1 = char_count1;
        patch.start2 = char_count2;
      }

      switch (aDiff.operation) {
      case INSERT:
        patch.diffs.add(aDiff);
        patch.length2 += aDiff.text.length();
        postpatch_text = postpatch_text.substring(0, char_count2)
            + aDiff.text + postpatch_text.substring(char_count2);
        break;
      case DELETE:
        patch.length1 += aDiff.text.length();
        patch.diffs.add(aDiff);
        postpatch_text = postpatch_text.substring(0, char_count2)
            + postpatch_text.substring(char_count2 + aDiff.text.length());
        break;
      case EQUAL:
        if (aDiff.text.length() <= 2 * Patch_Margin
            && !patch.diffs.isEmpty() && aDiff != diffs.getLast()) {
          // Small equality inside a patch.
          patch.diffs.add(aDiff);
          patch.length1 += aDiff.text.length();
          patch.length2 += aDiff.text.length();
        }

        if (aDiff.text.length() >= 2 * Patch_Margin) {
          // Time for a new patch.
          if (!patch.diffs.isEmpty()) {
            patch_addContext(patch, prepatch_text);
            patches.add(patch);
            patch = new Patch();
            // Unlike Unidiff, our patch lists have a rolling context.
            // http://code.google.com/p/google-diff-match-patch/wiki/Unidiff
            // Update prepatch text & pos to reflect the application of the
            // just completed patch.
            prepatch_text = postpatch_text;
            char_count1 = char_count2;
          }
        }
        break;
      }

      // Update the current character count.
      if (aDiff.operation != Operation.INSERT) {
        char_count1 += aDiff.text.length();
      }
      if (aDiff.operation != Operation.DELETE) {
        char_count2 += aDiff.text.length();
      }
    }
    // Pick up the leftover patch if not empty.
    if (!patch.diffs.isEmpty()) {
      patch_addContext(patch, prepatch_text);
      patches.add(patch);
    }

    return patches;
  }

Compute a list of patches to turn text1 into text2.
text2 is not provided, diffs are the delta between text1 and text2.
@param text1 Old text.
@param diffs Array of Diff objects for text1 to text2.
@return LinkedList of Patch objects.

Compute a list of patches to turn text1 into text2 . text2 is not provided diffs are the delta between text1 and text2 .


@Override
    public <R> Option<R> flatMap(ThrowableFunction1<T, Option<R>> function) {
        try {
            return function.apply(value);
        }
        catch (Throwable ex) {
            throw new BrokenFunctionException("Caught exception while applying function", ex);
        }
    }

Returns an Option consisting of the result of applying the given function to the current value.

@since 1.2

Returns an Option consisting of the result of applying the given function to the current value .


String convertSoapMessageAsString(SOAPMessage soapMessage) {
		if (soapMessage == null) {
			return "null";
		}
		try {
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			soapMessage.writeTo(os);
			return new String(os.toByteArray(), determineMessageEncoding(soapMessage));
		} catch (Exception e) {
			logger.error("Couldn't create string representation of soapMessage: " + soapMessage.toString());
			return "ERROR";
		}
	}

Converts a SOAPMessage instance to string representation.

Converts a SOAPMessage instance to string representation .


protected static synchronized FileObjectWrapper getOrCreateProfileProperties(final Filer filer, String fileName) throws IOException {

		FileObjectWrapper fileObject = traceeProfileProperties.get(fileName);

		if (fileObject == null) {

			fileObject = new FileObjectWrapper(filer.createResource(StandardLocation.SOURCE_OUTPUT, "", fileName, null));
			traceeProfileProperties.put(fileName, fileObject);

		}
		return fileObject;

	}

protected static synchronized FileObjectWrapper getOrCreateProfileProperties ( final Filer filer , String fileName ) throws IOException { FileObjectWrapper fileObject = traceeProfileProperties . get ( fileName ) ; if ( fileObject == null ) { fileObject = new FileObjectWrapper ( filer . createResource ( StandardLocation . SOURCE_OUTPUT , "" , fileName , null ) ) ; traceeProfileProperties . put ( fileName , fileObject ) ; } return fileObject ; }

Central method to get cached FileObjectWrapper. Creates new FileObjectWrapper if it can't be found

Central method to get cached FileObjectWrapper . Creates new FileObjectWrapper if it can t be found


protected boolean isValidMethod(Element element) {

        // must be of type class
        if (element.getKind() != ElementKind.METHOD) {
            error(element, "Element %s annotated with annotation %s must be a method", element.getSimpleName(),
                    TraceeContextProviderMethod.class.getSimpleName());
            return false;
        }

        // must be public
        if (!element.getModifiers().contains(Modifier.PUBLIC)) {
            error(element, "Method %s annotated with annotation %s must be public", element.getSimpleName(),
                    TraceeContextProviderMethod.class.getSimpleName());
            return false;
        }

        // must not abstract
        if (element.getModifiers().contains(Modifier.ABSTRACT)) {
            error(element, "Method %s annotated with annotation %s must not be abstract", element.getSimpleName(),
                    TraceeContextProviderMethod.class.getSimpleName());
            return false;
        }

        // must not be static
        if (element.getModifiers().contains(Modifier.STATIC)) {
            error(element, "Method %s annotated with annotation %s must not be static", element.getSimpleName(),
                    TraceeContextProviderMethod.class.getSimpleName());
            return false;
        }

        return true;
    }

Checks if passed element is a method declared as public, not abstract and not static

@param element the element to check
@return true if passed element is public, not abstract and not static method

Checks if passed element is a method declared as public not abstract and not static


protected boolean isGetterMethod(ExecutableElement executableElement) {

        // must have a return value
        TypeMirror returnTypeMirror = executableElement.getReturnType();

        if (returnTypeMirror.getKind().equals(TypeKind.VOID)) {
            error(executableElement, "method %s must have a non void return type", executableElement.getSimpleName().toString());
            return false;
        }

        // check if method takes no parameters
        List parameters = executableElement.getParameters();
        if (parameters != null && parameters.size() > 0) {
            error(executableElement, "method %s must have no parameters ", executableElement.getSimpleName().toString());
            return false;
        }

        return true;
    }

Checks if passed element has a non void return type and takes no parameters

@param executableElement
@return true if passed element has a non void return type and takes no parameters


public Boolean getPropertyValue(final String propertyKey) {

		if (propertyKey == null) {
			return null;
		}

		// check system property override
		if (toTraceeContextStringRepresentationBuilder != null && toTraceeContextStringRepresentationBuilder.getManualContextOverrides() != null) {
			Boolean manualOverrideCheck = toTraceeContextStringRepresentationBuilder.getManualContextOverrides().get(propertyKey);
			if (manualOverrideCheck != null) {
				return manualOverrideCheck;
			}
		}

		// check profile properties
		if (profileProperties != null) {
			String value = profileProperties.getProperty(propertyKey);
			if (value != null) {
				return Boolean.valueOf(value);
			}

		}

		return null;
	}

Checks whether the property for the passed key is enabled or not.

@param propertyKey the property key to check
@return true, if the property is enabled in profile or manual overrides and not disabled in manual overrides, otherwise false

Checks whether the property for the passed key is enabled or not .


protected boolean checkIfClassHasNoargsConstructor(TypeElement typeElement) {

        // check if annotated class has noargs constructor
        boolean foundConstructor = false;
        boolean foundNoargsConstructor = false;

        for (Element child : typeElement.getEnclosedElements()) {
            if (ElementKind.CONSTRUCTOR.equals(child.getKind())) {
                foundConstructor = true;
                ExecutableElement constructor = (ExecutableElement) child;
                if (constructor.getParameters().size() == 0) {
                    foundNoargsConstructor = true;
                    break;
                }
            }
        }
        return !(foundConstructor && !foundNoargsConstructor);

    }

Checks if class has noargs constructor or default noargs constructor.

@param typeElement the type element to check.
@return true if element has noarg constructor or no constructor at all

Checks if class has noargs constructor or default noargs constructor .


public static <T extends Annotation> T getAnnotationFromType(final Object instance, Class<T> annotation) {
        if (instance == null || annotation == null) {
            return null;
        }
        return instance.getClass().getAnnotation(annotation);
    }

public static < T extends Annotation > T getAnnotationFromType ( final Object instance , Class < T > annotation ) { if ( instance == null || annotation == null ) { return null ; } return instance . getClass ( ) . getAnnotation ( annotation ) ; }

Gets an annotation of passed instance.

@param instance he instance to get the annotation from
@param <T>      the annotations class to get
@return the annotation if present, otherwise null


public static boolean checkMethodHasNonVoidReturnType(final Method method) {

        if (method == null) {
            return false;
        }
        try {

            return !(Void.TYPE == method.getReturnType());

        } catch (Exception e) {
            return false;
        }

    }

public static boolean checkMethodHasNonVoidReturnType ( final Method method ) { if ( method == null ) { return false ; } try { return ! ( Void . TYPE == method . getReturnType ( ) ) ; } catch ( Exception e ) { return false ; } }

Checks whether the passsed method has a non void return value.

@param method the method to check
@return true if the method has a non void return type, otherwise false

Checks whether the passsed method has a non void return value .


public boolean apply(final StringBuilder stringBuilder, final OutputStyle outputStyle, final OutputElement outputElement) {

        boolean result = false;

        if (outputElement != null) {

            if (OutputElementType.COLLECTION.equals(outputElement.getOutputElementType())) {
                result = handleCollectionType(stringBuilder, outputStyle, outputElement);
            } else if (OutputElementType.COMPLEX.equals(outputElement.getOutputElementType())) {

                if (TraceeContextLogAnnotationUtilities.getAnnotationFromType(outputElement.getEncapsulatedInstance()) != null) {
                    result = handleTraceeContextprovider(stringBuilder, outputStyle, outputElement);
                } else {
                    result = handleComplexType(stringBuilder, outputStyle, outputElement);
                }

            }

        }

        return result;
    }

public boolean apply ( final StringBuilder stringBuilder , final OutputStyle outputStyle , final OutputElement outputElement ) { boolean result = false ; if ( outputElement != null ) { if ( OutputElementType . COLLECTION . equals ( outputElement . getOutputElementType ( ) ) ) { result = handleCollectionType ( stringBuilder , outputStyle , outputElement ) ; } else if ( OutputElementType . COMPLEX . equals ( outputElement . getOutputElementType ( ) ) ) { if ( TraceeContextLogAnnotationUtilities . getAnnotationFromType ( outputElement . getEncapsulatedInstance ( ) ) != null ) { result = handleTraceeContextprovider ( stringBuilder , outputStyle , outputElement ) ; } else { result = handleComplexType ( stringBuilder , outputStyle , outputElement ) ; } } } return result ; }

Write the type string to the Stringbuilder

@param stringBuilder the stringbuilder to write to
@param outputStyle   the output style to use
@param outputElement the output element to write the type string for.
@return true, if any output was written to the stringbuilder, otherwise false.