repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1
value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
aoindustries/aocode-public | src/main/java/com/aoindustries/io/FifoFileInputStream.java | FifoFileInputStream.read | @Override
public int read() throws IOException {
// Read from the queue
synchronized(file) {
while(true) {
long len=file.getLength();
if(len>=1) {
long pos=file.getFirstIndex();
file.file.seek(pos+16);
int b=file.file.read();
if(b==-1) throw new EOFException("Unexpected EOF");
addStats(1);
long newFirstIndex=pos+1;
while(newFirstIndex>=file.maxFifoLength) newFirstIndex-=file.maxFifoLength;
file.setFirstIndex(newFirstIndex);
file.setLength(len-1);
file.notify();
return b;
}
try {
file.wait();
} catch(InterruptedException err) {
InterruptedIOException ioErr=new InterruptedIOException();
ioErr.initCause(err);
throw ioErr;
}
}
}
} | java | @Override
public int read() throws IOException {
// Read from the queue
synchronized(file) {
while(true) {
long len=file.getLength();
if(len>=1) {
long pos=file.getFirstIndex();
file.file.seek(pos+16);
int b=file.file.read();
if(b==-1) throw new EOFException("Unexpected EOF");
addStats(1);
long newFirstIndex=pos+1;
while(newFirstIndex>=file.maxFifoLength) newFirstIndex-=file.maxFifoLength;
file.setFirstIndex(newFirstIndex);
file.setLength(len-1);
file.notify();
return b;
}
try {
file.wait();
} catch(InterruptedException err) {
InterruptedIOException ioErr=new InterruptedIOException();
ioErr.initCause(err);
throw ioErr;
}
}
}
} | [
"@",
"Override",
"public",
"int",
"read",
"(",
")",
"throws",
"IOException",
"{",
"// Read from the queue",
"synchronized",
"(",
"file",
")",
"{",
"while",
"(",
"true",
")",
"{",
"long",
"len",
"=",
"file",
".",
"getLength",
"(",
")",
";",
"if",
"(",
"... | Reads data from the file, blocks until the data is available. | [
"Reads",
"data",
"from",
"the",
"file",
"blocks",
"until",
"the",
"data",
"is",
"available",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/FifoFileInputStream.java#L78-L106 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/FifoFileInputStream.java | FifoFileInputStream.read | @Override
public int read(byte[] b, int off, int len) throws IOException {
// Read from the queue
synchronized(file) {
while(true) {
long fileLen=file.getLength();
if(fileLen>=1) {
long pos=file.getFirstIndex();
file.file.seek(pos+16);
int readSize=fileLen>len?len:(int)fileLen;
// When at the end of the file, read the remaining bytes
if((pos+readSize)>file.maxFifoLength) readSize=(int)(file.maxFifoLength-pos);
// Read as many bytes as currently available
int totalRead=file.file.read(b, off, readSize);
if(totalRead==-1) throw new EOFException("Unexpected EOF");
addStats(totalRead);
long newFirstIndex=pos+totalRead;
while(newFirstIndex>=file.maxFifoLength) newFirstIndex-=file.maxFifoLength;
file.setFirstIndex(newFirstIndex);
file.setLength(fileLen-totalRead);
file.notify();
return totalRead;
}
try {
file.wait();
} catch(InterruptedException err) {
InterruptedIOException ioErr=new InterruptedIOException();
ioErr.initCause(err);
throw ioErr;
}
}
}
} | java | @Override
public int read(byte[] b, int off, int len) throws IOException {
// Read from the queue
synchronized(file) {
while(true) {
long fileLen=file.getLength();
if(fileLen>=1) {
long pos=file.getFirstIndex();
file.file.seek(pos+16);
int readSize=fileLen>len?len:(int)fileLen;
// When at the end of the file, read the remaining bytes
if((pos+readSize)>file.maxFifoLength) readSize=(int)(file.maxFifoLength-pos);
// Read as many bytes as currently available
int totalRead=file.file.read(b, off, readSize);
if(totalRead==-1) throw new EOFException("Unexpected EOF");
addStats(totalRead);
long newFirstIndex=pos+totalRead;
while(newFirstIndex>=file.maxFifoLength) newFirstIndex-=file.maxFifoLength;
file.setFirstIndex(newFirstIndex);
file.setLength(fileLen-totalRead);
file.notify();
return totalRead;
}
try {
file.wait();
} catch(InterruptedException err) {
InterruptedIOException ioErr=new InterruptedIOException();
ioErr.initCause(err);
throw ioErr;
}
}
}
} | [
"@",
"Override",
"public",
"int",
"read",
"(",
"byte",
"[",
"]",
"b",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"// Read from the queue",
"synchronized",
"(",
"file",
")",
"{",
"while",
"(",
"true",
")",
"{",
"long",
"fil... | Reads data from the file, blocks until at least one byte is available. | [
"Reads",
"data",
"from",
"the",
"file",
"blocks",
"until",
"at",
"least",
"one",
"byte",
"is",
"available",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/FifoFileInputStream.java#L119-L152 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/FifoFileInputStream.java | FifoFileInputStream.skip | @Override
public long skip(long n) throws IOException {
// Skip in the queue
synchronized(file) {
while(true) {
long fileLen=file.getLength();
if(fileLen>=1) {
long pos=file.getFirstIndex();
long skipSize=fileLen>n?n:fileLen;
// When at the end of the file, skip the remaining bytes
if((pos+skipSize)>file.maxFifoLength) skipSize=file.maxFifoLength-pos;
// Skip as many bytes as currently available
long totalSkipped=skipSize;
long newFirstIndex=pos+skipSize;
while(newFirstIndex>=file.maxFifoLength) newFirstIndex-=file.maxFifoLength;
file.setFirstIndex(newFirstIndex);
file.setLength(fileLen-skipSize);
file.notify();
return totalSkipped;
}
try {
file.wait();
} catch(InterruptedException err) {
InterruptedIOException ioErr=new InterruptedIOException();
ioErr.initCause(err);
throw ioErr;
}
}
}
} | java | @Override
public long skip(long n) throws IOException {
// Skip in the queue
synchronized(file) {
while(true) {
long fileLen=file.getLength();
if(fileLen>=1) {
long pos=file.getFirstIndex();
long skipSize=fileLen>n?n:fileLen;
// When at the end of the file, skip the remaining bytes
if((pos+skipSize)>file.maxFifoLength) skipSize=file.maxFifoLength-pos;
// Skip as many bytes as currently available
long totalSkipped=skipSize;
long newFirstIndex=pos+skipSize;
while(newFirstIndex>=file.maxFifoLength) newFirstIndex-=file.maxFifoLength;
file.setFirstIndex(newFirstIndex);
file.setLength(fileLen-skipSize);
file.notify();
return totalSkipped;
}
try {
file.wait();
} catch(InterruptedException err) {
InterruptedIOException ioErr=new InterruptedIOException();
ioErr.initCause(err);
throw ioErr;
}
}
}
} | [
"@",
"Override",
"public",
"long",
"skip",
"(",
"long",
"n",
")",
"throws",
"IOException",
"{",
"// Skip in the queue",
"synchronized",
"(",
"file",
")",
"{",
"while",
"(",
"true",
")",
"{",
"long",
"fileLen",
"=",
"file",
".",
"getLength",
"(",
")",
";"... | Skips data in the queue, blocks until at least one byte is skipped. | [
"Skips",
"data",
"in",
"the",
"queue",
"blocks",
"until",
"at",
"least",
"one",
"byte",
"is",
"skipped",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/FifoFileInputStream.java#L157-L187 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/FifoFileInputStream.java | FifoFileInputStream.available | @Override
public int available() throws IOException {
synchronized(file) {
long len=file.getLength();
return len>Integer.MAX_VALUE?Integer.MAX_VALUE:(int)len;
}
} | java | @Override
public int available() throws IOException {
synchronized(file) {
long len=file.getLength();
return len>Integer.MAX_VALUE?Integer.MAX_VALUE:(int)len;
}
} | [
"@",
"Override",
"public",
"int",
"available",
"(",
")",
"throws",
"IOException",
"{",
"synchronized",
"(",
"file",
")",
"{",
"long",
"len",
"=",
"file",
".",
"getLength",
"(",
")",
";",
"return",
"len",
">",
"Integer",
".",
"MAX_VALUE",
"?",
"Integer",
... | Determines the number of bytes that may be read without blocking. | [
"Determines",
"the",
"number",
"of",
"bytes",
"that",
"may",
"be",
"read",
"without",
"blocking",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/FifoFileInputStream.java#L192-L198 | train |
attribyte/metrics-reporting | src/main/java/org/attribyte/metrics/ReporterBase.java | ReporterBase.init | protected void init(final String name, final Properties props) {
init = new InitUtil("", props, false);
this.name = name;
} | java | protected void init(final String name, final Properties props) {
init = new InitUtil("", props, false);
this.name = name;
} | [
"protected",
"void",
"init",
"(",
"final",
"String",
"name",
",",
"final",
"Properties",
"props",
")",
"{",
"init",
"=",
"new",
"InitUtil",
"(",
"\"\"",
",",
"props",
",",
"false",
")",
";",
"this",
".",
"name",
"=",
"name",
";",
"}"
] | Initialize the properties.
@param name The instance name.
@param props The properties. | [
"Initialize",
"the",
"properties",
"."
] | f7420264cc124598dc93aedbd902267dab2d1c02 | https://github.com/attribyte/metrics-reporting/blob/f7420264cc124598dc93aedbd902267dab2d1c02/src/main/java/org/attribyte/metrics/ReporterBase.java#L55-L58 | train |
nlalevee/jsourcemap | jsourcemap/src/java/org/hibnet/jsourcemap/SourceMapConsumer.java | SourceMapConsumer.allGeneratedPositionsFor | public List<GeneratedPosition> allGeneratedPositionsFor(int line, Integer column, String source) {
// When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
// returns the index of the closest mapping less than the needle. By
// setting needle.originalColumn to 0, we thus find the last mapping for
// the given line, provided such a mapping exists.
ParsedMapping needle = new ParsedMapping(null, null, line, column == null ? 0 : column, null, null);
if (this.sourceRoot != null) {
source = Util.relative(this.sourceRoot, source);
}
if (!this._sources.has(source)) {
return Collections.emptyList();
}
needle.source = this._sources.indexOf(source);
List<GeneratedPosition> mappings = new ArrayList<>();
int index = _findMapping(needle, this._originalMappings(), "originalLine", "originalColumn",
(mapping1, mapping2) -> Util.compareByOriginalPositions(mapping1, mapping2, true), BinarySearch.Bias.LEAST_UPPER_BOUND);
if (index >= 0) {
ParsedMapping mapping = this._originalMappings().get(index);
if (column == null) {
int originalLine = mapping.originalLine;
// Iterate until either we run out of mappings, or we run into
// a mapping for a different line than the one we found. Since
// mappings are sorted, this is guaranteed to find all mappings for
// the line we found.
while (mapping != null && mapping.originalLine == originalLine) {
mappings.add(new GeneratedPosition(mapping.generatedLine, mapping.generatedColumn, mapping.lastGeneratedColumn));
index++;
if (index >= this._originalMappings().size()) {
mapping = null;
} else {
mapping = this._originalMappings().get(index);
}
}
} else {
int originalColumn = mapping.originalColumn;
// Iterate until either we run out of mappings, or we run into
// a mapping for a different line than the one we were searching for.
// Since mappings are sorted, this is guaranteed to find all mappings for
// the line we are searching for.
while (mapping != null && mapping.originalLine == line && mapping.originalColumn == originalColumn) {
mappings.add(new GeneratedPosition(mapping.generatedLine, mapping.generatedColumn, mapping.lastGeneratedColumn));
index++;
if (index >= this._originalMappings().size()) {
mapping = null;
} else {
mapping = this._originalMappings().get(index);
}
}
}
}
return mappings;
} | java | public List<GeneratedPosition> allGeneratedPositionsFor(int line, Integer column, String source) {
// When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
// returns the index of the closest mapping less than the needle. By
// setting needle.originalColumn to 0, we thus find the last mapping for
// the given line, provided such a mapping exists.
ParsedMapping needle = new ParsedMapping(null, null, line, column == null ? 0 : column, null, null);
if (this.sourceRoot != null) {
source = Util.relative(this.sourceRoot, source);
}
if (!this._sources.has(source)) {
return Collections.emptyList();
}
needle.source = this._sources.indexOf(source);
List<GeneratedPosition> mappings = new ArrayList<>();
int index = _findMapping(needle, this._originalMappings(), "originalLine", "originalColumn",
(mapping1, mapping2) -> Util.compareByOriginalPositions(mapping1, mapping2, true), BinarySearch.Bias.LEAST_UPPER_BOUND);
if (index >= 0) {
ParsedMapping mapping = this._originalMappings().get(index);
if (column == null) {
int originalLine = mapping.originalLine;
// Iterate until either we run out of mappings, or we run into
// a mapping for a different line than the one we found. Since
// mappings are sorted, this is guaranteed to find all mappings for
// the line we found.
while (mapping != null && mapping.originalLine == originalLine) {
mappings.add(new GeneratedPosition(mapping.generatedLine, mapping.generatedColumn, mapping.lastGeneratedColumn));
index++;
if (index >= this._originalMappings().size()) {
mapping = null;
} else {
mapping = this._originalMappings().get(index);
}
}
} else {
int originalColumn = mapping.originalColumn;
// Iterate until either we run out of mappings, or we run into
// a mapping for a different line than the one we were searching for.
// Since mappings are sorted, this is guaranteed to find all mappings for
// the line we are searching for.
while (mapping != null && mapping.originalLine == line && mapping.originalColumn == originalColumn) {
mappings.add(new GeneratedPosition(mapping.generatedLine, mapping.generatedColumn, mapping.lastGeneratedColumn));
index++;
if (index >= this._originalMappings().size()) {
mapping = null;
} else {
mapping = this._originalMappings().get(index);
}
}
}
}
return mappings;
} | [
"public",
"List",
"<",
"GeneratedPosition",
">",
"allGeneratedPositionsFor",
"(",
"int",
"line",
",",
"Integer",
"column",
",",
"String",
"source",
")",
"{",
"// When there is no exact match, BasicSourceMapConsumer.prototype._findMapping",
"// returns the index of the closest map... | Returns all generated line and column information for the original source, line, and column provided. If no column is provided, returns all
mappings corresponding to a either the line we are searching for or the next closest line that has any mappings. Otherwise, returns all
mappings corresponding to the given line and either the column we are searching for or the next closest column that has any offsets.
The only argument is an object with the following properties:
<ul>
<li>source: The filename of the original source.</li>
<li>line: The line number in the original source.</li>
<li>column: Optional. the column number in the original source.</li>
</ul>
and an array of objects is returned, each with the following properties:
<ul>
<li>line: The line number in the generated source, or null.</li>
<li>column: The column number in the generated source, or null.</li>
</ul> | [
"Returns",
"all",
"generated",
"line",
"and",
"column",
"information",
"for",
"the",
"original",
"source",
"line",
"and",
"column",
"provided",
".",
"If",
"no",
"column",
"is",
"provided",
"returns",
"all",
"mappings",
"corresponding",
"to",
"a",
"either",
"th... | 361a99c73d51c11afa5579dd83d477c4d0345599 | https://github.com/nlalevee/jsourcemap/blob/361a99c73d51c11afa5579dd83d477c4d0345599/jsourcemap/src/java/org/hibnet/jsourcemap/SourceMapConsumer.java#L236-L294 | train |
nlalevee/jsourcemap | jsourcemap/src/java/org/hibnet/jsourcemap/SourceMapConsumer.java | SourceMapConsumer._findMapping | <T> int _findMapping(T aNeedle, List<T> aMappings, Object aLineName, Object aColumnName, BinarySearch.Comparator<T> aComparator,
BinarySearch.Bias aBias) {
// To return the position we are searching for, we must first find the
// mapping for the given position and then return the opposite position it
// points to. Because the mappings are sorted, we can use binary search to
// find the best mapping.
// if (aNeedle[aLineName] <= 0) {
// throw new TypeError("Line must be greater than or equal to 1, got " + aNeedle[aLineName]);
// }
// if (aNeedle[aColumnName] < 0) {
// throw new TypeError("Column must be greater than or equal to 0, got " + aNeedle[aColumnName]);
// }
return BinarySearch.search(aNeedle, aMappings, aComparator, aBias);
} | java | <T> int _findMapping(T aNeedle, List<T> aMappings, Object aLineName, Object aColumnName, BinarySearch.Comparator<T> aComparator,
BinarySearch.Bias aBias) {
// To return the position we are searching for, we must first find the
// mapping for the given position and then return the opposite position it
// points to. Because the mappings are sorted, we can use binary search to
// find the best mapping.
// if (aNeedle[aLineName] <= 0) {
// throw new TypeError("Line must be greater than or equal to 1, got " + aNeedle[aLineName]);
// }
// if (aNeedle[aColumnName] < 0) {
// throw new TypeError("Column must be greater than or equal to 0, got " + aNeedle[aColumnName]);
// }
return BinarySearch.search(aNeedle, aMappings, aComparator, aBias);
} | [
"<",
"T",
">",
"int",
"_findMapping",
"(",
"T",
"aNeedle",
",",
"List",
"<",
"T",
">",
"aMappings",
",",
"Object",
"aLineName",
",",
"Object",
"aColumnName",
",",
"BinarySearch",
".",
"Comparator",
"<",
"T",
">",
"aComparator",
",",
"BinarySearch",
".",
... | Find the mapping that best matches the hypothetical "needle" mapping that we are searching for in the given "haystack" of mappings. | [
"Find",
"the",
"mapping",
"that",
"best",
"matches",
"the",
"hypothetical",
"needle",
"mapping",
"that",
"we",
"are",
"searching",
"for",
"in",
"the",
"given",
"haystack",
"of",
"mappings",
"."
] | 361a99c73d51c11afa5579dd83d477c4d0345599 | https://github.com/nlalevee/jsourcemap/blob/361a99c73d51c11afa5579dd83d477c4d0345599/jsourcemap/src/java/org/hibnet/jsourcemap/SourceMapConsumer.java#L299-L314 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/HTMLInputStreamPage.java | HTMLInputStreamPage.getHTMLInputStream | public static InputStream getHTMLInputStream(Class<?> clazz) throws IOException {
return HTMLInputStreamPage.class.getResourceAsStream('/'+clazz.getName().replace('.', '/')+".html");
} | java | public static InputStream getHTMLInputStream(Class<?> clazz) throws IOException {
return HTMLInputStreamPage.class.getResourceAsStream('/'+clazz.getName().replace('.', '/')+".html");
} | [
"public",
"static",
"InputStream",
"getHTMLInputStream",
"(",
"Class",
"<",
"?",
">",
"clazz",
")",
"throws",
"IOException",
"{",
"return",
"HTMLInputStreamPage",
".",
"class",
".",
"getResourceAsStream",
"(",
"'",
"'",
"+",
"clazz",
".",
"getName",
"(",
")",
... | Gets the HTML file with the same name as the provided Class. | [
"Gets",
"the",
"HTML",
"file",
"with",
"the",
"same",
"name",
"as",
"the",
"provided",
"Class",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/HTMLInputStreamPage.java#L74-L76 | train |
probedock/probedock-java | src/main/java/io/probedock/client/core/storage/FileStore.java | FileStore.save | public void save(ProbeTestRun probeTestRun) throws IOException {
OutputStreamWriter osw = new OutputStreamWriter(
new FileOutputStream(new File(getTmpDir(probeTestRun), UUID.randomUUID().toString())),
Charset.forName(Constants.ENCODING).newEncoder()
);
serializer.serializePayload(osw, probeTestRun, true);
} | java | public void save(ProbeTestRun probeTestRun) throws IOException {
OutputStreamWriter osw = new OutputStreamWriter(
new FileOutputStream(new File(getTmpDir(probeTestRun), UUID.randomUUID().toString())),
Charset.forName(Constants.ENCODING).newEncoder()
);
serializer.serializePayload(osw, probeTestRun, true);
} | [
"public",
"void",
"save",
"(",
"ProbeTestRun",
"probeTestRun",
")",
"throws",
"IOException",
"{",
"OutputStreamWriter",
"osw",
"=",
"new",
"OutputStreamWriter",
"(",
"new",
"FileOutputStream",
"(",
"new",
"File",
"(",
"getTmpDir",
"(",
"probeTestRun",
")",
",",
... | Save a payload
@param probeTestRun The payload to save
@throws IOException I/O Errors | [
"Save",
"a",
"payload"
] | 92ee6634ba4fe3fdffeb4e202f5372ef947a67c3 | https://github.com/probedock/probedock-java/blob/92ee6634ba4fe3fdffeb4e202f5372ef947a67c3/src/main/java/io/probedock/client/core/storage/FileStore.java#L61-L68 | train |
aoindustries/ao-messaging-base | src/main/java/com/aoindustries/messaging/base/AbstractSocketContext.java | AbstractSocketContext.onClose | void onClose(AbstractSocket socket) {
synchronized(sockets) {
if(sockets.remove(socket.getId()) == null) throw new AssertionError("Socket not part of this context. onClose called twice?");
}
} | java | void onClose(AbstractSocket socket) {
synchronized(sockets) {
if(sockets.remove(socket.getId()) == null) throw new AssertionError("Socket not part of this context. onClose called twice?");
}
} | [
"void",
"onClose",
"(",
"AbstractSocket",
"socket",
")",
"{",
"synchronized",
"(",
"sockets",
")",
"{",
"if",
"(",
"sockets",
".",
"remove",
"(",
"socket",
".",
"getId",
"(",
")",
")",
"==",
"null",
")",
"throw",
"new",
"AssertionError",
"(",
"\"Socket n... | Called by a socket when it is closed.
This will only be called once. | [
"Called",
"by",
"a",
"socket",
"when",
"it",
"is",
"closed",
".",
"This",
"will",
"only",
"be",
"called",
"once",
"."
] | 77921e05e06cf7999f313755d0bff1cc8b6b0228 | https://github.com/aoindustries/ao-messaging-base/blob/77921e05e06cf7999f313755d0bff1cc8b6b0228/src/main/java/com/aoindustries/messaging/base/AbstractSocketContext.java#L133-L137 | train |
aoindustries/ao-messaging-base | src/main/java/com/aoindustries/messaging/base/AbstractSocketContext.java | AbstractSocketContext.addSocket | protected void addSocket(final S newSocket) {
if(isClosed()) throw new IllegalStateException("SocketContext is closed");
Future<?> future;
synchronized(sockets) {
Identifier id = newSocket.getId();
if(sockets.containsKey(id)) throw new IllegalStateException("Socket with the same ID has already been added");
sockets.put(id, newSocket);
future = listenerManager.enqueueEvent(
new ConcurrentListenerManager.Event<SocketContextListener>() {
@Override
public Runnable createCall(final SocketContextListener listener) {
return new Runnable() {
@Override
public void run() {
listener.onNewSocket(AbstractSocketContext.this, newSocket);
}
};
}
}
);
}
try {
future.get();
} catch(ExecutionException e) {
logger.log(Level.SEVERE, null, e);
} catch(InterruptedException e) {
logger.log(Level.SEVERE, null, e);
// Restore the interrupted status
Thread.currentThread().interrupt();
}
} | java | protected void addSocket(final S newSocket) {
if(isClosed()) throw new IllegalStateException("SocketContext is closed");
Future<?> future;
synchronized(sockets) {
Identifier id = newSocket.getId();
if(sockets.containsKey(id)) throw new IllegalStateException("Socket with the same ID has already been added");
sockets.put(id, newSocket);
future = listenerManager.enqueueEvent(
new ConcurrentListenerManager.Event<SocketContextListener>() {
@Override
public Runnable createCall(final SocketContextListener listener) {
return new Runnable() {
@Override
public void run() {
listener.onNewSocket(AbstractSocketContext.this, newSocket);
}
};
}
}
);
}
try {
future.get();
} catch(ExecutionException e) {
logger.log(Level.SEVERE, null, e);
} catch(InterruptedException e) {
logger.log(Level.SEVERE, null, e);
// Restore the interrupted status
Thread.currentThread().interrupt();
}
} | [
"protected",
"void",
"addSocket",
"(",
"final",
"S",
"newSocket",
")",
"{",
"if",
"(",
"isClosed",
"(",
")",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"SocketContext is closed\"",
")",
";",
"Future",
"<",
"?",
">",
"future",
";",
"synchronized",
"... | Adds a new socket to this context, sockets must be added to the context
before they create any of their own events. This gives context listeners
a chance to register per-socket listeners in "onNewSocket".
First, adds to the list of sockets.
Second, calls all listeners notifying them of new socket.
Third, waits for all listeners to handle the event before returning. | [
"Adds",
"a",
"new",
"socket",
"to",
"this",
"context",
"sockets",
"must",
"be",
"added",
"to",
"the",
"context",
"before",
"they",
"create",
"any",
"of",
"their",
"own",
"events",
".",
"This",
"gives",
"context",
"listeners",
"a",
"chance",
"to",
"register... | 77921e05e06cf7999f313755d0bff1cc8b6b0228 | https://github.com/aoindustries/ao-messaging-base/blob/77921e05e06cf7999f313755d0bff1cc8b6b0228/src/main/java/com/aoindustries/messaging/base/AbstractSocketContext.java#L222-L252 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/CompressedDataOutputStream.java | CompressedDataOutputStream.writeCompressedUTF | public void writeCompressedUTF(String str, int slot) throws IOException {
if(slot<0 || slot>0x3f) throw new IOException("Slot out of range (0-63): "+slot);
if(lastStrings==null) lastStrings=new String[64];
String last=lastStrings[slot];
if(last==null) last="";
int strLen=str.length();
int lastLen=last.length();
int maxCommon=Math.min(strLen, lastLen);
int common=0;
for(;common<maxCommon;common++) {
if(str.charAt(common)!=last.charAt(common)) break;
}
if(lastCommonLengths==null) lastCommonLengths=new int[64];
int commonDifference=common-lastCommonLengths[slot];
// Write the header byte
out.write(
(commonDifference==0?0:0x80)
| (common==strLen?0:0x40)
| slot
);
// Write the common difference
if(commonDifference>0) writeCompressedInt(commonDifference-1);
else if(commonDifference<0) writeCompressedInt(commonDifference);
// Write the suffix
if(common!=strLen) writeUTF(str.substring(common));
// Get ready for the next call
lastStrings[slot]=str;
lastCommonLengths[slot]=common;
} | java | public void writeCompressedUTF(String str, int slot) throws IOException {
if(slot<0 || slot>0x3f) throw new IOException("Slot out of range (0-63): "+slot);
if(lastStrings==null) lastStrings=new String[64];
String last=lastStrings[slot];
if(last==null) last="";
int strLen=str.length();
int lastLen=last.length();
int maxCommon=Math.min(strLen, lastLen);
int common=0;
for(;common<maxCommon;common++) {
if(str.charAt(common)!=last.charAt(common)) break;
}
if(lastCommonLengths==null) lastCommonLengths=new int[64];
int commonDifference=common-lastCommonLengths[slot];
// Write the header byte
out.write(
(commonDifference==0?0:0x80)
| (common==strLen?0:0x40)
| slot
);
// Write the common difference
if(commonDifference>0) writeCompressedInt(commonDifference-1);
else if(commonDifference<0) writeCompressedInt(commonDifference);
// Write the suffix
if(common!=strLen) writeUTF(str.substring(common));
// Get ready for the next call
lastStrings[slot]=str;
lastCommonLengths[slot]=common;
} | [
"public",
"void",
"writeCompressedUTF",
"(",
"String",
"str",
",",
"int",
"slot",
")",
"throws",
"IOException",
"{",
"if",
"(",
"slot",
"<",
"0",
"||",
"slot",
">",
"0x3f",
")",
"throw",
"new",
"IOException",
"(",
"\"Slot out of range (0-63): \"",
"+",
"slot... | Writes a String to the stream while using prefix compression.
<pre>
The first byte has these bits:
X X X X X X X X
| | +-+-+-+-+-+ Slot number (0-63)
| +------------ 1 = Suffix UTF follows, 0 = No suffix UTF exists
+-------------- 1 = Common length difference follows, 0 = Common length not changed
Second, if common length difference is not zero, the common length change follows
one less for positive differences because 0 is handled in first byte
Third, if suffix UTF follows, writeUTF of all the string after common length
</pre> | [
"Writes",
"a",
"String",
"to",
"the",
"stream",
"while",
"using",
"prefix",
"compression",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/CompressedDataOutputStream.java#L123-L155 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/CompressedDataOutputStream.java | CompressedDataOutputStream.writeLongUTF | public void writeLongUTF(String str) throws IOException {
int length = str.length();
writeCompressedInt(length);
for(int position = 0; position<length; position+=20480) {
int blockLength = length - position;
if(blockLength>20480) blockLength = 20480;
String block = str.substring(position, position+blockLength);
writeUTF(block);
}
} | java | public void writeLongUTF(String str) throws IOException {
int length = str.length();
writeCompressedInt(length);
for(int position = 0; position<length; position+=20480) {
int blockLength = length - position;
if(blockLength>20480) blockLength = 20480;
String block = str.substring(position, position+blockLength);
writeUTF(block);
}
} | [
"public",
"void",
"writeLongUTF",
"(",
"String",
"str",
")",
"throws",
"IOException",
"{",
"int",
"length",
"=",
"str",
".",
"length",
"(",
")",
";",
"writeCompressedInt",
"(",
"length",
")",
";",
"for",
"(",
"int",
"position",
"=",
"0",
";",
"position",... | Writes a string of any length. | [
"Writes",
"a",
"string",
"of",
"any",
"length",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/CompressedDataOutputStream.java#L165-L174 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/AutoListPage.java | AutoListPage.printPageList | public static void printPageList(ChainWriter out, WebSiteRequest req, HttpServletResponse resp, WebPage[] pages, WebPageLayout layout) throws IOException, SQLException {
int len = pages.length;
for (int c = 0; c < len; c++) {
WebPage page = pages[c];
out.print(" <tr>\n"
+ " <td style='white-space:nowrap'><a class='aoLightLink' href='").encodeXmlAttribute(req==null?"":resp.encodeURL(req.getContextPath()+req.getURL(page))).print("'>").encodeXhtml(page.getShortTitle()).print("</a>\n"
+ " </td>\n"
+ " <td style='width:12px; white-space:nowrap'> </td>\n"
+ " <td style='white-space:nowrap'>").encodeXhtml(page.getDescription()).print("</td>\n"
+ " </tr>\n");
}
} | java | public static void printPageList(ChainWriter out, WebSiteRequest req, HttpServletResponse resp, WebPage[] pages, WebPageLayout layout) throws IOException, SQLException {
int len = pages.length;
for (int c = 0; c < len; c++) {
WebPage page = pages[c];
out.print(" <tr>\n"
+ " <td style='white-space:nowrap'><a class='aoLightLink' href='").encodeXmlAttribute(req==null?"":resp.encodeURL(req.getContextPath()+req.getURL(page))).print("'>").encodeXhtml(page.getShortTitle()).print("</a>\n"
+ " </td>\n"
+ " <td style='width:12px; white-space:nowrap'> </td>\n"
+ " <td style='white-space:nowrap'>").encodeXhtml(page.getDescription()).print("</td>\n"
+ " </tr>\n");
}
} | [
"public",
"static",
"void",
"printPageList",
"(",
"ChainWriter",
"out",
",",
"WebSiteRequest",
"req",
",",
"HttpServletResponse",
"resp",
",",
"WebPage",
"[",
"]",
"pages",
",",
"WebPageLayout",
"layout",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"... | Prints a list of pages. | [
"Prints",
"a",
"list",
"of",
"pages",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/AutoListPage.java#L86-L97 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/AutoListPage.java | AutoListPage.printPageList | public static void printPageList(ChainWriter out, WebSiteRequest req, HttpServletResponse resp, WebPage parent, WebPageLayout layout) throws IOException, SQLException {
printPageList(out, req, resp, parent.getCachedPages(req), layout);
} | java | public static void printPageList(ChainWriter out, WebSiteRequest req, HttpServletResponse resp, WebPage parent, WebPageLayout layout) throws IOException, SQLException {
printPageList(out, req, resp, parent.getCachedPages(req), layout);
} | [
"public",
"static",
"void",
"printPageList",
"(",
"ChainWriter",
"out",
",",
"WebSiteRequest",
"req",
",",
"HttpServletResponse",
"resp",
",",
"WebPage",
"parent",
",",
"WebPageLayout",
"layout",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"printPageList... | Prints an unordered list of the available pages. | [
"Prints",
"an",
"unordered",
"list",
"of",
"the",
"available",
"pages",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/AutoListPage.java#L102-L104 | train |
nlalevee/jsourcemap | jsourcemap/src/java/org/hibnet/jsourcemap/MappingList.java | MappingList.generatedPositionAfter | private boolean generatedPositionAfter(Mapping mappingA, Mapping mappingB) {
// Optimized for most common case
int lineA = mappingA.generated.line;
int lineB = mappingB.generated.line;
int columnA = mappingA.generated.column;
int columnB = mappingB.generated.column;
return lineB > lineA || lineB == lineA && columnB >= columnA || Util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
} | java | private boolean generatedPositionAfter(Mapping mappingA, Mapping mappingB) {
// Optimized for most common case
int lineA = mappingA.generated.line;
int lineB = mappingB.generated.line;
int columnA = mappingA.generated.column;
int columnB = mappingB.generated.column;
return lineB > lineA || lineB == lineA && columnB >= columnA || Util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
} | [
"private",
"boolean",
"generatedPositionAfter",
"(",
"Mapping",
"mappingA",
",",
"Mapping",
"mappingB",
")",
"{",
"// Optimized for most common case",
"int",
"lineA",
"=",
"mappingA",
".",
"generated",
".",
"line",
";",
"int",
"lineB",
"=",
"mappingB",
".",
"gener... | Determine whether mappingB is after mappingA with respect to generated position. | [
"Determine",
"whether",
"mappingB",
"is",
"after",
"mappingA",
"with",
"respect",
"to",
"generated",
"position",
"."
] | 361a99c73d51c11afa5579dd83d477c4d0345599 | https://github.com/nlalevee/jsourcemap/blob/361a99c73d51c11afa5579dd83d477c4d0345599/jsourcemap/src/java/org/hibnet/jsourcemap/MappingList.java#L32-L39 | train |
nlalevee/jsourcemap | jsourcemap/src/java/org/hibnet/jsourcemap/MappingList.java | MappingList.add | void add(Mapping aMapping) {
if (generatedPositionAfter(this._last, aMapping)) {
this._last = aMapping;
this._array.add(aMapping);
} else {
this._sorted = false;
this._array.add(aMapping);
}
} | java | void add(Mapping aMapping) {
if (generatedPositionAfter(this._last, aMapping)) {
this._last = aMapping;
this._array.add(aMapping);
} else {
this._sorted = false;
this._array.add(aMapping);
}
} | [
"void",
"add",
"(",
"Mapping",
"aMapping",
")",
"{",
"if",
"(",
"generatedPositionAfter",
"(",
"this",
".",
"_last",
",",
"aMapping",
")",
")",
"{",
"this",
".",
"_last",
"=",
"aMapping",
";",
"this",
".",
"_array",
".",
"add",
"(",
"aMapping",
")",
... | Add the given source mapping.
@param Object
aMapping | [
"Add",
"the",
"given",
"source",
"mapping",
"."
] | 361a99c73d51c11afa5579dd83d477c4d0345599 | https://github.com/nlalevee/jsourcemap/blob/361a99c73d51c11afa5579dd83d477c4d0345599/jsourcemap/src/java/org/hibnet/jsourcemap/MappingList.java#L69-L77 | train |
nlalevee/jsourcemap | jsourcemap/src/java/org/hibnet/jsourcemap/MappingList.java | MappingList.toArray | List<Mapping> toArray() {
if (!this._sorted) {
Collections.sort(this._array, Util::compareByGeneratedPositionsInflated);
this._sorted = true;
}
return this._array;
} | java | List<Mapping> toArray() {
if (!this._sorted) {
Collections.sort(this._array, Util::compareByGeneratedPositionsInflated);
this._sorted = true;
}
return this._array;
} | [
"List",
"<",
"Mapping",
">",
"toArray",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"_sorted",
")",
"{",
"Collections",
".",
"sort",
"(",
"this",
".",
"_array",
",",
"Util",
"::",
"compareByGeneratedPositionsInflated",
")",
";",
"this",
".",
"_sorted",
... | Returns the flat, sorted array of mappings. The mappings are sorted by generated position.
WARNING: This method returns internal data without copying, for performance. The return value must NOT be mutated, and should be treated as an
immutable borrow. If you want to take ownership, you must make your own copy.
@return | [
"Returns",
"the",
"flat",
"sorted",
"array",
"of",
"mappings",
".",
"The",
"mappings",
"are",
"sorted",
"by",
"generated",
"position",
"."
] | 361a99c73d51c11afa5579dd83d477c4d0345599 | https://github.com/nlalevee/jsourcemap/blob/361a99c73d51c11afa5579dd83d477c4d0345599/jsourcemap/src/java/org/hibnet/jsourcemap/MappingList.java#L87-L93 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/sql/AOConnectionPool.java | AOConnectionPool.loadDriver | private static void loadDriver(String classname) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
if(!driversLoaded.containsKey(classname)) {
Object O = Class.forName(classname).newInstance();
driversLoaded.putIfAbsent(classname, O);
}
} | java | private static void loadDriver(String classname) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
if(!driversLoaded.containsKey(classname)) {
Object O = Class.forName(classname).newInstance();
driversLoaded.putIfAbsent(classname, O);
}
} | [
"private",
"static",
"void",
"loadDriver",
"(",
"String",
"classname",
")",
"throws",
"ClassNotFoundException",
",",
"InstantiationException",
",",
"IllegalAccessException",
"{",
"if",
"(",
"!",
"driversLoaded",
".",
"containsKey",
"(",
"classname",
")",
")",
"{",
... | Loads a driver at most once. | [
"Loads",
"a",
"driver",
"at",
"most",
"once",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/sql/AOConnectionPool.java#L129-L134 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/util/persistent/FixedPersistentBlockBuffer.java | FixedPersistentBlockBuffer.ensureCapacity | @Override
// @NotThreadSafe
protected void ensureCapacity(long capacity) throws IOException {
long curCapacity = pbuffer.capacity();
if(curCapacity<capacity) expandCapacity(curCapacity, capacity);
} | java | @Override
// @NotThreadSafe
protected void ensureCapacity(long capacity) throws IOException {
long curCapacity = pbuffer.capacity();
if(curCapacity<capacity) expandCapacity(curCapacity, capacity);
} | [
"@",
"Override",
"// @NotThreadSafe",
"protected",
"void",
"ensureCapacity",
"(",
"long",
"capacity",
")",
"throws",
"IOException",
"{",
"long",
"curCapacity",
"=",
"pbuffer",
".",
"capacity",
"(",
")",
";",
"if",
"(",
"curCapacity",
"<",
"capacity",
")",
"exp... | This class takes a lazy approach on allocating buffer space. It will allocate
additional space as needed here, rounding up to the next 4096-byte boundary. | [
"This",
"class",
"takes",
"a",
"lazy",
"approach",
"on",
"allocating",
"buffer",
"space",
".",
"It",
"will",
"allocate",
"additional",
"space",
"as",
"needed",
"here",
"rounding",
"up",
"to",
"the",
"next",
"4096",
"-",
"byte",
"boundary",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/persistent/FixedPersistentBlockBuffer.java#L318-L323 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/ParallelDelete.java | ParallelDelete.getRelativePath | private static String getRelativePath(File file, FilesystemIterator iterator) throws IOException {
String path = file.getPath();
String prefix = iterator.getStartPath();
if(!path.startsWith(prefix)) throw new IOException("path doesn't start with prefix: path=\""+path+"\", prefix=\""+prefix+"\"");
return path.substring(prefix.length());
} | java | private static String getRelativePath(File file, FilesystemIterator iterator) throws IOException {
String path = file.getPath();
String prefix = iterator.getStartPath();
if(!path.startsWith(prefix)) throw new IOException("path doesn't start with prefix: path=\""+path+"\", prefix=\""+prefix+"\"");
return path.substring(prefix.length());
} | [
"private",
"static",
"String",
"getRelativePath",
"(",
"File",
"file",
",",
"FilesystemIterator",
"iterator",
")",
"throws",
"IOException",
"{",
"String",
"path",
"=",
"file",
".",
"getPath",
"(",
")",
";",
"String",
"prefix",
"=",
"iterator",
".",
"getStartPa... | Gets the relative path for the provided file from the provided iterator. | [
"Gets",
"the",
"relative",
"path",
"for",
"the",
"provided",
"file",
"from",
"the",
"provided",
"iterator",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/ParallelDelete.java#L328-L333 | train |
attribyte/metrics-reporting | src/main/java/org/attribyte/metrics/newrelic/ScheduledNewRelicReporter.java | ScheduledNewRelicReporter.toLabel | private String toLabel(final TimeUnit unit) {
switch(unit) {
case DAYS: return "day";
case HOURS: return "hour";
case MINUTES: return "minute";
case SECONDS: return "second";
case MILLISECONDS: return "ms";
case MICROSECONDS: return "us";
case NANOSECONDS: return "ns";
default: return "";
}
} | java | private String toLabel(final TimeUnit unit) {
switch(unit) {
case DAYS: return "day";
case HOURS: return "hour";
case MINUTES: return "minute";
case SECONDS: return "second";
case MILLISECONDS: return "ms";
case MICROSECONDS: return "us";
case NANOSECONDS: return "ns";
default: return "";
}
} | [
"private",
"String",
"toLabel",
"(",
"final",
"TimeUnit",
"unit",
")",
"{",
"switch",
"(",
"unit",
")",
"{",
"case",
"DAYS",
":",
"return",
"\"day\"",
";",
"case",
"HOURS",
":",
"return",
"\"hour\"",
";",
"case",
"MINUTES",
":",
"return",
"\"minute\"",
"... | Converts a time unit to a label.
@param unit The time unit.
@return The label. | [
"Converts",
"a",
"time",
"unit",
"to",
"a",
"label",
"."
] | f7420264cc124598dc93aedbd902267dab2d1c02 | https://github.com/attribyte/metrics-reporting/blob/f7420264cc124598dc93aedbd902267dab2d1c02/src/main/java/org/attribyte/metrics/newrelic/ScheduledNewRelicReporter.java#L153-L164 | train |
aoindustries/ao-messaging-http-client | src/main/java/com/aoindustries/messaging/http/client/HttpSocketClient.java | HttpSocketClient.connect | public void connect(
final String endpoint,
final Callback<? super HttpSocket> onConnect,
final Callback<? super Exception> onError
) {
executors.getUnbounded().submit(
new Runnable() {
@Override
public void run() {
try {
// Build request bytes
AoByteArrayOutputStream bout = new AoByteArrayOutputStream();
try {
try (DataOutputStream out = new DataOutputStream(bout)) {
out.writeBytes("action=connect");
}
} finally {
bout.close();
}
long connectTime = System.currentTimeMillis();
URL endpointURL = new URL(endpoint);
HttpURLConnection conn = (HttpURLConnection)endpointURL.openConnection();
conn.setAllowUserInteraction(false);
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(bout.size());
conn.setInstanceFollowRedirects(false);
conn.setReadTimeout(CONNECT_TIMEOUT);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
// Write request
OutputStream out = conn.getOutputStream();
try {
out.write(bout.getInternalByteArray(), 0, bout.size());
out.flush();
} finally {
out.close();
}
// Get response
int responseCode = conn.getResponseCode();
if(responseCode != 200) throw new IOException("Unexpect response code: " + responseCode);
if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: got connection");
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Element document = builder.parse(conn.getInputStream()).getDocumentElement();
if(!"connection".equals(document.getNodeName())) throw new IOException("Unexpected root node name: " + document.getNodeName());
Identifier id = Identifier.valueOf(document.getAttribute("id"));
if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: got id=" + id);
HttpSocket httpSocket = new HttpSocket(
HttpSocketClient.this,
id,
connectTime,
endpointURL
);
if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: adding socket");
addSocket(httpSocket);
if(onConnect!=null) {
if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: calling onConnect");
onConnect.call(httpSocket);
}
} catch(Exception exc) {
if(onError!=null) {
if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: calling onError");
onError.call(exc);
}
}
}
}
);
} | java | public void connect(
final String endpoint,
final Callback<? super HttpSocket> onConnect,
final Callback<? super Exception> onError
) {
executors.getUnbounded().submit(
new Runnable() {
@Override
public void run() {
try {
// Build request bytes
AoByteArrayOutputStream bout = new AoByteArrayOutputStream();
try {
try (DataOutputStream out = new DataOutputStream(bout)) {
out.writeBytes("action=connect");
}
} finally {
bout.close();
}
long connectTime = System.currentTimeMillis();
URL endpointURL = new URL(endpoint);
HttpURLConnection conn = (HttpURLConnection)endpointURL.openConnection();
conn.setAllowUserInteraction(false);
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(bout.size());
conn.setInstanceFollowRedirects(false);
conn.setReadTimeout(CONNECT_TIMEOUT);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
// Write request
OutputStream out = conn.getOutputStream();
try {
out.write(bout.getInternalByteArray(), 0, bout.size());
out.flush();
} finally {
out.close();
}
// Get response
int responseCode = conn.getResponseCode();
if(responseCode != 200) throw new IOException("Unexpect response code: " + responseCode);
if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: got connection");
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Element document = builder.parse(conn.getInputStream()).getDocumentElement();
if(!"connection".equals(document.getNodeName())) throw new IOException("Unexpected root node name: " + document.getNodeName());
Identifier id = Identifier.valueOf(document.getAttribute("id"));
if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: got id=" + id);
HttpSocket httpSocket = new HttpSocket(
HttpSocketClient.this,
id,
connectTime,
endpointURL
);
if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: adding socket");
addSocket(httpSocket);
if(onConnect!=null) {
if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: calling onConnect");
onConnect.call(httpSocket);
}
} catch(Exception exc) {
if(onError!=null) {
if(DEBUG) System.out.println("DEBUG: HttpSocketClient: connect: calling onError");
onError.call(exc);
}
}
}
}
);
} | [
"public",
"void",
"connect",
"(",
"final",
"String",
"endpoint",
",",
"final",
"Callback",
"<",
"?",
"super",
"HttpSocket",
">",
"onConnect",
",",
"final",
"Callback",
"<",
"?",
"super",
"Exception",
">",
"onError",
")",
"{",
"executors",
".",
"getUnbounded"... | Asynchronously connects. | [
"Asynchronously",
"connects",
"."
] | 37bb05ff06fc19622162d4671fb79d3fc4e969a3 | https://github.com/aoindustries/ao-messaging-http-client/blob/37bb05ff06fc19622162d4671fb79d3fc4e969a3/src/main/java/com/aoindustries/messaging/http/client/HttpSocketClient.java#L65-L133 | train |
nlalevee/jsourcemap | jsourcemap/src/java/org/hibnet/jsourcemap/Base64VLQ.java | Base64VLQ.encode | static final String encode(int aValue) {
String encoded = "";
int digit;
int vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit |= VLQ_CONTINUATION_BIT;
}
encoded += Base64.encode(digit);
} while (vlq > 0);
return encoded;
} | java | static final String encode(int aValue) {
String encoded = "";
int digit;
int vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit |= VLQ_CONTINUATION_BIT;
}
encoded += Base64.encode(digit);
} while (vlq > 0);
return encoded;
} | [
"static",
"final",
"String",
"encode",
"(",
"int",
"aValue",
")",
"{",
"String",
"encoded",
"=",
"\"\"",
";",
"int",
"digit",
";",
"int",
"vlq",
"=",
"toVLQSigned",
"(",
"aValue",
")",
";",
"do",
"{",
"digit",
"=",
"vlq",
"&",
"VLQ_BASE_MASK",
";",
"... | Returns the base 64 VLQ encoded value. | [
"Returns",
"the",
"base",
"64",
"VLQ",
"encoded",
"value",
"."
] | 361a99c73d51c11afa5579dd83d477c4d0345599 | https://github.com/nlalevee/jsourcemap/blob/361a99c73d51c11afa5579dd83d477c4d0345599/jsourcemap/src/java/org/hibnet/jsourcemap/Base64VLQ.java#L64-L82 | train |
nlalevee/jsourcemap | jsourcemap/src/java/org/hibnet/jsourcemap/Base64VLQ.java | Base64VLQ.decode | static Base64VLQResult decode(String aStr, int aIndex) {
int strLen = aStr.length();
int result = 0;
int shift = 0;
boolean continuation;
int digit;
do {
if (aIndex >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = Base64.decode(aStr.charAt(aIndex++));
if (digit == -1) {
throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
}
continuation = (digit & VLQ_CONTINUATION_BIT) != 0;
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
return new Base64VLQResult(fromVLQSigned(result), aIndex);
} | java | static Base64VLQResult decode(String aStr, int aIndex) {
int strLen = aStr.length();
int result = 0;
int shift = 0;
boolean continuation;
int digit;
do {
if (aIndex >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = Base64.decode(aStr.charAt(aIndex++));
if (digit == -1) {
throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
}
continuation = (digit & VLQ_CONTINUATION_BIT) != 0;
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
return new Base64VLQResult(fromVLQSigned(result), aIndex);
} | [
"static",
"Base64VLQResult",
"decode",
"(",
"String",
"aStr",
",",
"int",
"aIndex",
")",
"{",
"int",
"strLen",
"=",
"aStr",
".",
"length",
"(",
")",
";",
"int",
"result",
"=",
"0",
";",
"int",
"shift",
"=",
"0",
";",
"boolean",
"continuation",
";",
"... | Decodes the next base 64 VLQ value from the given string and returns the value and the rest of the string via the out parameter.
@return | [
"Decodes",
"the",
"next",
"base",
"64",
"VLQ",
"value",
"from",
"the",
"given",
"string",
"and",
"returns",
"the",
"value",
"and",
"the",
"rest",
"of",
"the",
"string",
"via",
"the",
"out",
"parameter",
"."
] | 361a99c73d51c11afa5579dd83d477c4d0345599 | https://github.com/nlalevee/jsourcemap/blob/361a99c73d51c11afa5579dd83d477c4d0345599/jsourcemap/src/java/org/hibnet/jsourcemap/Base64VLQ.java#L89-L113 | train |
aoindustries/semanticcms-core-model | src/main/java/com/semanticcms/core/model/Element.java | Element.generateIdPrefix | public static StringBuilder generateIdPrefix(String template, String prefix) {
NullArgumentException.checkNotNull(template, "template");
NullArgumentException.checkNotNull(prefix, "prefix");
assert isValidId(prefix);
final int len = template.length();
// First character must be [A-Za-z]
int pos = 0;
while(pos < len) {
char ch = template.charAt(pos);
if(
(ch >= 'A' && ch <= 'Z')
|| (ch >= 'a' && ch <= 'z')
) {
break;
}
pos++;
}
StringBuilder idPrefix;
if(pos == len) {
// No usable characters from label
idPrefix = new StringBuilder(prefix);
} else {
// Get remaining usable characters from label
idPrefix = new StringBuilder(len - pos);
//idPrefix.append(template.charAt(pos));
//pos++;
// Remaining must match [A-Za-z0-9:_.-]
while(pos < len) {
char ch = template.charAt(pos);
pos++;
// Convert space to '-'
if(ch == ' ') {
idPrefix.append('-');
} else if(
(ch >= 'A' && ch <= 'Z')
|| (ch >= 'a' && ch <= 'z')
|| (ch >= '0' && ch <= '9')
|| ch == ':'
|| ch == '_'
|| ch == '.'
|| ch == '-'
) {
if(ch >= 'A' && ch <= 'Z') {
// Works since we're only using ASCII range:
ch = (char)(ch + ('a' - 'A'));
// Would support Unicode, but id's don't have Unicode:
// ch = Character.toLowerCase(ch);
}
idPrefix.append(ch);
}
}
}
assert isValidId(idPrefix.toString());
return idPrefix;
} | java | public static StringBuilder generateIdPrefix(String template, String prefix) {
NullArgumentException.checkNotNull(template, "template");
NullArgumentException.checkNotNull(prefix, "prefix");
assert isValidId(prefix);
final int len = template.length();
// First character must be [A-Za-z]
int pos = 0;
while(pos < len) {
char ch = template.charAt(pos);
if(
(ch >= 'A' && ch <= 'Z')
|| (ch >= 'a' && ch <= 'z')
) {
break;
}
pos++;
}
StringBuilder idPrefix;
if(pos == len) {
// No usable characters from label
idPrefix = new StringBuilder(prefix);
} else {
// Get remaining usable characters from label
idPrefix = new StringBuilder(len - pos);
//idPrefix.append(template.charAt(pos));
//pos++;
// Remaining must match [A-Za-z0-9:_.-]
while(pos < len) {
char ch = template.charAt(pos);
pos++;
// Convert space to '-'
if(ch == ' ') {
idPrefix.append('-');
} else if(
(ch >= 'A' && ch <= 'Z')
|| (ch >= 'a' && ch <= 'z')
|| (ch >= '0' && ch <= '9')
|| ch == ':'
|| ch == '_'
|| ch == '.'
|| ch == '-'
) {
if(ch >= 'A' && ch <= 'Z') {
// Works since we're only using ASCII range:
ch = (char)(ch + ('a' - 'A'));
// Would support Unicode, but id's don't have Unicode:
// ch = Character.toLowerCase(ch);
}
idPrefix.append(ch);
}
}
}
assert isValidId(idPrefix.toString());
return idPrefix;
} | [
"public",
"static",
"StringBuilder",
"generateIdPrefix",
"(",
"String",
"template",
",",
"String",
"prefix",
")",
"{",
"NullArgumentException",
".",
"checkNotNull",
"(",
"template",
",",
"\"template\"",
")",
";",
"NullArgumentException",
".",
"checkNotNull",
"(",
"p... | Generates a valid ID from an arbitrary string.
Strip all character not matching [A-Za-z][A-Za-z0-9:_.-]*
Also converts characters to lower case.
@param template The preferred text to base the id on
@param prefix The base used when template is unusable (must be a valid id or invalid ID's may be generated)
@see <a href="http://www.w3.org/TR/2002/REC-xhtml1-20020801/#C_8">http://www.w3.org/TR/2002/REC-xhtml1-20020801/#C_8</a> | [
"Generates",
"a",
"valid",
"ID",
"from",
"an",
"arbitrary",
"string",
"."
] | 14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624 | https://github.com/aoindustries/semanticcms-core-model/blob/14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624/src/main/java/com/semanticcms/core/model/Element.java#L82-L136 | train |
aoindustries/semanticcms-core-model | src/main/java/com/semanticcms/core/model/Element.java | Element.setPage | void setPage(Page page) {
synchronized(lock) {
checkNotFrozen();
if(this.page != null) throw new IllegalStateException("element already has a page: " + this);
this.page = page;
}
assert checkPageAndParentElement();
} | java | void setPage(Page page) {
synchronized(lock) {
checkNotFrozen();
if(this.page != null) throw new IllegalStateException("element already has a page: " + this);
this.page = page;
}
assert checkPageAndParentElement();
} | [
"void",
"setPage",
"(",
"Page",
"page",
")",
"{",
"synchronized",
"(",
"lock",
")",
"{",
"checkNotFrozen",
"(",
")",
";",
"if",
"(",
"this",
".",
"page",
"!=",
"null",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"element already has a page: \"",
"+"... | This is set when the element is associated with the page.
@see Page#addElement(com.aoindustries.docs.Element) | [
"This",
"is",
"set",
"when",
"the",
"element",
"is",
"associated",
"with",
"the",
"page",
"."
] | 14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624 | https://github.com/aoindustries/semanticcms-core-model/blob/14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624/src/main/java/com/semanticcms/core/model/Element.java#L194-L201 | train |
aoindustries/semanticcms-core-model | src/main/java/com/semanticcms/core/model/Element.java | Element.getId | public String getId() {
if(id == null) {
synchronized(lock) {
if(id == null) {
if(page != null) {
Map<String,Element> elementsById = page.getElementsById();
// Generate the ID now
String template = getElementIdTemplate();
if(template == null) {
throw new IllegalStateException("null from getElementIdTemplate");
}
StringBuilder possId = Element.generateIdPrefix(template, getDefaultIdPrefix());
int possIdLen = possId.length();
// Find an unused identifier
for(int i=1; i<=Integer.MAX_VALUE; i++) {
if(i == Integer.MAX_VALUE) throw new IllegalStateException("ID not generated");
if(i>1) possId.append('-').append(i);
String newId = possId.toString();
if(
elementsById == null
|| !elementsById.containsKey(newId)
) {
setId(newId, true);
break;
}
// Reset for next element number to check
possId.setLength(possIdLen);
}
}
}
}
}
return id;
} | java | public String getId() {
if(id == null) {
synchronized(lock) {
if(id == null) {
if(page != null) {
Map<String,Element> elementsById = page.getElementsById();
// Generate the ID now
String template = getElementIdTemplate();
if(template == null) {
throw new IllegalStateException("null from getElementIdTemplate");
}
StringBuilder possId = Element.generateIdPrefix(template, getDefaultIdPrefix());
int possIdLen = possId.length();
// Find an unused identifier
for(int i=1; i<=Integer.MAX_VALUE; i++) {
if(i == Integer.MAX_VALUE) throw new IllegalStateException("ID not generated");
if(i>1) possId.append('-').append(i);
String newId = possId.toString();
if(
elementsById == null
|| !elementsById.containsKey(newId)
) {
setId(newId, true);
break;
}
// Reset for next element number to check
possId.setLength(possIdLen);
}
}
}
}
}
return id;
} | [
"public",
"String",
"getId",
"(",
")",
"{",
"if",
"(",
"id",
"==",
"null",
")",
"{",
"synchronized",
"(",
"lock",
")",
"{",
"if",
"(",
"id",
"==",
"null",
")",
"{",
"if",
"(",
"page",
"!=",
"null",
")",
"{",
"Map",
"<",
"String",
",",
"Element"... | When inside a page, every element must have a per-page unique ID, when one is not provided, it will be generated.
When not inside a page, no missing ID is generated and it will remain null. | [
"When",
"inside",
"a",
"page",
"every",
"element",
"must",
"have",
"a",
"per",
"-",
"page",
"unique",
"ID",
"when",
"one",
"is",
"not",
"provided",
"it",
"will",
"be",
"generated",
".",
"When",
"not",
"inside",
"a",
"page",
"no",
"missing",
"ID",
"is",... | 14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624 | https://github.com/aoindustries/semanticcms-core-model/blob/14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624/src/main/java/com/semanticcms/core/model/Element.java#L214-L247 | train |
aoindustries/semanticcms-core-model | src/main/java/com/semanticcms/core/model/Element.java | Element.getElementRef | public ElementRef getElementRef() throws IllegalStateException {
Page p = page;
if(p == null) throw new IllegalStateException("page not set");
PageRef pageRef = p.getPageRef();
String i = getId();
if(i == null) throw new IllegalStateException("page not set so no id generated");
ElementRef er = elementRef;
if(
er == null
// Make sure object still valid
|| !er.getPageRef().equals(pageRef)
|| !er.getId().equals(i)
) {
er = new ElementRef(pageRef, i);
elementRef = er;
}
return er;
} | java | public ElementRef getElementRef() throws IllegalStateException {
Page p = page;
if(p == null) throw new IllegalStateException("page not set");
PageRef pageRef = p.getPageRef();
String i = getId();
if(i == null) throw new IllegalStateException("page not set so no id generated");
ElementRef er = elementRef;
if(
er == null
// Make sure object still valid
|| !er.getPageRef().equals(pageRef)
|| !er.getId().equals(i)
) {
er = new ElementRef(pageRef, i);
elementRef = er;
}
return er;
} | [
"public",
"ElementRef",
"getElementRef",
"(",
")",
"throws",
"IllegalStateException",
"{",
"Page",
"p",
"=",
"page",
";",
"if",
"(",
"p",
"==",
"null",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"page not set\"",
")",
";",
"PageRef",
"pageRef",
"=",
... | Gets an ElementRef for this element.
Must have a page set.
If id has not yet been set, one will be generated.
@throws IllegalStateException if page not set | [
"Gets",
"an",
"ElementRef",
"for",
"this",
"element",
".",
"Must",
"have",
"a",
"page",
"set",
".",
"If",
"id",
"has",
"not",
"yet",
"been",
"set",
"one",
"will",
"be",
"generated",
"."
] | 14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624 | https://github.com/aoindustries/semanticcms-core-model/blob/14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624/src/main/java/com/semanticcms/core/model/Element.java#L274-L291 | train |
aoindustries/semanticcms-core-model | src/main/java/com/semanticcms/core/model/Element.java | Element.setParentElement | private void setParentElement(Element parentElement) {
synchronized(lock) {
checkNotFrozen();
if(this.parentElement != null) throw new IllegalStateException("parentElement already set");
this.parentElement = parentElement;
}
assert checkPageAndParentElement();
} | java | private void setParentElement(Element parentElement) {
synchronized(lock) {
checkNotFrozen();
if(this.parentElement != null) throw new IllegalStateException("parentElement already set");
this.parentElement = parentElement;
}
assert checkPageAndParentElement();
} | [
"private",
"void",
"setParentElement",
"(",
"Element",
"parentElement",
")",
"{",
"synchronized",
"(",
"lock",
")",
"{",
"checkNotFrozen",
"(",
")",
";",
"if",
"(",
"this",
".",
"parentElement",
"!=",
"null",
")",
"throw",
"new",
"IllegalStateException",
"(",
... | Sets the parent element of this element. | [
"Sets",
"the",
"parent",
"element",
"of",
"this",
"element",
"."
] | 14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624 | https://github.com/aoindustries/semanticcms-core-model/blob/14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624/src/main/java/com/semanticcms/core/model/Element.java#L305-L312 | train |
aoindustries/semanticcms-core-model | src/main/java/com/semanticcms/core/model/Element.java | Element.addChildElement | @Override
public Long addChildElement(Element childElement, ElementWriter elementWriter) {
Long elementKey = super.addChildElement(childElement, elementWriter);
childElement.setParentElement(this);
return elementKey;
} | java | @Override
public Long addChildElement(Element childElement, ElementWriter elementWriter) {
Long elementKey = super.addChildElement(childElement, elementWriter);
childElement.setParentElement(this);
return elementKey;
} | [
"@",
"Override",
"public",
"Long",
"addChildElement",
"(",
"Element",
"childElement",
",",
"ElementWriter",
"elementWriter",
")",
"{",
"Long",
"elementKey",
"=",
"super",
".",
"addChildElement",
"(",
"childElement",
",",
"elementWriter",
")",
";",
"childElement",
... | Adds a child element to this element. | [
"Adds",
"a",
"child",
"element",
"to",
"this",
"element",
"."
] | 14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624 | https://github.com/aoindustries/semanticcms-core-model/blob/14bdbe3f3d69b2b337129c5b1afcaa9e87cb5624/src/main/java/com/semanticcms/core/model/Element.java#L329-L334 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/LoggingProxy.java | LoggingProxy.log | private static void log(File logFile, long connectionId, char separator, String line) {
synchronized(logFile) {
try {
try (Writer out = new FileWriter(logFile, true)) {
out.write(Long.toString(connectionId));
out.write(separator);
out.write(' ');
out.write(line);
out.write('\n');
}
} catch(IOException e) {
e.printStackTrace(System.err);
}
}
} | java | private static void log(File logFile, long connectionId, char separator, String line) {
synchronized(logFile) {
try {
try (Writer out = new FileWriter(logFile, true)) {
out.write(Long.toString(connectionId));
out.write(separator);
out.write(' ');
out.write(line);
out.write('\n');
}
} catch(IOException e) {
e.printStackTrace(System.err);
}
}
} | [
"private",
"static",
"void",
"log",
"(",
"File",
"logFile",
",",
"long",
"connectionId",
",",
"char",
"separator",
",",
"String",
"line",
")",
"{",
"synchronized",
"(",
"logFile",
")",
"{",
"try",
"{",
"try",
"(",
"Writer",
"out",
"=",
"new",
"FileWriter... | Writes one line to the given file, synchronizes on the file object. | [
"Writes",
"one",
"line",
"to",
"the",
"given",
"file",
"synchronizes",
"on",
"the",
"file",
"object",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/LoggingProxy.java#L52-L66 | train |
HalBuilder/halbuilder-guava | src/main/java/com/theoryinpractise/halbuilder/guava/Representations.java | Representations.tryValue | public static Optional<Object> tryValue(ReadableRepresentation representation, String name) {
try {
return Optional.fromNullable(representation.getValue(name));
} catch (RepresentationException e) {
return Optional.absent();
}
} | java | public static Optional<Object> tryValue(ReadableRepresentation representation, String name) {
try {
return Optional.fromNullable(representation.getValue(name));
} catch (RepresentationException e) {
return Optional.absent();
}
} | [
"public",
"static",
"Optional",
"<",
"Object",
">",
"tryValue",
"(",
"ReadableRepresentation",
"representation",
",",
"String",
"name",
")",
"{",
"try",
"{",
"return",
"Optional",
".",
"fromNullable",
"(",
"representation",
".",
"getValue",
"(",
"name",
")",
"... | Returns a property from the Representation.
@param name The property to return
@return A Guava Optional for the property | [
"Returns",
"a",
"property",
"from",
"the",
"Representation",
"."
] | 648cb1ae6c4b4cebd82364a8d72d9801bd3db771 | https://github.com/HalBuilder/halbuilder-guava/blob/648cb1ae6c4b4cebd82364a8d72d9801bd3db771/src/main/java/com/theoryinpractise/halbuilder/guava/Representations.java#L90-L96 | train |
nlalevee/jsourcemap | jsourcemap/src/java/org/hibnet/jsourcemap/Util.java | Util.intcmp | private static final int intcmp(Integer i1, Integer i2) {
if (i1 == null && i2 == null) {
return 0;
}
if (i1 == null) {
return -i2;
}
if (i2 == null) {
return i1;
}
return i1 - i2;
} | java | private static final int intcmp(Integer i1, Integer i2) {
if (i1 == null && i2 == null) {
return 0;
}
if (i1 == null) {
return -i2;
}
if (i2 == null) {
return i1;
}
return i1 - i2;
} | [
"private",
"static",
"final",
"int",
"intcmp",
"(",
"Integer",
"i1",
",",
"Integer",
"i2",
")",
"{",
"if",
"(",
"i1",
"==",
"null",
"&&",
"i2",
"==",
"null",
")",
"{",
"return",
"0",
";",
"}",
"if",
"(",
"i1",
"==",
"null",
")",
"{",
"return",
... | mimic the behaviour of i1 - i2 in JS | [
"mimic",
"the",
"behaviour",
"of",
"i1",
"-",
"i2",
"in",
"JS"
] | 361a99c73d51c11afa5579dd83d477c4d0345599 | https://github.com/nlalevee/jsourcemap/blob/361a99c73d51c11afa5579dd83d477c4d0345599/jsourcemap/src/java/org/hibnet/jsourcemap/Util.java#L220-L231 | train |
aoindustries/semanticcms-news-model | src/main/java/com/semanticcms/news/model/News.java | News.compareTo | @Override
public int compareTo(News o) {
int diff = o.getPubDate().compareTo(getPubDate());
if(diff != 0) return diff;
return getPage().compareTo(o.getPage());
} | java | @Override
public int compareTo(News o) {
int diff = o.getPubDate().compareTo(getPubDate());
if(diff != 0) return diff;
return getPage().compareTo(o.getPage());
} | [
"@",
"Override",
"public",
"int",
"compareTo",
"(",
"News",
"o",
")",
"{",
"int",
"diff",
"=",
"o",
".",
"getPubDate",
"(",
")",
".",
"compareTo",
"(",
"getPubDate",
"(",
")",
")",
";",
"if",
"(",
"diff",
"!=",
"0",
")",
"return",
"diff",
";",
"r... | Ordered by pubDate desc, page | [
"Ordered",
"by",
"pubDate",
"desc",
"page"
] | addcb3d4a112dabd4ccf02b8f2c9dd3343dbff23 | https://github.com/aoindustries/semanticcms-news-model/blob/addcb3d4a112dabd4ccf02b8f2c9dd3343dbff23/src/main/java/com/semanticcms/news/model/News.java#L53-L58 | train |
NessComputing/components-ness-jmx | src/main/java/com/nesscomputing/jmx/starter/JmxExporterConfig.java | JmxExporterConfig.defaultJmxExporterConfig | public static JmxExporterConfig defaultJmxExporterConfig(final InetAddress hostname, final Integer rmiRegistryPort, final Integer rmiServerPort, final boolean useRandomIds)
throws IOException
{
return new JmxExporterConfig(
(hostname != null) ? hostname : InetAddress.getByName(null),
(rmiRegistryPort != null) ? rmiRegistryPort : NetUtils.findUnusedPort(),
(rmiServerPort != null) ? rmiServerPort : NetUtils.findUnusedPort(),
useRandomIds);
} | java | public static JmxExporterConfig defaultJmxExporterConfig(final InetAddress hostname, final Integer rmiRegistryPort, final Integer rmiServerPort, final boolean useRandomIds)
throws IOException
{
return new JmxExporterConfig(
(hostname != null) ? hostname : InetAddress.getByName(null),
(rmiRegistryPort != null) ? rmiRegistryPort : NetUtils.findUnusedPort(),
(rmiServerPort != null) ? rmiServerPort : NetUtils.findUnusedPort(),
useRandomIds);
} | [
"public",
"static",
"JmxExporterConfig",
"defaultJmxExporterConfig",
"(",
"final",
"InetAddress",
"hostname",
",",
"final",
"Integer",
"rmiRegistryPort",
",",
"final",
"Integer",
"rmiServerPort",
",",
"final",
"boolean",
"useRandomIds",
")",
"throws",
"IOException",
"{"... | Creates a default configuration object.
@param hostname The hostname to use. If null, the localhost is used.
@param rmiRegistryPort The port for the JMX registry. This is where remote clients will connect to the MBean server.
@param rmiServerPort The port for the JMX Server. If null, a random port is used.
@param useRandomIds If true, use random ids for RMI.
@return A JmxExportConfig object.
@throws IOException | [
"Creates",
"a",
"default",
"configuration",
"object",
"."
] | 694e0f117e1579019df835528a150257b57330b4 | https://github.com/NessComputing/components-ness-jmx/blob/694e0f117e1579019df835528a150257b57330b4/src/main/java/com/nesscomputing/jmx/starter/JmxExporterConfig.java#L43-L51 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/NativeToUnixWriter.java | NativeToUnixWriter.getInstance | public static Writer getInstance(Writer out) {
// Already in Unix format, no conversion necessary
if(UNIX_EOL.equals(EOL)) return out;
// Use FindReplaceWriter
return new FindReplaceWriter(out, EOL, UNIX_EOL);
} | java | public static Writer getInstance(Writer out) {
// Already in Unix format, no conversion necessary
if(UNIX_EOL.equals(EOL)) return out;
// Use FindReplaceWriter
return new FindReplaceWriter(out, EOL, UNIX_EOL);
} | [
"public",
"static",
"Writer",
"getInstance",
"(",
"Writer",
"out",
")",
"{",
"// Already in Unix format, no conversion necessary",
"if",
"(",
"UNIX_EOL",
".",
"equals",
"(",
"EOL",
")",
")",
"return",
"out",
";",
"// Use FindReplaceWriter",
"return",
"new",
"FindRep... | Gets an instance of the Writer that performs the conversion.
The implementation may be optimized for common platforms. | [
"Gets",
"an",
"instance",
"of",
"the",
"Writer",
"that",
"performs",
"the",
"conversion",
".",
"The",
"implementation",
"may",
"be",
"optimized",
"for",
"common",
"platforms",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/NativeToUnixWriter.java#L54-L59 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/awt/image/Images.java | Images.getRGB | public static int[] getRGB(BufferedImage image) {
int[] pixels = getRGBArray(image);
getRGB(image, pixels);
return pixels;
} | java | public static int[] getRGB(BufferedImage image) {
int[] pixels = getRGBArray(image);
getRGB(image, pixels);
return pixels;
} | [
"public",
"static",
"int",
"[",
"]",
"getRGB",
"(",
"BufferedImage",
"image",
")",
"{",
"int",
"[",
"]",
"pixels",
"=",
"getRGBArray",
"(",
"image",
")",
";",
"getRGB",
"(",
"image",
",",
"pixels",
")",
";",
"return",
"pixels",
";",
"}"
] | Gets the RGB pixels for the given image into a new array. | [
"Gets",
"the",
"RGB",
"pixels",
"for",
"the",
"given",
"image",
"into",
"a",
"new",
"array",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/awt/image/Images.java#L66-L70 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/awt/image/Images.java | Images.getImageFromResources | public static Image getImageFromResources(Class<?> clazz, String name) throws IOException {
return getImageFromResources(clazz, name, Toolkit.getDefaultToolkit());
} | java | public static Image getImageFromResources(Class<?> clazz, String name) throws IOException {
return getImageFromResources(clazz, name, Toolkit.getDefaultToolkit());
} | [
"public",
"static",
"Image",
"getImageFromResources",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"name",
")",
"throws",
"IOException",
"{",
"return",
"getImageFromResources",
"(",
"clazz",
",",
"name",
",",
"Toolkit",
".",
"getDefaultToolkit",
"(",
"... | Loads an image from a resource using the default toolkit. | [
"Loads",
"an",
"image",
"from",
"a",
"resource",
"using",
"the",
"default",
"toolkit",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/awt/image/Images.java#L170-L172 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/awt/image/Images.java | Images.getImageFromResources | public static Image getImageFromResources(Class<?> clazz, String name, Toolkit toolkit) throws IOException {
byte[] imageData;
InputStream in = clazz.getResourceAsStream(name);
if(in==null) throw new IOException("Unable to find resource: "+name);
try {
imageData = IoUtils.readFully(in);
} finally {
in.close();
}
return toolkit.createImage(imageData);
} | java | public static Image getImageFromResources(Class<?> clazz, String name, Toolkit toolkit) throws IOException {
byte[] imageData;
InputStream in = clazz.getResourceAsStream(name);
if(in==null) throw new IOException("Unable to find resource: "+name);
try {
imageData = IoUtils.readFully(in);
} finally {
in.close();
}
return toolkit.createImage(imageData);
} | [
"public",
"static",
"Image",
"getImageFromResources",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"name",
",",
"Toolkit",
"toolkit",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"imageData",
";",
"InputStream",
"in",
"=",
"clazz",
".",
"ge... | Loads an image from a resource using the provided toolkit. | [
"Loads",
"an",
"image",
"from",
"a",
"resource",
"using",
"the",
"provided",
"toolkit",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/awt/image/Images.java#L177-L187 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebPage.java | WebPage.printLoginForm | public void printLoginForm(WebPage page, LoginException loginException, WebSiteRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
getParent().printLoginForm(page, loginException, req, resp);
} | java | public void printLoginForm(WebPage page, LoginException loginException, WebSiteRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
getParent().printLoginForm(page, loginException, req, resp);
} | [
"public",
"void",
"printLoginForm",
"(",
"WebPage",
"page",
",",
"LoginException",
"loginException",
",",
"WebSiteRequest",
"req",
",",
"HttpServletResponse",
"resp",
")",
"throws",
"ServletException",
",",
"IOException",
",",
"SQLException",
"{",
"getParent",
"(",
... | Prints the form that is used to login. | [
"Prints",
"the",
"form",
"that",
"is",
"used",
"to",
"login",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebPage.java#L176-L178 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebPage.java | WebPage.printUnauthorizedPage | public void printUnauthorizedPage(WebPage page, WebSiteRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
getParent().printUnauthorizedPage(page, req, resp);
} | java | public void printUnauthorizedPage(WebPage page, WebSiteRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
getParent().printUnauthorizedPage(page, req, resp);
} | [
"public",
"void",
"printUnauthorizedPage",
"(",
"WebPage",
"page",
",",
"WebSiteRequest",
"req",
",",
"HttpServletResponse",
"resp",
")",
"throws",
"ServletException",
",",
"IOException",
",",
"SQLException",
"{",
"getParent",
"(",
")",
".",
"printUnauthorizedPage",
... | Prints the unauthorized page message. | [
"Prints",
"the",
"unauthorized",
"page",
"message",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebPage.java#L183-L185 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebPage.java | WebPage.getClassLastModified | protected final long getClassLastModified() throws IOException, SQLException {
String dir=getServletContext().getRealPath("/WEB-INF/classes");
if(dir!=null && dir.length()>0) {
// Try to get from the class file
long lastMod=new File(dir, getClass().getName().replace('.', File.separatorChar) + ".class").lastModified();
if(lastMod!=0 && lastMod!=-1) return lastMod;
}
return getUptime();
} | java | protected final long getClassLastModified() throws IOException, SQLException {
String dir=getServletContext().getRealPath("/WEB-INF/classes");
if(dir!=null && dir.length()>0) {
// Try to get from the class file
long lastMod=new File(dir, getClass().getName().replace('.', File.separatorChar) + ".class").lastModified();
if(lastMod!=0 && lastMod!=-1) return lastMod;
}
return getUptime();
} | [
"protected",
"final",
"long",
"getClassLastModified",
"(",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"String",
"dir",
"=",
"getServletContext",
"(",
")",
".",
"getRealPath",
"(",
"\"/WEB-INF/classes\"",
")",
";",
"if",
"(",
"dir",
"!=",
"null",
"... | Gets the last modified time of the java class file. If the class file is
unavailable, it defaults to the time the servlets were loaded.
@see WebSiteFrameworkConfiguration#getServletDirectory
@see ErrorReportingServlet#getUptime() | [
"Gets",
"the",
"last",
"modified",
"time",
"of",
"the",
"java",
"class",
"file",
".",
"If",
"the",
"class",
"file",
"is",
"unavailable",
"it",
"defaults",
"to",
"the",
"time",
"the",
"servlets",
"were",
"loaded",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebPage.java#L228-L236 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebPage.java | WebPage.getWebPageAndChildrenLastModified | public long getWebPageAndChildrenLastModified(WebSiteRequest req) throws IOException, SQLException {
WebPage[] myPages = getCachedPages(req);
int len = myPages.length;
long mostRecent = getClassLastModified();
if(mostRecent==-1) return -1;
for (int c = 0; c < len; c++) {
long time = myPages[c].getLastModified(req);
if(time==-1) return -1;
if (time > mostRecent) mostRecent = time;
}
return mostRecent;
} | java | public long getWebPageAndChildrenLastModified(WebSiteRequest req) throws IOException, SQLException {
WebPage[] myPages = getCachedPages(req);
int len = myPages.length;
long mostRecent = getClassLastModified();
if(mostRecent==-1) return -1;
for (int c = 0; c < len; c++) {
long time = myPages[c].getLastModified(req);
if(time==-1) return -1;
if (time > mostRecent) mostRecent = time;
}
return mostRecent;
} | [
"public",
"long",
"getWebPageAndChildrenLastModified",
"(",
"WebSiteRequest",
"req",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"WebPage",
"[",
"]",
"myPages",
"=",
"getCachedPages",
"(",
"req",
")",
";",
"int",
"len",
"=",
"myPages",
".",
"length",... | Gets the most recent last modified time of this page and its immediate children. | [
"Gets",
"the",
"most",
"recent",
"last",
"modified",
"time",
"of",
"this",
"page",
"and",
"its",
"immediate",
"children",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebPage.java#L241-L252 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebPage.java | WebPage.getLastModifiedRecursive | final public long getLastModifiedRecursive(WebSiteRequest req) throws IOException, SQLException {
long time=getLastModified(req);
WebPage[] myPages=getCachedPages(req);
int len=myPages.length;
for(int c=0; c<len; c++) {
long time2=myPages[c].getLastModifiedRecursive(req);
if(time2>time) time=time2;
}
return time;
} | java | final public long getLastModifiedRecursive(WebSiteRequest req) throws IOException, SQLException {
long time=getLastModified(req);
WebPage[] myPages=getCachedPages(req);
int len=myPages.length;
for(int c=0; c<len; c++) {
long time2=myPages[c].getLastModifiedRecursive(req);
if(time2>time) time=time2;
}
return time;
} | [
"final",
"public",
"long",
"getLastModifiedRecursive",
"(",
"WebSiteRequest",
"req",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"long",
"time",
"=",
"getLastModified",
"(",
"req",
")",
";",
"WebPage",
"[",
"]",
"myPages",
"=",
"getCachedPages",
"(",... | Recursively gets the most recent modification time. | [
"Recursively",
"gets",
"the",
"most",
"recent",
"modification",
"time",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebPage.java#L257-L266 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebPage.java | WebPage.getLastModifiedRecursive | public static long getLastModifiedRecursive(File file) {
long time=file.lastModified();
if(file.isDirectory()) {
String[] list=file.list();
if(list!=null) {
int len=list.length;
for(int c=0; c<len; c++) {
long time2=getLastModifiedRecursive(new File(file, list[c]));
if (time2 > time) time=time2;
}
}
}
return time;
} | java | public static long getLastModifiedRecursive(File file) {
long time=file.lastModified();
if(file.isDirectory()) {
String[] list=file.list();
if(list!=null) {
int len=list.length;
for(int c=0; c<len; c++) {
long time2=getLastModifiedRecursive(new File(file, list[c]));
if (time2 > time) time=time2;
}
}
}
return time;
} | [
"public",
"static",
"long",
"getLastModifiedRecursive",
"(",
"File",
"file",
")",
"{",
"long",
"time",
"=",
"file",
".",
"lastModified",
"(",
")",
";",
"if",
"(",
"file",
".",
"isDirectory",
"(",
")",
")",
"{",
"String",
"[",
"]",
"list",
"=",
"file",
... | Recursively gets the most recent modification time of a file or directory. | [
"Recursively",
"gets",
"the",
"most",
"recent",
"modification",
"time",
"of",
"a",
"file",
"or",
"directory",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebPage.java#L271-L284 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebPage.java | WebPage.doGet | public void doGet(
ChainWriter out,
WebSiteRequest req,
HttpServletResponse resp
) throws ServletException, IOException, SQLException {
} | java | public void doGet(
ChainWriter out,
WebSiteRequest req,
HttpServletResponse resp
) throws ServletException, IOException, SQLException {
} | [
"public",
"void",
"doGet",
"(",
"ChainWriter",
"out",
",",
"WebSiteRequest",
"req",
",",
"HttpServletResponse",
"resp",
")",
"throws",
"ServletException",
",",
"IOException",
",",
"SQLException",
"{",
"}"
] | By default, GET provides no content.
@param out the <code>ChainWriter</code> to send output to
@param req the current <code>WebSiteRequest</code>
@param resp the <code>HttpServletResponse</code> for this request, is <code>null</code> when searching | [
"By",
"default",
"GET",
"provides",
"no",
"content",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebPage.java#L369-L374 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebPage.java | WebPage.getRootPage | public final WebPage getRootPage() throws IOException, SQLException {
WebPage page = this;
WebPage parent;
while ((parent = page.getParent()) != null) page = parent;
return page;
} | java | public final WebPage getRootPage() throws IOException, SQLException {
WebPage page = this;
WebPage parent;
while ((parent = page.getParent()) != null) page = parent;
return page;
} | [
"public",
"final",
"WebPage",
"getRootPage",
"(",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"WebPage",
"page",
"=",
"this",
";",
"WebPage",
"parent",
";",
"while",
"(",
"(",
"parent",
"=",
"page",
".",
"getParent",
"(",
")",
")",
"!=",
"nul... | Gets the root page in the web page hierarchy. The root page has no parent. | [
"Gets",
"the",
"root",
"page",
"in",
"the",
"web",
"page",
"hierarchy",
".",
"The",
"root",
"page",
"has",
"no",
"parent",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebPage.java#L584-L589 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebPage.java | WebPage.getNavImageURL | public String getNavImageURL(WebSiteRequest req, HttpServletResponse resp, Object params) throws IOException, SQLException {
return resp.encodeURL(req.getContextPath()+req.getURL(this, params));
} | java | public String getNavImageURL(WebSiteRequest req, HttpServletResponse resp, Object params) throws IOException, SQLException {
return resp.encodeURL(req.getContextPath()+req.getURL(this, params));
} | [
"public",
"String",
"getNavImageURL",
"(",
"WebSiteRequest",
"req",
",",
"HttpServletResponse",
"resp",
",",
"Object",
"params",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"return",
"resp",
".",
"encodeURL",
"(",
"req",
".",
"getContextPath",
"(",
"... | Gets the URL associated with a nav image.
@see #getNavImageAlt
@see #getNavImageSuffix | [
"Gets",
"the",
"URL",
"associated",
"with",
"a",
"nav",
"image",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebPage.java#L674-L676 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebPage.java | WebPage.getPageIndexInParent | final public int getPageIndexInParent(WebSiteRequest req) throws IOException, SQLException {
WebPage[] myPages=getParent().getCachedPages(req);
int len=myPages.length;
for(int c=0;c<len;c++) if(myPages[c].equals(this)) return c;
throw new RuntimeException("Unable to find page index in parent.");
} | java | final public int getPageIndexInParent(WebSiteRequest req) throws IOException, SQLException {
WebPage[] myPages=getParent().getCachedPages(req);
int len=myPages.length;
for(int c=0;c<len;c++) if(myPages[c].equals(this)) return c;
throw new RuntimeException("Unable to find page index in parent.");
} | [
"final",
"public",
"int",
"getPageIndexInParent",
"(",
"WebSiteRequest",
"req",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"WebPage",
"[",
"]",
"myPages",
"=",
"getParent",
"(",
")",
".",
"getCachedPages",
"(",
"req",
")",
";",
"int",
"len",
"="... | Gets the index of this page in the parents list of children pages. | [
"Gets",
"the",
"index",
"of",
"this",
"page",
"in",
"the",
"parents",
"list",
"of",
"children",
"pages",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebPage.java#L681-L686 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebPage.java | WebPage.loadClass | public static Class<? extends WebPage> loadClass(String className) throws ClassNotFoundException {
return Class.forName(className).asSubclass(WebPage.class);
} | java | public static Class<? extends WebPage> loadClass(String className) throws ClassNotFoundException {
return Class.forName(className).asSubclass(WebPage.class);
} | [
"public",
"static",
"Class",
"<",
"?",
"extends",
"WebPage",
">",
"loadClass",
"(",
"String",
"className",
")",
"throws",
"ClassNotFoundException",
"{",
"return",
"Class",
".",
"forName",
"(",
"className",
")",
".",
"asSubclass",
"(",
"WebPage",
".",
"class",
... | Dynamically loads new classes based on the source .class file's modified time. | [
"Dynamically",
"loads",
"new",
"classes",
"based",
"on",
"the",
"source",
".",
"class",
"file",
"s",
"modified",
"time",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebPage.java#L923-L925 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebPage.java | WebPage.getCopyright | public String getCopyright(WebSiteRequest req, HttpServletResponse resp, WebPage requestPage) throws IOException, SQLException {
return getParent().getCopyright(req, resp, requestPage);
} | java | public String getCopyright(WebSiteRequest req, HttpServletResponse resp, WebPage requestPage) throws IOException, SQLException {
return getParent().getCopyright(req, resp, requestPage);
} | [
"public",
"String",
"getCopyright",
"(",
"WebSiteRequest",
"req",
",",
"HttpServletResponse",
"resp",
",",
"WebPage",
"requestPage",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"return",
"getParent",
"(",
")",
".",
"getCopyright",
"(",
"req",
",",
"r... | Gets the copyright information for this page. Defaults to the copyright of the parent page.
// TODO: Use dcterms:
http://stackoverflow.com/questions/6665312/is-the-copyright-meta-tag-valid-in-html5
https://wiki.whatwg.org/wiki/MetaExtensions
http://dublincore.org/documents/dcmi-terms/ | [
"Gets",
"the",
"copyright",
"information",
"for",
"this",
"page",
".",
"Defaults",
"to",
"the",
"copyright",
"of",
"the",
"parent",
"page",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebPage.java#L1241-L1243 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/util/StringUtility.java | StringUtility.join | public static String join(Iterable<?> objects, String delimiter) throws ConcurrentModificationException {
int delimiterLength = delimiter.length();
// Find total length
int totalLength = 0;
boolean didOne = false;
for(Object obj : objects) {
if(didOne) totalLength += delimiterLength;
else didOne = true;
totalLength += String.valueOf(obj).length();
}
// Build result
StringBuilder sb = new StringBuilder(totalLength);
didOne = false;
for(Object obj : objects) {
if(didOne) sb.append(delimiter);
else didOne = true;
sb.append(obj);
}
if(totalLength!=sb.length()) throw new ConcurrentModificationException();
return sb.toString();
} | java | public static String join(Iterable<?> objects, String delimiter) throws ConcurrentModificationException {
int delimiterLength = delimiter.length();
// Find total length
int totalLength = 0;
boolean didOne = false;
for(Object obj : objects) {
if(didOne) totalLength += delimiterLength;
else didOne = true;
totalLength += String.valueOf(obj).length();
}
// Build result
StringBuilder sb = new StringBuilder(totalLength);
didOne = false;
for(Object obj : objects) {
if(didOne) sb.append(delimiter);
else didOne = true;
sb.append(obj);
}
if(totalLength!=sb.length()) throw new ConcurrentModificationException();
return sb.toString();
} | [
"public",
"static",
"String",
"join",
"(",
"Iterable",
"<",
"?",
">",
"objects",
",",
"String",
"delimiter",
")",
"throws",
"ConcurrentModificationException",
"{",
"int",
"delimiterLength",
"=",
"delimiter",
".",
"length",
"(",
")",
";",
"// Find total length",
... | Joins the string representation of objects on the provided delimiter.
The iteration will be performed twice. Once to compute the total length
of the resulting string, and the second to build the result.
@throws ConcurrentModificationException if iteration is not consistent between passes
@see #join(java.lang.Iterable, java.lang.String, java.lang.Appendable)
@see #join(java.lang.Object[], java.lang.String) | [
"Joins",
"the",
"string",
"representation",
"of",
"objects",
"on",
"the",
"provided",
"delimiter",
".",
"The",
"iteration",
"will",
"be",
"performed",
"twice",
".",
"Once",
"to",
"compute",
"the",
"total",
"length",
"of",
"the",
"resulting",
"string",
"and",
... | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/StringUtility.java#L137-L157 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/util/StringUtility.java | StringUtility.join | public static <A extends Appendable> A join(Iterable<?> objects, String delimiter, A out) throws IOException {
boolean didOne = false;
for(Object obj : objects) {
if(didOne) out.append(delimiter);
else didOne = true;
out.append(String.valueOf(obj));
}
return out;
} | java | public static <A extends Appendable> A join(Iterable<?> objects, String delimiter, A out) throws IOException {
boolean didOne = false;
for(Object obj : objects) {
if(didOne) out.append(delimiter);
else didOne = true;
out.append(String.valueOf(obj));
}
return out;
} | [
"public",
"static",
"<",
"A",
"extends",
"Appendable",
">",
"A",
"join",
"(",
"Iterable",
"<",
"?",
">",
"objects",
",",
"String",
"delimiter",
",",
"A",
"out",
")",
"throws",
"IOException",
"{",
"boolean",
"didOne",
"=",
"false",
";",
"for",
"(",
"Obj... | Joins the string representation of objects on the provided delimiter.
@see #join(java.lang.Iterable, java.lang.String)
@see #join(java.lang.Object[], java.lang.String, java.lang.Appendable) | [
"Joins",
"the",
"string",
"representation",
"of",
"objects",
"on",
"the",
"provided",
"delimiter",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/StringUtility.java#L165-L173 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/util/StringUtility.java | StringUtility.compareToDDMMYYYY | public static int compareToDDMMYYYY(String date1, String date2) {
if(date1.length()!=8 || date2.length()!=8) return 0;
return compareToDDMMYYYY0(date1)-compareToDDMMYYYY0(date2);
} | java | public static int compareToDDMMYYYY(String date1, String date2) {
if(date1.length()!=8 || date2.length()!=8) return 0;
return compareToDDMMYYYY0(date1)-compareToDDMMYYYY0(date2);
} | [
"public",
"static",
"int",
"compareToDDMMYYYY",
"(",
"String",
"date1",
",",
"String",
"date2",
")",
"{",
"if",
"(",
"date1",
".",
"length",
"(",
")",
"!=",
"8",
"||",
"date2",
".",
"length",
"(",
")",
"!=",
"8",
")",
"return",
"0",
";",
"return",
... | Compare one date to another, must be in the DDMMYYYY format.
@return <0 if the first date is before the second<br>
0 if the dates are the same or the format is invalid<br>
>0 if the first date is after the second | [
"Compare",
"one",
"date",
"to",
"another",
"must",
"be",
"in",
"the",
"DDMMYYYY",
"format",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/StringUtility.java#L230-L233 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/util/StringUtility.java | StringUtility.indexOf | public static int indexOf(String S, char[] chars, int start) {
int Slen=S.length();
int clen=chars.length;
for(int c=start;c<Slen;c++) {
char ch=S.charAt(c);
for(int d=0;d<clen;d++) if(ch==chars[d]) return c;
}
return -1;
} | java | public static int indexOf(String S, char[] chars, int start) {
int Slen=S.length();
int clen=chars.length;
for(int c=start;c<Slen;c++) {
char ch=S.charAt(c);
for(int d=0;d<clen;d++) if(ch==chars[d]) return c;
}
return -1;
} | [
"public",
"static",
"int",
"indexOf",
"(",
"String",
"S",
",",
"char",
"[",
"]",
"chars",
",",
"int",
"start",
")",
"{",
"int",
"Slen",
"=",
"S",
".",
"length",
"(",
")",
";",
"int",
"clen",
"=",
"chars",
".",
"length",
";",
"for",
"(",
"int",
... | Finds the first occurrence of any of the supplied characters starting at the specified index.
@param S the <code>String</code> to search
@param chars the characters to look for
@param start the starting index.
@return the index of the first occurrence of <code>-1</code> if none found | [
"Finds",
"the",
"first",
"occurrence",
"of",
"any",
"of",
"the",
"supplied",
"characters",
"starting",
"at",
"the",
"specified",
"index",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/StringUtility.java#L633-L641 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/util/StringUtility.java | StringUtility.replace | public static String replace(final String string, final String find, final String replacement) {
int pos = string.indexOf(find);
//System.out.println(string+": "+find+" at "+pos);
if (pos == -1) return string;
StringBuilder SB = new StringBuilder();
int lastpos = 0;
final int findLen = find.length();
do {
SB.append(string, lastpos, pos).append(replacement);
lastpos = pos + findLen;
pos = string.indexOf(find, lastpos);
} while (pos != -1);
int len = string.length();
if(lastpos<len) SB.append(string, lastpos, len);
return SB.toString();
} | java | public static String replace(final String string, final String find, final String replacement) {
int pos = string.indexOf(find);
//System.out.println(string+": "+find+" at "+pos);
if (pos == -1) return string;
StringBuilder SB = new StringBuilder();
int lastpos = 0;
final int findLen = find.length();
do {
SB.append(string, lastpos, pos).append(replacement);
lastpos = pos + findLen;
pos = string.indexOf(find, lastpos);
} while (pos != -1);
int len = string.length();
if(lastpos<len) SB.append(string, lastpos, len);
return SB.toString();
} | [
"public",
"static",
"String",
"replace",
"(",
"final",
"String",
"string",
",",
"final",
"String",
"find",
",",
"final",
"String",
"replacement",
")",
"{",
"int",
"pos",
"=",
"string",
".",
"indexOf",
"(",
"find",
")",
";",
"//System.out.println(string+\": \"+... | Replaces all occurrences of a String with a String
Please consider the variant with the Appendable for higher performance. | [
"Replaces",
"all",
"occurrences",
"of",
"a",
"String",
"with",
"a",
"String",
"Please",
"consider",
"the",
"variant",
"with",
"the",
"Appendable",
"for",
"higher",
"performance",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/StringUtility.java#L714-L729 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/util/StringUtility.java | StringUtility.replace | public static void replace(final StringBuffer sb, final String find, final String replacement) {
int pos = 0;
while(pos<sb.length()) {
pos = sb.indexOf(find, pos);
if(pos==-1) break;
sb.replace(pos, pos+find.length(), replacement);
pos += replacement.length();
}
} | java | public static void replace(final StringBuffer sb, final String find, final String replacement) {
int pos = 0;
while(pos<sb.length()) {
pos = sb.indexOf(find, pos);
if(pos==-1) break;
sb.replace(pos, pos+find.length(), replacement);
pos += replacement.length();
}
} | [
"public",
"static",
"void",
"replace",
"(",
"final",
"StringBuffer",
"sb",
",",
"final",
"String",
"find",
",",
"final",
"String",
"replacement",
")",
"{",
"int",
"pos",
"=",
"0",
";",
"while",
"(",
"pos",
"<",
"sb",
".",
"length",
"(",
")",
")",
"{"... | Replaces all occurrences of a String with a String. | [
"Replaces",
"all",
"occurrences",
"of",
"a",
"String",
"with",
"a",
"String",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/StringUtility.java#L756-L764 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/util/StringUtility.java | StringUtility.splitLines | public static List<String> splitLines(String S) {
List<String> V=new ArrayList<>();
int start=0;
int pos;
while((pos=S.indexOf('\n', start))!=-1) {
String line;
if(pos>start && S.charAt(pos-1)=='\r') line = S.substring(start, pos-1);
else line = S.substring(start, pos);
V.add(line);
start=pos+1;
}
int slen = S.length();
if(start<slen) {
// Ignore any trailing '\r'
if(S.charAt(slen-1)=='\r') slen--;
String line = S.substring(start, slen);
V.add(line);
}
return V;
} | java | public static List<String> splitLines(String S) {
List<String> V=new ArrayList<>();
int start=0;
int pos;
while((pos=S.indexOf('\n', start))!=-1) {
String line;
if(pos>start && S.charAt(pos-1)=='\r') line = S.substring(start, pos-1);
else line = S.substring(start, pos);
V.add(line);
start=pos+1;
}
int slen = S.length();
if(start<slen) {
// Ignore any trailing '\r'
if(S.charAt(slen-1)=='\r') slen--;
String line = S.substring(start, slen);
V.add(line);
}
return V;
} | [
"public",
"static",
"List",
"<",
"String",
">",
"splitLines",
"(",
"String",
"S",
")",
"{",
"List",
"<",
"String",
">",
"V",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"int",
"start",
"=",
"0",
";",
"int",
"pos",
";",
"while",
"(",
"(",
"pos",... | Splits a String into lines on any '\n' characters. Also removes any ending '\r' characters if present | [
"Splits",
"a",
"String",
"into",
"lines",
"on",
"any",
"\\",
"n",
"characters",
".",
"Also",
"removes",
"any",
"ending",
"\\",
"r",
"characters",
"if",
"present"
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/StringUtility.java#L782-L801 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/util/StringUtility.java | StringUtility.splitStringCommaSpace | public static List<String> splitStringCommaSpace(String line) {
List<String> words=new ArrayList<>();
int len=line.length();
int pos=0;
while(pos<len) {
// Skip past blank space
char ch;
while(pos<len && ((ch=line.charAt(pos))<=' ' || ch==',')) pos++;
int start=pos;
// Skip to the next blank space
while(pos<len && (ch=line.charAt(pos))>' ' && ch!=',') pos++;
if(pos>start) words.add(line.substring(start,pos));
}
return words;
} | java | public static List<String> splitStringCommaSpace(String line) {
List<String> words=new ArrayList<>();
int len=line.length();
int pos=0;
while(pos<len) {
// Skip past blank space
char ch;
while(pos<len && ((ch=line.charAt(pos))<=' ' || ch==',')) pos++;
int start=pos;
// Skip to the next blank space
while(pos<len && (ch=line.charAt(pos))>' ' && ch!=',') pos++;
if(pos>start) words.add(line.substring(start,pos));
}
return words;
} | [
"public",
"static",
"List",
"<",
"String",
">",
"splitStringCommaSpace",
"(",
"String",
"line",
")",
"{",
"List",
"<",
"String",
">",
"words",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"int",
"len",
"=",
"line",
".",
"length",
"(",
")",
";",
"int... | Splits a string into multiple words on either whitespace or commas
@return java.lang.String[]
@param line java.lang.String | [
"Splits",
"a",
"string",
"into",
"multiple",
"words",
"on",
"either",
"whitespace",
"or",
"commas"
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/StringUtility.java#L987-L1001 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/util/StringUtility.java | StringUtility.convertToHex | public static void convertToHex(int value, Appendable out) throws IOException {
out.append(getHexChar(value >>> 28));
out.append(getHexChar(value >>> 24));
out.append(getHexChar(value >>> 20));
out.append(getHexChar(value >>> 16));
out.append(getHexChar(value >>> 12));
out.append(getHexChar(value >>> 8));
out.append(getHexChar(value >>> 4));
out.append(getHexChar(value));
} | java | public static void convertToHex(int value, Appendable out) throws IOException {
out.append(getHexChar(value >>> 28));
out.append(getHexChar(value >>> 24));
out.append(getHexChar(value >>> 20));
out.append(getHexChar(value >>> 16));
out.append(getHexChar(value >>> 12));
out.append(getHexChar(value >>> 8));
out.append(getHexChar(value >>> 4));
out.append(getHexChar(value));
} | [
"public",
"static",
"void",
"convertToHex",
"(",
"int",
"value",
",",
"Appendable",
"out",
")",
"throws",
"IOException",
"{",
"out",
".",
"append",
"(",
"getHexChar",
"(",
"value",
">>>",
"28",
")",
")",
";",
"out",
".",
"append",
"(",
"getHexChar",
"(",... | Converts an int to a full 8-character hex code. | [
"Converts",
"an",
"int",
"to",
"a",
"full",
"8",
"-",
"character",
"hex",
"code",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/StringUtility.java#L1168-L1177 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/util/StringUtility.java | StringUtility.compareToIgnoreCaseCarefulEquals | public static int compareToIgnoreCaseCarefulEquals(String S1, String S2) {
int diff=S1.compareToIgnoreCase(S2);
if(diff==0) diff=S1.compareTo(S2);
return diff;
} | java | public static int compareToIgnoreCaseCarefulEquals(String S1, String S2) {
int diff=S1.compareToIgnoreCase(S2);
if(diff==0) diff=S1.compareTo(S2);
return diff;
} | [
"public",
"static",
"int",
"compareToIgnoreCaseCarefulEquals",
"(",
"String",
"S1",
",",
"String",
"S2",
")",
"{",
"int",
"diff",
"=",
"S1",
".",
"compareToIgnoreCase",
"(",
"S2",
")",
";",
"if",
"(",
"diff",
"==",
"0",
")",
"diff",
"=",
"S1",
".",
"co... | Compares two strings in a case insensitive manner. However, if they are considered equals in the
case-insensitive manner, the case sensitive comparison is done. | [
"Compares",
"two",
"strings",
"in",
"a",
"case",
"insensitive",
"manner",
".",
"However",
"if",
"they",
"are",
"considered",
"equals",
"in",
"the",
"case",
"-",
"insensitive",
"manner",
"the",
"case",
"sensitive",
"comparison",
"is",
"done",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/StringUtility.java#L1345-L1349 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/util/StringUtility.java | StringUtility.indexOf | public static int indexOf(String source, String target, int fromIndex, int toIndex) {
if(fromIndex>toIndex) throw new IllegalArgumentException("fromIndex>toIndex: fromIndex="+fromIndex+", toIndex="+toIndex);
int sourceCount = source.length();
// This line makes it different than regular String indexOf method.
if(toIndex<sourceCount) sourceCount = toIndex;
int targetCount = target.length();
if (fromIndex >= sourceCount) {
return (targetCount == 0 ? sourceCount : -1);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}
char first = target.charAt(0);
int max = sourceCount - targetCount;
for (int i = fromIndex; i <= max; i++) {
/* Look for first character. */
if (source.charAt(i) != first) {
while (++i <= max && source.charAt(i) != first) {
// Intentionally empty
}
}
/* Found first character, now look at the rest of v2 */
if (i <= max) {
int j = i + 1;
int end = j + targetCount - 1;
for (int k = 1; j < end && source.charAt(j) == target.charAt(k); j++, k++) {
// Intentionally empty
}
if (j == end) {
/* Found whole string. */
return i;
}
}
}
return -1;
} | java | public static int indexOf(String source, String target, int fromIndex, int toIndex) {
if(fromIndex>toIndex) throw new IllegalArgumentException("fromIndex>toIndex: fromIndex="+fromIndex+", toIndex="+toIndex);
int sourceCount = source.length();
// This line makes it different than regular String indexOf method.
if(toIndex<sourceCount) sourceCount = toIndex;
int targetCount = target.length();
if (fromIndex >= sourceCount) {
return (targetCount == 0 ? sourceCount : -1);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}
char first = target.charAt(0);
int max = sourceCount - targetCount;
for (int i = fromIndex; i <= max; i++) {
/* Look for first character. */
if (source.charAt(i) != first) {
while (++i <= max && source.charAt(i) != first) {
// Intentionally empty
}
}
/* Found first character, now look at the rest of v2 */
if (i <= max) {
int j = i + 1;
int end = j + targetCount - 1;
for (int k = 1; j < end && source.charAt(j) == target.charAt(k); j++, k++) {
// Intentionally empty
}
if (j == end) {
/* Found whole string. */
return i;
}
}
}
return -1;
} | [
"public",
"static",
"int",
"indexOf",
"(",
"String",
"source",
",",
"String",
"target",
",",
"int",
"fromIndex",
",",
"int",
"toIndex",
")",
"{",
"if",
"(",
"fromIndex",
">",
"toIndex",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"fromIndex>toIndex... | Finds the next of a substring like regular String.indexOf, but stops at a certain maximum index.
Like substring, will look up to the character one before toIndex. | [
"Finds",
"the",
"next",
"of",
"a",
"substring",
"like",
"regular",
"String",
".",
"indexOf",
"but",
"stops",
"at",
"a",
"certain",
"maximum",
"index",
".",
"Like",
"substring",
"will",
"look",
"up",
"to",
"the",
"character",
"one",
"before",
"toIndex",
"."... | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/StringUtility.java#L1365-L1411 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/util/StringUtility.java | StringUtility.nullIfEmpty | public static String nullIfEmpty(String value) {
return value==null || value.isEmpty() ? null : value;
} | java | public static String nullIfEmpty(String value) {
return value==null || value.isEmpty() ? null : value;
} | [
"public",
"static",
"String",
"nullIfEmpty",
"(",
"String",
"value",
")",
"{",
"return",
"value",
"==",
"null",
"||",
"value",
".",
"isEmpty",
"(",
")",
"?",
"null",
":",
"value",
";",
"}"
] | Returns null if the string is null or empty. | [
"Returns",
"null",
"if",
"the",
"string",
"is",
"null",
"or",
"empty",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/StringUtility.java#L1428-L1430 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/util/UnionMethodSet.java | UnionMethodSet.isEmpty | @Override
public boolean isEmpty() {
for(List<? extends Method<? extends E>> methods : methodsByClass.values()) {
for(Method<? extends E> method : methods) {
E singleton = method.getSingleton(target);
if(singleton!=null) return false;
Set<? extends E> set = method.getSet(target);
if(set!=null && !set.isEmpty()) return false;
}
}
return true;
} | java | @Override
public boolean isEmpty() {
for(List<? extends Method<? extends E>> methods : methodsByClass.values()) {
for(Method<? extends E> method : methods) {
E singleton = method.getSingleton(target);
if(singleton!=null) return false;
Set<? extends E> set = method.getSet(target);
if(set!=null && !set.isEmpty()) return false;
}
}
return true;
} | [
"@",
"Override",
"public",
"boolean",
"isEmpty",
"(",
")",
"{",
"for",
"(",
"List",
"<",
"?",
"extends",
"Method",
"<",
"?",
"extends",
"E",
">",
">",
"methods",
":",
"methodsByClass",
".",
"values",
"(",
")",
")",
"{",
"for",
"(",
"Method",
"<",
"... | Checks if this set is empty. This can be an expensive method since it can potentially call all methods. | [
"Checks",
"if",
"this",
"set",
"is",
"empty",
".",
"This",
"can",
"be",
"an",
"expensive",
"method",
"since",
"it",
"can",
"potentially",
"call",
"all",
"methods",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/UnionMethodSet.java#L204-L215 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/util/UnionClassSet.java | UnionClassSet.addAll | @Override
@SuppressWarnings("unchecked")
public boolean addAll(Collection<? extends E> c) {
if(c.isEmpty()) return false;
if(c instanceof Set) return addAll((Set<? extends E>)c);
else throw new UnsupportedOperationException("May only add sets");
} | java | @Override
@SuppressWarnings("unchecked")
public boolean addAll(Collection<? extends E> c) {
if(c.isEmpty()) return false;
if(c instanceof Set) return addAll((Set<? extends E>)c);
else throw new UnsupportedOperationException("May only add sets");
} | [
"@",
"Override",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"boolean",
"addAll",
"(",
"Collection",
"<",
"?",
"extends",
"E",
">",
"c",
")",
"{",
"if",
"(",
"c",
".",
"isEmpty",
"(",
")",
")",
"return",
"false",
";",
"if",
"(",
"c"... | Must be a set.
@see #addAll(java.util.Set) | [
"Must",
"be",
"a",
"set",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/UnionClassSet.java#L134-L140 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/TempFileList.java | TempFileList.createTempFile | public TempFile createTempFile() throws IOException {
TempFile tempFile = new TempFile(prefix, suffix, directory);
synchronized(tempFiles) {
tempFiles.add(new WeakReference<>(tempFile));
}
return tempFile;
} | java | public TempFile createTempFile() throws IOException {
TempFile tempFile = new TempFile(prefix, suffix, directory);
synchronized(tempFiles) {
tempFiles.add(new WeakReference<>(tempFile));
}
return tempFile;
} | [
"public",
"TempFile",
"createTempFile",
"(",
")",
"throws",
"IOException",
"{",
"TempFile",
"tempFile",
"=",
"new",
"TempFile",
"(",
"prefix",
",",
"suffix",
",",
"directory",
")",
";",
"synchronized",
"(",
"tempFiles",
")",
"{",
"tempFiles",
".",
"add",
"("... | Creates a new temp file while adding it to the list of files that will
be explicitly deleted when this list is deleted. | [
"Creates",
"a",
"new",
"temp",
"file",
"while",
"adding",
"it",
"to",
"the",
"list",
"of",
"files",
"that",
"will",
"be",
"explicitly",
"deleted",
"when",
"this",
"list",
"is",
"deleted",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/TempFileList.java#L92-L98 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/TempFileList.java | TempFileList.delete | public void delete() throws IOException {
synchronized(tempFiles) {
for(WeakReference<TempFile> tempFileRef : tempFiles) {
TempFile tempFile = tempFileRef.get();
if(tempFile!=null) tempFile.delete();
}
tempFiles.clear();
}
} | java | public void delete() throws IOException {
synchronized(tempFiles) {
for(WeakReference<TempFile> tempFileRef : tempFiles) {
TempFile tempFile = tempFileRef.get();
if(tempFile!=null) tempFile.delete();
}
tempFiles.clear();
}
} | [
"public",
"void",
"delete",
"(",
")",
"throws",
"IOException",
"{",
"synchronized",
"(",
"tempFiles",
")",
"{",
"for",
"(",
"WeakReference",
"<",
"TempFile",
">",
"tempFileRef",
":",
"tempFiles",
")",
"{",
"TempFile",
"tempFile",
"=",
"tempFileRef",
".",
"ge... | Deletes all of the underlying temp files immediately.
This list may still be used for additional temp files.
@see TempFile#delete() | [
"Deletes",
"all",
"of",
"the",
"underlying",
"temp",
"files",
"immediately",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/TempFileList.java#L107-L115 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebSiteRequest.java | WebSiteRequest.getFileUploadDirectory | private static File getFileUploadDirectory(ServletContext servletContext) throws FileNotFoundException {
File uploadDir = new File(
(File)servletContext.getAttribute(ServletContext.TEMPDIR),
"uploads"
);
if(
!uploadDir.exists()
&& !uploadDir.mkdirs()
// Check exists again, another thread may have created it and interfered with mkdirs
&& !uploadDir.exists()
) {
throw new FileNotFoundException(uploadDir.getPath());
}
return uploadDir;
} | java | private static File getFileUploadDirectory(ServletContext servletContext) throws FileNotFoundException {
File uploadDir = new File(
(File)servletContext.getAttribute(ServletContext.TEMPDIR),
"uploads"
);
if(
!uploadDir.exists()
&& !uploadDir.mkdirs()
// Check exists again, another thread may have created it and interfered with mkdirs
&& !uploadDir.exists()
) {
throw new FileNotFoundException(uploadDir.getPath());
}
return uploadDir;
} | [
"private",
"static",
"File",
"getFileUploadDirectory",
"(",
"ServletContext",
"servletContext",
")",
"throws",
"FileNotFoundException",
"{",
"File",
"uploadDir",
"=",
"new",
"File",
"(",
"(",
"File",
")",
"servletContext",
".",
"getAttribute",
"(",
"ServletContext",
... | Gets the upload directory. | [
"Gets",
"the",
"upload",
"directory",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebSiteRequest.java#L66-L80 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebSiteRequest.java | WebSiteRequest.appendParams | protected static boolean appendParams(StringBuilder SB, Object optParam, List<String> finishedParams, boolean alreadyAppended) {
if (optParam != null) {
if (optParam instanceof String) {
List<String> nameValuePairs=StringUtility.splitString((String)optParam, '&');
int len=nameValuePairs.size();
for(int i=0;i<len;i++) {
SB.append(alreadyAppended?'&':'?');
String S=nameValuePairs.get(i);
int pos=S.indexOf('=');
if(pos==-1) {
SB.append(S);
alreadyAppended=true;
} else {
String name=S.substring(0, pos);
if(!finishedParams.contains(name)) {
SB.append(S);
finishedParams.add(name);
alreadyAppended=true;
}
}
}
} else if (optParam instanceof String[]) {
String[] SA = (String[]) optParam;
int len = SA.length;
for (int c = 0; c < len; c += 2) {
String name=SA[c];
if(!finishedParams.contains(name)) {
SB.append(alreadyAppended?'&':'?').append(name).append('=').append(SA[c + 1]);
finishedParams.add(name);
alreadyAppended=true;
}
}
} else throw new IllegalArgumentException("Unsupported type for optParam: " + optParam.getClass().getName());
}
return alreadyAppended;
} | java | protected static boolean appendParams(StringBuilder SB, Object optParam, List<String> finishedParams, boolean alreadyAppended) {
if (optParam != null) {
if (optParam instanceof String) {
List<String> nameValuePairs=StringUtility.splitString((String)optParam, '&');
int len=nameValuePairs.size();
for(int i=0;i<len;i++) {
SB.append(alreadyAppended?'&':'?');
String S=nameValuePairs.get(i);
int pos=S.indexOf('=');
if(pos==-1) {
SB.append(S);
alreadyAppended=true;
} else {
String name=S.substring(0, pos);
if(!finishedParams.contains(name)) {
SB.append(S);
finishedParams.add(name);
alreadyAppended=true;
}
}
}
} else if (optParam instanceof String[]) {
String[] SA = (String[]) optParam;
int len = SA.length;
for (int c = 0; c < len; c += 2) {
String name=SA[c];
if(!finishedParams.contains(name)) {
SB.append(alreadyAppended?'&':'?').append(name).append('=').append(SA[c + 1]);
finishedParams.add(name);
alreadyAppended=true;
}
}
} else throw new IllegalArgumentException("Unsupported type for optParam: " + optParam.getClass().getName());
}
return alreadyAppended;
} | [
"protected",
"static",
"boolean",
"appendParams",
"(",
"StringBuilder",
"SB",
",",
"Object",
"optParam",
",",
"List",
"<",
"String",
">",
"finishedParams",
",",
"boolean",
"alreadyAppended",
")",
"{",
"if",
"(",
"optParam",
"!=",
"null",
")",
"{",
"if",
"(",... | Appends the parameters to a URL.
Parameters should already be URL encoded but not XML encoded. | [
"Appends",
"the",
"parameters",
"to",
"a",
"URL",
".",
"Parameters",
"should",
"already",
"be",
"URL",
"encoded",
"but",
"not",
"XML",
"encoded",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebSiteRequest.java#L310-L345 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebSiteRequest.java | WebSiteRequest.getURL | public String getURL(String classAndParams) throws IOException, SQLException {
String className, params;
int pos=classAndParams.indexOf('?');
if(pos==-1) {
className=classAndParams;
params=null;
} else {
className=classAndParams.substring(0, pos);
params=classAndParams.substring(pos+1);
}
return getURL(className, params);
} | java | public String getURL(String classAndParams) throws IOException, SQLException {
String className, params;
int pos=classAndParams.indexOf('?');
if(pos==-1) {
className=classAndParams;
params=null;
} else {
className=classAndParams.substring(0, pos);
params=classAndParams.substring(pos+1);
}
return getURL(className, params);
} | [
"public",
"String",
"getURL",
"(",
"String",
"classAndParams",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"String",
"className",
",",
"params",
";",
"int",
"pos",
"=",
"classAndParams",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"pos"... | Gets a relative URL from a String containing a classname and optional parameters.
Parameters should already be URL encoded but not XML encoded. | [
"Gets",
"a",
"relative",
"URL",
"from",
"a",
"String",
"containing",
"a",
"classname",
"and",
"optional",
"parameters",
".",
"Parameters",
"should",
"already",
"be",
"URL",
"encoded",
"but",
"not",
"XML",
"encoded",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebSiteRequest.java#L351-L362 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebSiteRequest.java | WebSiteRequest.getURL | public String getURL(String classname, String params) throws IOException, SQLException {
try {
Class<? extends WebPage> clazz=Class.forName(classname).asSubclass(WebPage.class);
return getURL(clazz, params);
} catch(ClassNotFoundException err) {
throw new IOException("Unable to load class: "+classname, err);
}
} | java | public String getURL(String classname, String params) throws IOException, SQLException {
try {
Class<? extends WebPage> clazz=Class.forName(classname).asSubclass(WebPage.class);
return getURL(clazz, params);
} catch(ClassNotFoundException err) {
throw new IOException("Unable to load class: "+classname, err);
}
} | [
"public",
"String",
"getURL",
"(",
"String",
"classname",
",",
"String",
"params",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"try",
"{",
"Class",
"<",
"?",
"extends",
"WebPage",
">",
"clazz",
"=",
"Class",
".",
"forName",
"(",
"classname",
")... | Gets a relative URL given its classname and optional parameters.
Parameters should already be URL encoded but not XML encoded. | [
"Gets",
"a",
"relative",
"URL",
"given",
"its",
"classname",
"and",
"optional",
"parameters",
".",
"Parameters",
"should",
"already",
"be",
"URL",
"encoded",
"but",
"not",
"XML",
"encoded",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebSiteRequest.java#L368-L375 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebSiteRequest.java | WebSiteRequest.getURL | public String getURL(String url, Object optParam, boolean keepSettings) throws IOException {
StringBuilder SB=new StringBuilder();
SB.append(url);
List<String> finishedParams=new SortedArrayList<>();
boolean alreadyAppended=appendParams(SB, optParam, finishedParams, false);
if(keepSettings) appendSettings(finishedParams, alreadyAppended, SB);
return SB.toString();
} | java | public String getURL(String url, Object optParam, boolean keepSettings) throws IOException {
StringBuilder SB=new StringBuilder();
SB.append(url);
List<String> finishedParams=new SortedArrayList<>();
boolean alreadyAppended=appendParams(SB, optParam, finishedParams, false);
if(keepSettings) appendSettings(finishedParams, alreadyAppended, SB);
return SB.toString();
} | [
"public",
"String",
"getURL",
"(",
"String",
"url",
",",
"Object",
"optParam",
",",
"boolean",
"keepSettings",
")",
"throws",
"IOException",
"{",
"StringBuilder",
"SB",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"SB",
".",
"append",
"(",
"url",
")",
";",
... | Gets the context-relative URL, optionally with the settings embedded.
Parameters should already be URL encoded but not XML encoded.
@param url the context-relative URL | [
"Gets",
"the",
"context",
"-",
"relative",
"URL",
"optionally",
"with",
"the",
"settings",
"embedded",
".",
"Parameters",
"should",
"already",
"be",
"URL",
"encoded",
"but",
"not",
"XML",
"encoded",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebSiteRequest.java#L383-L390 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebSiteRequest.java | WebSiteRequest.getURL | public String getURL(WebPage page) throws IOException, SQLException {
return getURL(page, (Object)null);
} | java | public String getURL(WebPage page) throws IOException, SQLException {
return getURL(page, (Object)null);
} | [
"public",
"String",
"getURL",
"(",
"WebPage",
"page",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"return",
"getURL",
"(",
"page",
",",
"(",
"Object",
")",
"null",
")",
";",
"}"
] | Gets the context-relative URL to a web page. | [
"Gets",
"the",
"context",
"-",
"relative",
"URL",
"to",
"a",
"web",
"page",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebSiteRequest.java#L424-L426 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebSiteRequest.java | WebSiteRequest.getURL | public String getURL(String url, Object optParam) throws IOException {
return getURL(url, optParam, true);
} | java | public String getURL(String url, Object optParam) throws IOException {
return getURL(url, optParam, true);
} | [
"public",
"String",
"getURL",
"(",
"String",
"url",
",",
"Object",
"optParam",
")",
"throws",
"IOException",
"{",
"return",
"getURL",
"(",
"url",
",",
"optParam",
",",
"true",
")",
";",
"}"
] | Gets the URL String with the given parameters embedded, keeping the current settings.
@param url the context-relative URL, with a beginning slash
@param optParam any number of additional parameters. This parameter can accept several types of
objects. The following is a list of supported objects and a brief description of its
behavior.
Parameters should already be URL encoded but not yet XML encoded.
<ul>
<li>
<code>String</code> - appended to the end of the parameters, assumed to be in the
format name=value
</li>
<li>
<code>String[]</code> - name and value pairs, the first element of each pair is the
name, the second is the value
</li>
</ul>
@exception IllegalArgumentException if <code>optParam</code> is not a supported object | [
"Gets",
"the",
"URL",
"String",
"with",
"the",
"given",
"parameters",
"embedded",
"keeping",
"the",
"current",
"settings",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebSiteRequest.java#L477-L479 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebSiteRequest.java | WebSiteRequest.isLynx | public boolean isLynx() {
if(!isLynxDone) {
String agent = req.getHeader("user-agent");
isLynx=agent != null && agent.toLowerCase(Locale.ROOT).contains("lynx");
isLynxDone=true;
}
return isLynx;
} | java | public boolean isLynx() {
if(!isLynxDone) {
String agent = req.getHeader("user-agent");
isLynx=agent != null && agent.toLowerCase(Locale.ROOT).contains("lynx");
isLynxDone=true;
}
return isLynx;
} | [
"public",
"boolean",
"isLynx",
"(",
")",
"{",
"if",
"(",
"!",
"isLynxDone",
")",
"{",
"String",
"agent",
"=",
"req",
".",
"getHeader",
"(",
"\"user-agent\"",
")",
";",
"isLynx",
"=",
"agent",
"!=",
"null",
"&&",
"agent",
".",
"toLowerCase",
"(",
"Local... | Determines if the request is for a Lynx browser | [
"Determines",
"if",
"the",
"request",
"is",
"for",
"a",
"Lynx",
"browser"
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebSiteRequest.java#L484-L491 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebSiteRequest.java | WebSiteRequest.isBlackBerry | public boolean isBlackBerry() {
if(!isBlackBerryDone) {
String agent = req.getHeader("user-agent");
isBlackBerry=agent != null && agent.startsWith("BlackBerry");
isBlackBerryDone=true;
}
return isBlackBerry;
} | java | public boolean isBlackBerry() {
if(!isBlackBerryDone) {
String agent = req.getHeader("user-agent");
isBlackBerry=agent != null && agent.startsWith("BlackBerry");
isBlackBerryDone=true;
}
return isBlackBerry;
} | [
"public",
"boolean",
"isBlackBerry",
"(",
")",
"{",
"if",
"(",
"!",
"isBlackBerryDone",
")",
"{",
"String",
"agent",
"=",
"req",
".",
"getHeader",
"(",
"\"user-agent\"",
")",
";",
"isBlackBerry",
"=",
"agent",
"!=",
"null",
"&&",
"agent",
".",
"startsWith"... | Determines if the request is for a BlackBerry browser | [
"Determines",
"if",
"the",
"request",
"is",
"for",
"a",
"BlackBerry",
"browser"
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebSiteRequest.java#L496-L503 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebSiteRequest.java | WebSiteRequest.isLinux | public boolean isLinux() {
if(!isLinuxDone) {
String agent = req.getHeader("user-agent");
isLinux=agent == null || agent.toLowerCase(Locale.ROOT).contains("linux");
isLinuxDone=true;
}
return isLinux;
} | java | public boolean isLinux() {
if(!isLinuxDone) {
String agent = req.getHeader("user-agent");
isLinux=agent == null || agent.toLowerCase(Locale.ROOT).contains("linux");
isLinuxDone=true;
}
return isLinux;
} | [
"public",
"boolean",
"isLinux",
"(",
")",
"{",
"if",
"(",
"!",
"isLinuxDone",
")",
"{",
"String",
"agent",
"=",
"req",
".",
"getHeader",
"(",
"\"user-agent\"",
")",
";",
"isLinux",
"=",
"agent",
"==",
"null",
"||",
"agent",
".",
"toLowerCase",
"(",
"Lo... | Determines if the request is for a Linux browser | [
"Determines",
"if",
"the",
"request",
"is",
"for",
"a",
"Linux",
"browser"
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebSiteRequest.java#L508-L515 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/net/HttpParametersUtils.java | HttpParametersUtils.addParams | public static String addParams(String href, HttpParameters params, String encoding) throws UnsupportedEncodingException {
if(params!=null) {
StringBuilder sb = new StringBuilder(href);
// First find any anchor and if has parameters
int anchorStart = href.lastIndexOf('#');
String anchor;
boolean hasQuestion;
if(anchorStart == -1) {
anchor = null;
hasQuestion = href.lastIndexOf('?') != -1;
} else {
anchor = href.substring(anchorStart);
sb.setLength(anchorStart);
hasQuestion = href.lastIndexOf('?', anchorStart-1) != -1;
}
for(Map.Entry<String,List<String>> entry : params.getParameterMap().entrySet()) {
String encodedName = URLEncoder.encode(entry.getKey(), encoding);
for(String value : entry.getValue()) {
if(hasQuestion) sb.append('&');
else {
sb.append('?');
hasQuestion = true;
}
sb.append(encodedName);
assert value!=null : "null values no longer supported to be consistent with servlet environment";
sb.append('=').append(URLEncoder.encode(value, encoding));
}
}
if(anchor!=null) sb.append(anchor);
href = sb.toString();
}
return href;
} | java | public static String addParams(String href, HttpParameters params, String encoding) throws UnsupportedEncodingException {
if(params!=null) {
StringBuilder sb = new StringBuilder(href);
// First find any anchor and if has parameters
int anchorStart = href.lastIndexOf('#');
String anchor;
boolean hasQuestion;
if(anchorStart == -1) {
anchor = null;
hasQuestion = href.lastIndexOf('?') != -1;
} else {
anchor = href.substring(anchorStart);
sb.setLength(anchorStart);
hasQuestion = href.lastIndexOf('?', anchorStart-1) != -1;
}
for(Map.Entry<String,List<String>> entry : params.getParameterMap().entrySet()) {
String encodedName = URLEncoder.encode(entry.getKey(), encoding);
for(String value : entry.getValue()) {
if(hasQuestion) sb.append('&');
else {
sb.append('?');
hasQuestion = true;
}
sb.append(encodedName);
assert value!=null : "null values no longer supported to be consistent with servlet environment";
sb.append('=').append(URLEncoder.encode(value, encoding));
}
}
if(anchor!=null) sb.append(anchor);
href = sb.toString();
}
return href;
} | [
"public",
"static",
"String",
"addParams",
"(",
"String",
"href",
",",
"HttpParameters",
"params",
",",
"String",
"encoding",
")",
"throws",
"UnsupportedEncodingException",
"{",
"if",
"(",
"params",
"!=",
"null",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"S... | Adds all of the parameters to a URL. | [
"Adds",
"all",
"of",
"the",
"parameters",
"to",
"a",
"URL",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/net/HttpParametersUtils.java#L40-L72 | train |
inversoft/jackson5 | src/main/java/com/inversoft/json/ToString.java | ToString.toJSONString | public static String toJSONString(Object o) {
try {
return objectMapper.writer().without(SerializationFeature.INDENT_OUTPUT).writeValueAsString(o);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
} | java | public static String toJSONString(Object o) {
try {
return objectMapper.writer().without(SerializationFeature.INDENT_OUTPUT).writeValueAsString(o);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
} | [
"public",
"static",
"String",
"toJSONString",
"(",
"Object",
"o",
")",
"{",
"try",
"{",
"return",
"objectMapper",
".",
"writer",
"(",
")",
".",
"without",
"(",
"SerializationFeature",
".",
"INDENT_OUTPUT",
")",
".",
"writeValueAsString",
"(",
"o",
")",
";",
... | A not-pretty printed JSON string. Returns a portable JSON string.
@param o the object to serialize
@return a string representation of the object. | [
"A",
"not",
"-",
"pretty",
"printed",
"JSON",
"string",
".",
"Returns",
"a",
"portable",
"JSON",
"string",
"."
] | 65de3c17408ca03a2e28c1062ef6bb139f36f5a7 | https://github.com/inversoft/jackson5/blob/65de3c17408ca03a2e28c1062ef6bb139f36f5a7/src/main/java/com/inversoft/json/ToString.java#L53-L59 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/WebPageLayout.java | WebPageLayout.beginLightArea | final public void beginLightArea(WebSiteRequest req, HttpServletResponse resp, ChainWriter out) throws IOException {
beginLightArea(req, resp, out, null, false);
} | java | final public void beginLightArea(WebSiteRequest req, HttpServletResponse resp, ChainWriter out) throws IOException {
beginLightArea(req, resp, out, null, false);
} | [
"final",
"public",
"void",
"beginLightArea",
"(",
"WebSiteRequest",
"req",
",",
"HttpServletResponse",
"resp",
",",
"ChainWriter",
"out",
")",
"throws",
"IOException",
"{",
"beginLightArea",
"(",
"req",
",",
"resp",
",",
"out",
",",
"null",
",",
"false",
")",
... | Begins a lighter colored area of the site. | [
"Begins",
"a",
"lighter",
"colored",
"area",
"of",
"the",
"site",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/WebPageLayout.java#L263-L265 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/MultiFileOutputStream.java | MultiFileOutputStream.makeNewFile | private void makeNewFile() throws IOException {
String filename=prefix+(files.size()+1)+suffix;
File file=new File(parent, filename);
out=new FileOutputStream(file);
bytesOut=0;
files.add(file);
} | java | private void makeNewFile() throws IOException {
String filename=prefix+(files.size()+1)+suffix;
File file=new File(parent, filename);
out=new FileOutputStream(file);
bytesOut=0;
files.add(file);
} | [
"private",
"void",
"makeNewFile",
"(",
")",
"throws",
"IOException",
"{",
"String",
"filename",
"=",
"prefix",
"+",
"(",
"files",
".",
"size",
"(",
")",
"+",
"1",
")",
"+",
"suffix",
";",
"File",
"file",
"=",
"new",
"File",
"(",
"parent",
",",
"filen... | All accesses are already synchronized. | [
"All",
"accesses",
"are",
"already",
"synchronized",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/MultiFileOutputStream.java#L119-L125 | train |
aoindustries/ao-messaging-api | src/main/java/com/aoindustries/messaging/FileMessage.java | FileMessage.decode | public static FileMessage decode(String encodedMessage, File file) throws IOException {
return decode(
encodedMessage.isEmpty()
? ByteArray.EMPTY_BYTE_ARRAY
: new ByteArray(
Base64Coder.decode(
encodedMessage
)
),
file
);
} | java | public static FileMessage decode(String encodedMessage, File file) throws IOException {
return decode(
encodedMessage.isEmpty()
? ByteArray.EMPTY_BYTE_ARRAY
: new ByteArray(
Base64Coder.decode(
encodedMessage
)
),
file
);
} | [
"public",
"static",
"FileMessage",
"decode",
"(",
"String",
"encodedMessage",
",",
"File",
"file",
")",
"throws",
"IOException",
"{",
"return",
"decode",
"(",
"encodedMessage",
".",
"isEmpty",
"(",
")",
"?",
"ByteArray",
".",
"EMPTY_BYTE_ARRAY",
":",
"new",
"B... | base-64 decodes the message into the provided file.
@see #decode(com.aoindustries.messaging.ByteArray, java.io.File) | [
"base",
"-",
"64",
"decodes",
"the",
"message",
"into",
"the",
"provided",
"file",
"."
] | dbe4d3baefcc846f99b7eeab42646057e99729f0 | https://github.com/aoindustries/ao-messaging-api/blob/dbe4d3baefcc846f99b7eeab42646057e99729f0/src/main/java/com/aoindustries/messaging/FileMessage.java#L48-L59 | train |
aoindustries/ao-messaging-api | src/main/java/com/aoindustries/messaging/FileMessage.java | FileMessage.decode | @Deprecated
public static FileMessage decode(String encodedMessage) throws IOException {
return decode(
encodedMessage.isEmpty()
? ByteArray.EMPTY_BYTE_ARRAY
: new ByteArray(
Base64Coder.decode(
encodedMessage
)
)
);
} | java | @Deprecated
public static FileMessage decode(String encodedMessage) throws IOException {
return decode(
encodedMessage.isEmpty()
? ByteArray.EMPTY_BYTE_ARRAY
: new ByteArray(
Base64Coder.decode(
encodedMessage
)
)
);
} | [
"@",
"Deprecated",
"public",
"static",
"FileMessage",
"decode",
"(",
"String",
"encodedMessage",
")",
"throws",
"IOException",
"{",
"return",
"decode",
"(",
"encodedMessage",
".",
"isEmpty",
"(",
")",
"?",
"ByteArray",
".",
"EMPTY_BYTE_ARRAY",
":",
"new",
"ByteA... | base-64 decodes the message into a temp file.
@see #decode(java.lang.String, java.io.File)
@deprecated Please use {@link TempFileContext}
as {@link File#deleteOnExit()} is prone to memory leaks in long-running applications. | [
"base",
"-",
"64",
"decodes",
"the",
"message",
"into",
"a",
"temp",
"file",
"."
] | dbe4d3baefcc846f99b7eeab42646057e99729f0 | https://github.com/aoindustries/ao-messaging-api/blob/dbe4d3baefcc846f99b7eeab42646057e99729f0/src/main/java/com/aoindustries/messaging/FileMessage.java#L69-L80 | train |
aoindustries/ao-messaging-api | src/main/java/com/aoindustries/messaging/FileMessage.java | FileMessage.decode | public static FileMessage decode(ByteArray encodedMessage, File file) throws IOException {
try (OutputStream out = new FileOutputStream(file)) {
out.write(encodedMessage.array, 0, encodedMessage.size);
}
return new FileMessage(true, file);
} | java | public static FileMessage decode(ByteArray encodedMessage, File file) throws IOException {
try (OutputStream out = new FileOutputStream(file)) {
out.write(encodedMessage.array, 0, encodedMessage.size);
}
return new FileMessage(true, file);
} | [
"public",
"static",
"FileMessage",
"decode",
"(",
"ByteArray",
"encodedMessage",
",",
"File",
"file",
")",
"throws",
"IOException",
"{",
"try",
"(",
"OutputStream",
"out",
"=",
"new",
"FileOutputStream",
"(",
"file",
")",
")",
"{",
"out",
".",
"write",
"(",
... | Restores this message into the provided file.
@see #decode(java.lang.String, java.io.File) | [
"Restores",
"this",
"message",
"into",
"the",
"provided",
"file",
"."
] | dbe4d3baefcc846f99b7eeab42646057e99729f0 | https://github.com/aoindustries/ao-messaging-api/blob/dbe4d3baefcc846f99b7eeab42646057e99729f0/src/main/java/com/aoindustries/messaging/FileMessage.java#L87-L92 | train |
aoindustries/ao-messaging-api | src/main/java/com/aoindustries/messaging/FileMessage.java | FileMessage.decode | @Deprecated
public static FileMessage decode(ByteArray encodedMessage) throws IOException {
File file = File.createTempFile("FileMessage.", null);
file.deleteOnExit();
return decode(encodedMessage, file);
} | java | @Deprecated
public static FileMessage decode(ByteArray encodedMessage) throws IOException {
File file = File.createTempFile("FileMessage.", null);
file.deleteOnExit();
return decode(encodedMessage, file);
} | [
"@",
"Deprecated",
"public",
"static",
"FileMessage",
"decode",
"(",
"ByteArray",
"encodedMessage",
")",
"throws",
"IOException",
"{",
"File",
"file",
"=",
"File",
".",
"createTempFile",
"(",
"\"FileMessage.\"",
",",
"null",
")",
";",
"file",
".",
"deleteOnExit"... | Restores this message into a temp file.
@see #decode(com.aoindustries.messaging.ByteArray, java.io.File)
@deprecated Please use {@link TempFileContext}
as {@link File#deleteOnExit()} is prone to memory leaks in long-running applications. | [
"Restores",
"this",
"message",
"into",
"a",
"temp",
"file",
"."
] | dbe4d3baefcc846f99b7eeab42646057e99729f0 | https://github.com/aoindustries/ao-messaging-api/blob/dbe4d3baefcc846f99b7eeab42646057e99729f0/src/main/java/com/aoindustries/messaging/FileMessage.java#L102-L107 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/rmi/RegistryManager.java | RegistryManager.createRegistry | public static Registry createRegistry(int port, RMIClientSocketFactory csf, RMIServerSocketFactory ssf) throws RemoteException {
synchronized(registryCache) {
Integer portObj = port;
Registry registry = registryCache.get(portObj);
if(registry==null) {
registry = LocateRegistry.createRegistry(port, csf, ssf);
registryCache.put(portObj, registry);
}
return registry;
}
} | java | public static Registry createRegistry(int port, RMIClientSocketFactory csf, RMIServerSocketFactory ssf) throws RemoteException {
synchronized(registryCache) {
Integer portObj = port;
Registry registry = registryCache.get(portObj);
if(registry==null) {
registry = LocateRegistry.createRegistry(port, csf, ssf);
registryCache.put(portObj, registry);
}
return registry;
}
} | [
"public",
"static",
"Registry",
"createRegistry",
"(",
"int",
"port",
",",
"RMIClientSocketFactory",
"csf",
",",
"RMIServerSocketFactory",
"ssf",
")",
"throws",
"RemoteException",
"{",
"synchronized",
"(",
"registryCache",
")",
"{",
"Integer",
"portObj",
"=",
"port"... | Creates a registry or returns the registry that is already using the port. | [
"Creates",
"a",
"registry",
"or",
"returns",
"the",
"registry",
"that",
"is",
"already",
"using",
"the",
"port",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/rmi/RegistryManager.java#L48-L58 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/AOPool.java | AOPool.close | final public void close() {
List<C> connsToClose;
synchronized(poolLock) {
// Prevent any new connections
isClosed = true;
// Find any connections that are available and open
connsToClose = new ArrayList<>(availableConnections.size());
for(PooledConnection<C> availableConnection : availableConnections) {
synchronized(availableConnection) {
C conn = availableConnection.connection;
if(conn!=null) {
availableConnection.connection = null;
connsToClose.add(conn);
}
}
}
poolLock.notifyAll();
}
// Close all of the connections
for(C conn : connsToClose) {
try {
close(conn);
} catch(Exception err) {
logger.log(Level.WARNING, null, err);
}
}
} | java | final public void close() {
List<C> connsToClose;
synchronized(poolLock) {
// Prevent any new connections
isClosed = true;
// Find any connections that are available and open
connsToClose = new ArrayList<>(availableConnections.size());
for(PooledConnection<C> availableConnection : availableConnections) {
synchronized(availableConnection) {
C conn = availableConnection.connection;
if(conn!=null) {
availableConnection.connection = null;
connsToClose.add(conn);
}
}
}
poolLock.notifyAll();
}
// Close all of the connections
for(C conn : connsToClose) {
try {
close(conn);
} catch(Exception err) {
logger.log(Level.WARNING, null, err);
}
}
} | [
"final",
"public",
"void",
"close",
"(",
")",
"{",
"List",
"<",
"C",
">",
"connsToClose",
";",
"synchronized",
"(",
"poolLock",
")",
"{",
"// Prevent any new connections",
"isClosed",
"=",
"true",
";",
"// Find any connections that are available and open",
"connsToClo... | Shuts down the pool, exceptions during close will be logged as a warning and not thrown. | [
"Shuts",
"down",
"the",
"pool",
"exceptions",
"during",
"close",
"will",
"be",
"logged",
"as",
"a",
"warning",
"and",
"not",
"thrown",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/AOPool.java#L228-L254 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/AOPool.java | AOPool.getConnectionCount | final public int getConnectionCount() {
int total = 0;
synchronized(poolLock) {
for(PooledConnection<C> pooledConnection : allConnections) {
if(pooledConnection.connection!=null) total++;
}
}
return total;
} | java | final public int getConnectionCount() {
int total = 0;
synchronized(poolLock) {
for(PooledConnection<C> pooledConnection : allConnections) {
if(pooledConnection.connection!=null) total++;
}
}
return total;
} | [
"final",
"public",
"int",
"getConnectionCount",
"(",
")",
"{",
"int",
"total",
"=",
"0",
";",
"synchronized",
"(",
"poolLock",
")",
"{",
"for",
"(",
"PooledConnection",
"<",
"C",
">",
"pooledConnection",
":",
"allConnections",
")",
"{",
"if",
"(",
"pooledC... | Gets the number of connections currently connected. | [
"Gets",
"the",
"number",
"of",
"connections",
"currently",
"connected",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/AOPool.java#L268-L276 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/AOPool.java | AOPool.release | private void release(PooledConnection<C> pooledConnection) {
long currentTime = System.currentTimeMillis();
long useTime;
synchronized(pooledConnection) {
pooledConnection.releaseTime = currentTime;
useTime = currentTime - pooledConnection.startTime;
if(useTime>0) pooledConnection.totalTime.addAndGet(useTime);
pooledConnection.allocateStackTrace = null;
}
// Remove from the pool
synchronized(poolLock) {
try {
if(busyConnections.remove(pooledConnection)) availableConnections.add(pooledConnection);
} finally {
poolLock.notify();
}
}
} | java | private void release(PooledConnection<C> pooledConnection) {
long currentTime = System.currentTimeMillis();
long useTime;
synchronized(pooledConnection) {
pooledConnection.releaseTime = currentTime;
useTime = currentTime - pooledConnection.startTime;
if(useTime>0) pooledConnection.totalTime.addAndGet(useTime);
pooledConnection.allocateStackTrace = null;
}
// Remove from the pool
synchronized(poolLock) {
try {
if(busyConnections.remove(pooledConnection)) availableConnections.add(pooledConnection);
} finally {
poolLock.notify();
}
}
} | [
"private",
"void",
"release",
"(",
"PooledConnection",
"<",
"C",
">",
"pooledConnection",
")",
"{",
"long",
"currentTime",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"long",
"useTime",
";",
"synchronized",
"(",
"pooledConnection",
")",
"{",
"poole... | Releases a PooledConnection. It is safe to release
it multiple times. The connection should have either
been closed or reset before this is called because
this makes the connection available for the next request. | [
"Releases",
"a",
"PooledConnection",
".",
"It",
"is",
"safe",
"to",
"release",
"it",
"multiple",
"times",
".",
"The",
"connection",
"should",
"have",
"either",
"been",
"closed",
"or",
"reset",
"before",
"this",
"is",
"called",
"because",
"this",
"makes",
"th... | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/AOPool.java#L450-L467 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/AOPool.java | AOPool.getConnects | final public long getConnects() {
long total = 0;
synchronized(poolLock) {
for(PooledConnection<C> conn : allConnections) {
total += conn.connectCount.get();
}
}
return total;
} | java | final public long getConnects() {
long total = 0;
synchronized(poolLock) {
for(PooledConnection<C> conn : allConnections) {
total += conn.connectCount.get();
}
}
return total;
} | [
"final",
"public",
"long",
"getConnects",
"(",
")",
"{",
"long",
"total",
"=",
"0",
";",
"synchronized",
"(",
"poolLock",
")",
"{",
"for",
"(",
"PooledConnection",
"<",
"C",
">",
"conn",
":",
"allConnections",
")",
"{",
"total",
"+=",
"conn",
".",
"con... | Gets the total number of connects for the entire pool. | [
"Gets",
"the",
"total",
"number",
"of",
"connects",
"for",
"the",
"entire",
"pool",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/AOPool.java#L472-L480 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/AOPool.java | AOPool.run | @Override
final public void run() {
while(true) {
try {
try {
sleep(delayTime);
} catch(InterruptedException err) {
logger.log(Level.WARNING, null, err);
}
long time = System.currentTimeMillis();
List<C> connsToClose;
synchronized(poolLock) {
if(isClosed) return;
// Find any connections that are available and been idle too long
int maxIdle = maxIdleTime;
connsToClose = new ArrayList<>(availableConnections.size());
for(PooledConnection<C> availableConnection : availableConnections) {
synchronized(availableConnection) {
C conn = availableConnection.connection;
if(conn!=null) {
if(
(time-availableConnection.releaseTime) > maxIdle // Idle too long
|| (
maxConnectionAge!=UNLIMITED_MAX_CONNECTION_AGE
&& (
availableConnection.createTime > time // System time reset?
|| (time-availableConnection.createTime) >= maxConnectionAge // Max connection age reached
)
)
) {
availableConnection.connection = null;
connsToClose.add(conn);
}
}
}
}
}
// Close all of the connections
for(C conn : connsToClose) {
try {
close(conn);
} catch(Exception err) {
logger.log(Level.WARNING, null, err);
}
}
} catch (ThreadDeath TD) {
throw TD;
} catch (Throwable T) {
logger.logp(Level.SEVERE, AOPool.class.getName(), "run", null, T);
}
}
} | java | @Override
final public void run() {
while(true) {
try {
try {
sleep(delayTime);
} catch(InterruptedException err) {
logger.log(Level.WARNING, null, err);
}
long time = System.currentTimeMillis();
List<C> connsToClose;
synchronized(poolLock) {
if(isClosed) return;
// Find any connections that are available and been idle too long
int maxIdle = maxIdleTime;
connsToClose = new ArrayList<>(availableConnections.size());
for(PooledConnection<C> availableConnection : availableConnections) {
synchronized(availableConnection) {
C conn = availableConnection.connection;
if(conn!=null) {
if(
(time-availableConnection.releaseTime) > maxIdle // Idle too long
|| (
maxConnectionAge!=UNLIMITED_MAX_CONNECTION_AGE
&& (
availableConnection.createTime > time // System time reset?
|| (time-availableConnection.createTime) >= maxConnectionAge // Max connection age reached
)
)
) {
availableConnection.connection = null;
connsToClose.add(conn);
}
}
}
}
}
// Close all of the connections
for(C conn : connsToClose) {
try {
close(conn);
} catch(Exception err) {
logger.log(Level.WARNING, null, err);
}
}
} catch (ThreadDeath TD) {
throw TD;
} catch (Throwable T) {
logger.logp(Level.SEVERE, AOPool.class.getName(), "run", null, T);
}
}
} | [
"@",
"Override",
"final",
"public",
"void",
"run",
"(",
")",
"{",
"while",
"(",
"true",
")",
"{",
"try",
"{",
"try",
"{",
"sleep",
"(",
"delayTime",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"err",
")",
"{",
"logger",
".",
"log",
"(",
"L... | The RefreshConnection thread polls every connection in the connection pool. If it
detects a connection is idle for more than the pre-defined MAX_IDLE_TIME, it closes
the connection. It will stop when the pool is flagged as closed. | [
"The",
"RefreshConnection",
"thread",
"polls",
"every",
"connection",
"in",
"the",
"connection",
"pool",
".",
"If",
"it",
"detects",
"a",
"connection",
"is",
"idle",
"for",
"more",
"than",
"the",
"pre",
"-",
"defined",
"MAX_IDLE_TIME",
"it",
"closes",
"the",
... | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/AOPool.java#L762-L813 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/md5/MD5Utils.java | MD5Utils.md5 | public static byte[] md5(File file) throws IOException {
try (InputStream in = new FileInputStream(file)) {
return md5(in);
}
} | java | public static byte[] md5(File file) throws IOException {
try (InputStream in = new FileInputStream(file)) {
return md5(in);
}
} | [
"public",
"static",
"byte",
"[",
"]",
"md5",
"(",
"File",
"file",
")",
"throws",
"IOException",
"{",
"try",
"(",
"InputStream",
"in",
"=",
"new",
"FileInputStream",
"(",
"file",
")",
")",
"{",
"return",
"md5",
"(",
"in",
")",
";",
"}",
"}"
] | Gets the MD5 hashcode of a file. | [
"Gets",
"the",
"MD5",
"hashcode",
"of",
"a",
"file",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/md5/MD5Utils.java#L54-L58 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/md5/MD5Utils.java | MD5Utils.md5 | public static byte[] md5(InputStream in) throws IOException {
MD5InputStream md5in=new MD5InputStream(in);
byte[] trashBuffer = BufferManager.getBytes();
try {
while(md5in.read(trashBuffer, 0, BufferManager.BUFFER_SIZE) != -1) {
// Intentional empty block
}
} finally {
BufferManager.release(trashBuffer, false);
}
return md5in.hash();
} | java | public static byte[] md5(InputStream in) throws IOException {
MD5InputStream md5in=new MD5InputStream(in);
byte[] trashBuffer = BufferManager.getBytes();
try {
while(md5in.read(trashBuffer, 0, BufferManager.BUFFER_SIZE) != -1) {
// Intentional empty block
}
} finally {
BufferManager.release(trashBuffer, false);
}
return md5in.hash();
} | [
"public",
"static",
"byte",
"[",
"]",
"md5",
"(",
"InputStream",
"in",
")",
"throws",
"IOException",
"{",
"MD5InputStream",
"md5in",
"=",
"new",
"MD5InputStream",
"(",
"in",
")",
";",
"byte",
"[",
"]",
"trashBuffer",
"=",
"BufferManager",
".",
"getBytes",
... | Gets the MD5 hashcode of an input stream. | [
"Gets",
"the",
"MD5",
"hashcode",
"of",
"an",
"input",
"stream",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/md5/MD5Utils.java#L63-L74 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/TempFile.java | TempFile.delete | public void delete() throws IOException {
File f = tempFile;
if(f!=null) {
FileUtils.delete(f);
tempFile = null;
}
} | java | public void delete() throws IOException {
File f = tempFile;
if(f!=null) {
FileUtils.delete(f);
tempFile = null;
}
} | [
"public",
"void",
"delete",
"(",
")",
"throws",
"IOException",
"{",
"File",
"f",
"=",
"tempFile",
";",
"if",
"(",
"f",
"!=",
"null",
")",
"{",
"FileUtils",
".",
"delete",
"(",
"f",
")",
";",
"tempFile",
"=",
"null",
";",
"}",
"}"
] | Deletes the underlying temp file immediately.
Subsequent calls will not delete the temp file, even if another file has the same path.
If already deleted, has no effect. | [
"Deletes",
"the",
"underlying",
"temp",
"file",
"immediately",
".",
"Subsequent",
"calls",
"will",
"not",
"delete",
"the",
"temp",
"file",
"even",
"if",
"another",
"file",
"has",
"the",
"same",
"path",
".",
"If",
"already",
"deleted",
"has",
"no",
"effect",
... | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/TempFile.java#L77-L83 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/io/TempFile.java | TempFile.getFile | public File getFile() throws IllegalStateException {
File f = tempFile;
if(f==null) throw new IllegalStateException();
return f;
} | java | public File getFile() throws IllegalStateException {
File f = tempFile;
if(f==null) throw new IllegalStateException();
return f;
} | [
"public",
"File",
"getFile",
"(",
")",
"throws",
"IllegalStateException",
"{",
"File",
"f",
"=",
"tempFile",
";",
"if",
"(",
"f",
"==",
"null",
")",
"throw",
"new",
"IllegalStateException",
"(",
")",
";",
"return",
"f",
";",
"}"
] | Gets the temp file.
@exception IllegalStateException if already deleted | [
"Gets",
"the",
"temp",
"file",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/io/TempFile.java#L102-L106 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/AutoSiteMap.java | AutoSiteMap.buildData | private void buildData(String path, WebPage page, List<TreePageData> data, WebSiteRequest req) throws IOException, SQLException {
if(isVisible(page)) {
if(path.length()>0) path=path+'/'+page.getShortTitle();
else path=page.getShortTitle();
WebPage[] pages=page.getCachedPages(req);
int len=pages.length;
data.add(
new TreePageData(
len>0 ? (path+'/') : path,
req.getContextPath()+req.getURL(page),
page.getDescription()
)
);
for(int c=0; c<len; c++) buildData(path, pages[c], data, req);
}
} | java | private void buildData(String path, WebPage page, List<TreePageData> data, WebSiteRequest req) throws IOException, SQLException {
if(isVisible(page)) {
if(path.length()>0) path=path+'/'+page.getShortTitle();
else path=page.getShortTitle();
WebPage[] pages=page.getCachedPages(req);
int len=pages.length;
data.add(
new TreePageData(
len>0 ? (path+'/') : path,
req.getContextPath()+req.getURL(page),
page.getDescription()
)
);
for(int c=0; c<len; c++) buildData(path, pages[c], data, req);
}
} | [
"private",
"void",
"buildData",
"(",
"String",
"path",
",",
"WebPage",
"page",
",",
"List",
"<",
"TreePageData",
">",
"data",
",",
"WebSiteRequest",
"req",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"if",
"(",
"isVisible",
"(",
"page",
")",
")... | Recursively builds the list of all sites. | [
"Recursively",
"builds",
"the",
"list",
"of",
"all",
"sites",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/AutoSiteMap.java#L56-L71 | train |
aoindustries/aoweb-framework | src/main/java/com/aoindustries/website/framework/AutoSiteMap.java | AutoSiteMap.doGet | @Override
public void doGet(
ChainWriter out,
WebSiteRequest req,
HttpServletResponse resp
) throws IOException, SQLException {
if(req!=null) super.doGet(out, req, resp);
} | java | @Override
public void doGet(
ChainWriter out,
WebSiteRequest req,
HttpServletResponse resp
) throws IOException, SQLException {
if(req!=null) super.doGet(out, req, resp);
} | [
"@",
"Override",
"public",
"void",
"doGet",
"(",
"ChainWriter",
"out",
",",
"WebSiteRequest",
"req",
",",
"HttpServletResponse",
"resp",
")",
"throws",
"IOException",
",",
"SQLException",
"{",
"if",
"(",
"req",
"!=",
"null",
")",
"super",
".",
"doGet",
"(",
... | The content of this page will not be included in the interal search engine. | [
"The",
"content",
"of",
"this",
"page",
"will",
"not",
"be",
"included",
"in",
"the",
"interal",
"search",
"engine",
"."
] | 8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0 | https://github.com/aoindustries/aoweb-framework/blob/8e58af4f5dd898cd2fdb855ffa810a1ca6973ae0/src/main/java/com/aoindustries/website/framework/AutoSiteMap.java#L76-L83 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/util/i18n/ModifiablePropertiesResourceBundle.java | ModifiablePropertiesResourceBundle.saveProperties | private void saveProperties() {
assert Thread.holdsLock(properties);
try {
// Create a properties instance that sorts the output by keys (case-insensitive)
Properties writer = new Properties() {
private static final long serialVersionUID = 6953022173340009928L;
@Override
public Enumeration<Object> keys() {
SortedSet<Object> sortedSet = new TreeSet<>(Collator.getInstance(Locale.ROOT));
Enumeration<Object> e = super.keys();
while(e.hasMoreElements()) sortedSet.add(e.nextElement());
return Collections.enumeration(sortedSet);
}
};
writer.putAll(properties);
File tmpFile = File.createTempFile("ApplicationResources", null, sourceFile.getParentFile());
OutputStream out = new BufferedOutputStream(new FileOutputStream(tmpFile));
try {
// Write any comments from when file was read
if(sourceFileComments!=null) {
for(String line : sourceFileComments) {
out.write(line.getBytes(propertiesCharset));
out.write(EOL.getBytes(propertiesCharset));
}
}
// Wrap to skip any comments generated by Properties code
out = new SkipCommentsFilterOutputStream(out);
writer.store(out, null);
} finally {
out.close();
}
FileUtils.renameAllowNonAtomic(tmpFile, sourceFile);
} catch(IOException err) {
throw new RuntimeException(err);
}
} | java | private void saveProperties() {
assert Thread.holdsLock(properties);
try {
// Create a properties instance that sorts the output by keys (case-insensitive)
Properties writer = new Properties() {
private static final long serialVersionUID = 6953022173340009928L;
@Override
public Enumeration<Object> keys() {
SortedSet<Object> sortedSet = new TreeSet<>(Collator.getInstance(Locale.ROOT));
Enumeration<Object> e = super.keys();
while(e.hasMoreElements()) sortedSet.add(e.nextElement());
return Collections.enumeration(sortedSet);
}
};
writer.putAll(properties);
File tmpFile = File.createTempFile("ApplicationResources", null, sourceFile.getParentFile());
OutputStream out = new BufferedOutputStream(new FileOutputStream(tmpFile));
try {
// Write any comments from when file was read
if(sourceFileComments!=null) {
for(String line : sourceFileComments) {
out.write(line.getBytes(propertiesCharset));
out.write(EOL.getBytes(propertiesCharset));
}
}
// Wrap to skip any comments generated by Properties code
out = new SkipCommentsFilterOutputStream(out);
writer.store(out, null);
} finally {
out.close();
}
FileUtils.renameAllowNonAtomic(tmpFile, sourceFile);
} catch(IOException err) {
throw new RuntimeException(err);
}
} | [
"private",
"void",
"saveProperties",
"(",
")",
"{",
"assert",
"Thread",
".",
"holdsLock",
"(",
"properties",
")",
";",
"try",
"{",
"// Create a properties instance that sorts the output by keys (case-insensitive)",
"Properties",
"writer",
"=",
"new",
"Properties",
"(",
... | Saves the properties file in ascending key order. All accesses must
already hold a lock on the properties object. | [
"Saves",
"the",
"properties",
"file",
"in",
"ascending",
"key",
"order",
".",
"All",
"accesses",
"must",
"already",
"hold",
"a",
"lock",
"on",
"the",
"properties",
"object",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/i18n/ModifiablePropertiesResourceBundle.java#L328-L363 | train |
aoindustries/aocode-public | src/main/java/com/aoindustries/util/graph/SymmetricAcyclicGraphChecker.java | SymmetricAcyclicGraphChecker.checkGraph | @Override
public void checkGraph() throws AsymmetricException, CycleException, EX {
Set<V> vertices = graph.getVertices();
Map<V,Color> colors = new HashMap<>(vertices.size()*4/3+1);
Map<V,V> predecessors = new HashMap<>(); // Could this be a simple sequence like TopologicalSorter? Any benefit?
for(V v : vertices) {
if(!colors.containsKey(v)) doCheck(colors, predecessors, v);
}
} | java | @Override
public void checkGraph() throws AsymmetricException, CycleException, EX {
Set<V> vertices = graph.getVertices();
Map<V,Color> colors = new HashMap<>(vertices.size()*4/3+1);
Map<V,V> predecessors = new HashMap<>(); // Could this be a simple sequence like TopologicalSorter? Any benefit?
for(V v : vertices) {
if(!colors.containsKey(v)) doCheck(colors, predecessors, v);
}
} | [
"@",
"Override",
"public",
"void",
"checkGraph",
"(",
")",
"throws",
"AsymmetricException",
",",
"CycleException",
",",
"EX",
"{",
"Set",
"<",
"V",
">",
"vertices",
"=",
"graph",
".",
"getVertices",
"(",
")",
";",
"Map",
"<",
"V",
",",
"Color",
">",
"c... | Test the graph for cycles and makes sure that all connections are consistent with back connections.
Cycle algorithm adapted from:
http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/GraphAlgor/depthSearch.htm
http://www.eecs.berkeley.edu/~kamil/teaching/sp03/041403.pdf
In the case of a multigraph, any number of edges one direction is considered a match to any number
of edges back. The number does not need to be equal.
@throws AsymmetricException where the edges are not symmetric
@throws CycleException if there is a cycle in the graph | [
"Test",
"the",
"graph",
"for",
"cycles",
"and",
"makes",
"sure",
"that",
"all",
"connections",
"are",
"consistent",
"with",
"back",
"connections",
"."
] | c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3 | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/util/graph/SymmetricAcyclicGraphChecker.java#L62-L70 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.