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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
VoltDB/voltdb | third_party/java/src/com/google_voltpatches/common/io/Files.java | Files.readLines | public static List<String> readLines(File file, Charset charset) throws IOException {
// don't use asCharSource(file, charset).readLines() because that returns
// an immutable list, which would change the behavior of this method
return readLines(
file,
charset,
new LineProcessor<List<String>>() {
final List<String> result = Lists.newArrayList();
@Override
public boolean processLine(String line) {
result.add(line);
return true;
}
@Override
public List<String> getResult() {
return result;
}
});
} | java | public static List<String> readLines(File file, Charset charset) throws IOException {
// don't use asCharSource(file, charset).readLines() because that returns
// an immutable list, which would change the behavior of this method
return readLines(
file,
charset,
new LineProcessor<List<String>>() {
final List<String> result = Lists.newArrayList();
@Override
public boolean processLine(String line) {
result.add(line);
return true;
}
@Override
public List<String> getResult() {
return result;
}
});
} | [
"public",
"static",
"List",
"<",
"String",
">",
"readLines",
"(",
"File",
"file",
",",
"Charset",
"charset",
")",
"throws",
"IOException",
"{",
"// don't use asCharSource(file, charset).readLines() because that returns",
"// an immutable list, which would change the behavior of t... | Reads all of the lines from a file. The lines do not include line-termination characters, but
do include other leading and trailing whitespace.
<p>This method returns a mutable {@code List}. For an {@code ImmutableList}, use
{@code Files.asCharSource(file, charset).readLines()}.
@param file the file to read from
@param charset the charset used to decode the input stream; see {@link StandardCharsets} for
helpful predefined constants
@return a mutable {@link List} containing all the lines
@throws IOException if an I/O error occurs | [
"Reads",
"all",
"of",
"the",
"lines",
"from",
"a",
"file",
".",
"The",
"lines",
"do",
"not",
"include",
"line",
"-",
"termination",
"characters",
"but",
"do",
"include",
"other",
"leading",
"and",
"trailing",
"whitespace",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/com/google_voltpatches/common/io/Files.java#L517-L537 | train |
VoltDB/voltdb | third_party/java/src/com/google_voltpatches/common/io/Files.java | Files.readBytes | @CanIgnoreReturnValue // some processors won't return a useful result
public static <T> T readBytes(File file, ByteProcessor<T> processor) throws IOException {
return asByteSource(file).read(processor);
} | java | @CanIgnoreReturnValue // some processors won't return a useful result
public static <T> T readBytes(File file, ByteProcessor<T> processor) throws IOException {
return asByteSource(file).read(processor);
} | [
"@",
"CanIgnoreReturnValue",
"// some processors won't return a useful result",
"public",
"static",
"<",
"T",
">",
"T",
"readBytes",
"(",
"File",
"file",
",",
"ByteProcessor",
"<",
"T",
">",
"processor",
")",
"throws",
"IOException",
"{",
"return",
"asByteSource",
"... | Process the bytes of a file.
<p>(If this seems too complicated, maybe you're looking for {@link #toByteArray}.)
@param file the file to read
@param processor the object to which the bytes of the file are passed.
@return the result of the byte processor
@throws IOException if an I/O error occurs | [
"Process",
"the",
"bytes",
"of",
"a",
"file",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/com/google_voltpatches/common/io/Files.java#L566-L569 | train |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/RangeVariableResolver.java | RangeVariableResolver.decomposeCondition | static Expression decomposeCondition(Expression e,
HsqlArrayList conditions) {
if (e == null) {
return Expression.EXPR_TRUE;
}
Expression arg1 = e.getLeftNode();
Expression arg2 = e.getRightNode();
int type = e.getType();
if (type == OpTypes.AND) {
arg1 = decomposeCondition(arg1, conditions);
arg2 = decomposeCondition(arg2, conditions);
if (arg1 == Expression.EXPR_TRUE) {
return arg2;
}
if (arg2 == Expression.EXPR_TRUE) {
return arg1;
}
e.setLeftNode(arg1);
e.setRightNode(arg2);
return e;
} else if (type == OpTypes.EQUAL) {
if (arg1.getType() == OpTypes.ROW
&& arg2.getType() == OpTypes.ROW) {
for (int i = 0; i < arg1.nodes.length; i++) {
Expression part = new ExpressionLogical(arg1.nodes[i],
arg2.nodes[i]);
part.resolveTypes(null, null);
conditions.add(part);
}
return Expression.EXPR_TRUE;
}
}
if (e != Expression.EXPR_TRUE) {
conditions.add(e);
}
return Expression.EXPR_TRUE;
} | java | static Expression decomposeCondition(Expression e,
HsqlArrayList conditions) {
if (e == null) {
return Expression.EXPR_TRUE;
}
Expression arg1 = e.getLeftNode();
Expression arg2 = e.getRightNode();
int type = e.getType();
if (type == OpTypes.AND) {
arg1 = decomposeCondition(arg1, conditions);
arg2 = decomposeCondition(arg2, conditions);
if (arg1 == Expression.EXPR_TRUE) {
return arg2;
}
if (arg2 == Expression.EXPR_TRUE) {
return arg1;
}
e.setLeftNode(arg1);
e.setRightNode(arg2);
return e;
} else if (type == OpTypes.EQUAL) {
if (arg1.getType() == OpTypes.ROW
&& arg2.getType() == OpTypes.ROW) {
for (int i = 0; i < arg1.nodes.length; i++) {
Expression part = new ExpressionLogical(arg1.nodes[i],
arg2.nodes[i]);
part.resolveTypes(null, null);
conditions.add(part);
}
return Expression.EXPR_TRUE;
}
}
if (e != Expression.EXPR_TRUE) {
conditions.add(e);
}
return Expression.EXPR_TRUE;
} | [
"static",
"Expression",
"decomposeCondition",
"(",
"Expression",
"e",
",",
"HsqlArrayList",
"conditions",
")",
"{",
"if",
"(",
"e",
"==",
"null",
")",
"{",
"return",
"Expression",
".",
"EXPR_TRUE",
";",
"}",
"Expression",
"arg1",
"=",
"e",
".",
"getLeftNode"... | Divides AND conditions and assigns | [
"Divides",
"AND",
"conditions",
"and",
"assigns"
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/RangeVariableResolver.java#L142-L189 | train |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/RangeVariableResolver.java | RangeVariableResolver.assignToLists | void assignToLists() {
int lastOuterIndex = -1;
for (int i = 0; i < rangeVariables.length; i++) {
if (rangeVariables[i].isLeftJoin
|| rangeVariables[i].isRightJoin) {
lastOuterIndex = i;
}
if (lastOuterIndex == i) {
joinExpressions[i].addAll(tempJoinExpressions[i]);
} else {
for (int j = 0; j < tempJoinExpressions[i].size(); j++) {
assignToLists((Expression) tempJoinExpressions[i].get(j),
joinExpressions, lastOuterIndex + 1);
}
}
}
for (int i = 0; i < queryExpressions.size(); i++) {
assignToLists((Expression) queryExpressions.get(i),
whereExpressions, lastOuterIndex);
}
} | java | void assignToLists() {
int lastOuterIndex = -1;
for (int i = 0; i < rangeVariables.length; i++) {
if (rangeVariables[i].isLeftJoin
|| rangeVariables[i].isRightJoin) {
lastOuterIndex = i;
}
if (lastOuterIndex == i) {
joinExpressions[i].addAll(tempJoinExpressions[i]);
} else {
for (int j = 0; j < tempJoinExpressions[i].size(); j++) {
assignToLists((Expression) tempJoinExpressions[i].get(j),
joinExpressions, lastOuterIndex + 1);
}
}
}
for (int i = 0; i < queryExpressions.size(); i++) {
assignToLists((Expression) queryExpressions.get(i),
whereExpressions, lastOuterIndex);
}
} | [
"void",
"assignToLists",
"(",
")",
"{",
"int",
"lastOuterIndex",
"=",
"-",
"1",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"rangeVariables",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"rangeVariables",
"[",
"i",
"]",
".",
"isL... | Assigns the conditions to separate lists | [
"Assigns",
"the",
"conditions",
"to",
"separate",
"lists"
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/RangeVariableResolver.java#L194-L218 | train |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/RangeVariableResolver.java | RangeVariableResolver.assignToLists | void assignToLists(Expression e, HsqlArrayList[] expressionLists,
int first) {
set.clear();
e.collectRangeVariables(rangeVariables, set);
int index = rangeVarSet.getLargestIndex(set);
// condition is independent of tables if no range variable is found
if (index == -1) {
index = 0;
}
// condition is assigned to first non-outer range variable
if (index < first) {
index = first;
}
expressionLists[index].add(e);
} | java | void assignToLists(Expression e, HsqlArrayList[] expressionLists,
int first) {
set.clear();
e.collectRangeVariables(rangeVariables, set);
int index = rangeVarSet.getLargestIndex(set);
// condition is independent of tables if no range variable is found
if (index == -1) {
index = 0;
}
// condition is assigned to first non-outer range variable
if (index < first) {
index = first;
}
expressionLists[index].add(e);
} | [
"void",
"assignToLists",
"(",
"Expression",
"e",
",",
"HsqlArrayList",
"[",
"]",
"expressionLists",
",",
"int",
"first",
")",
"{",
"set",
".",
"clear",
"(",
")",
";",
"e",
".",
"collectRangeVariables",
"(",
"rangeVariables",
",",
"set",
")",
";",
"int",
... | Assigns a single condition to the relevant list of conditions
Parameter first indicates the first range variable to which condition
can be assigned | [
"Assigns",
"a",
"single",
"condition",
"to",
"the",
"relevant",
"list",
"of",
"conditions"
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/RangeVariableResolver.java#L226-L245 | train |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/RangeVariableResolver.java | RangeVariableResolver.assignToRangeVariables | void assignToRangeVariables() {
for (int i = 0; i < rangeVariables.length; i++) {
boolean isOuter = rangeVariables[i].isLeftJoin
|| rangeVariables[i].isRightJoin;
if (isOuter) {
assignToRangeVariable(rangeVariables[i], i,
joinExpressions[i], true);
assignToRangeVariable(rangeVariables[i], i,
whereExpressions[i], false);
} else {
joinExpressions[i].addAll(whereExpressions[i]);
assignToRangeVariable(rangeVariables[i], i,
joinExpressions[i], true);
}
// A VoltDB extension to disable
// Turn off some weird rewriting of in expressions based on index support for the query.
// This makes it simpler to parse on the VoltDB side,
// at the expense of HSQL performance.
// Also fixed an apparent join/where confusion?
if (inExpressions[i] != null) {
if (!flags[i] && isOuter) {
rangeVariables[i].addJoinCondition(inExpressions[i]);
} else {
rangeVariables[i].addWhereCondition(inExpressions[i]);
}
/* disable 7 lines ...
if (rangeVariables[i].hasIndexCondition()
&& inExpressions[i] != null) {
if (!flags[i] && isOuter) {
rangeVariables[i].addWhereCondition(inExpressions[i]);
} else {
rangeVariables[i].addJoinCondition(inExpressions[i]);
}
... disabled 7 lines */
// End of VoltDB extension
inExpressions[i] = null;
inExpressionCount--;
}
}
if (inExpressionCount != 0) {
// A VoltDB extension to disable
// This will never be called because of the change made to the block above
assert(false);
// End of VoltDB extension
setInConditionsAsTables();
}
} | java | void assignToRangeVariables() {
for (int i = 0; i < rangeVariables.length; i++) {
boolean isOuter = rangeVariables[i].isLeftJoin
|| rangeVariables[i].isRightJoin;
if (isOuter) {
assignToRangeVariable(rangeVariables[i], i,
joinExpressions[i], true);
assignToRangeVariable(rangeVariables[i], i,
whereExpressions[i], false);
} else {
joinExpressions[i].addAll(whereExpressions[i]);
assignToRangeVariable(rangeVariables[i], i,
joinExpressions[i], true);
}
// A VoltDB extension to disable
// Turn off some weird rewriting of in expressions based on index support for the query.
// This makes it simpler to parse on the VoltDB side,
// at the expense of HSQL performance.
// Also fixed an apparent join/where confusion?
if (inExpressions[i] != null) {
if (!flags[i] && isOuter) {
rangeVariables[i].addJoinCondition(inExpressions[i]);
} else {
rangeVariables[i].addWhereCondition(inExpressions[i]);
}
/* disable 7 lines ...
if (rangeVariables[i].hasIndexCondition()
&& inExpressions[i] != null) {
if (!flags[i] && isOuter) {
rangeVariables[i].addWhereCondition(inExpressions[i]);
} else {
rangeVariables[i].addJoinCondition(inExpressions[i]);
}
... disabled 7 lines */
// End of VoltDB extension
inExpressions[i] = null;
inExpressionCount--;
}
}
if (inExpressionCount != 0) {
// A VoltDB extension to disable
// This will never be called because of the change made to the block above
assert(false);
// End of VoltDB extension
setInConditionsAsTables();
}
} | [
"void",
"assignToRangeVariables",
"(",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"rangeVariables",
".",
"length",
";",
"i",
"++",
")",
"{",
"boolean",
"isOuter",
"=",
"rangeVariables",
"[",
"i",
"]",
".",
"isLeftJoin",
"||",
"rangeVari... | Assigns conditions to range variables and converts suitable IN conditions
to table lookup. | [
"Assigns",
"conditions",
"to",
"range",
"variables",
"and",
"converts",
"suitable",
"IN",
"conditions",
"to",
"table",
"lookup",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/RangeVariableResolver.java#L333-L385 | train |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/RangeVariableResolver.java | RangeVariableResolver.setInConditionsAsTables | void setInConditionsAsTables() {
for (int i = rangeVariables.length - 1; i >= 0; i--) {
RangeVariable rangeVar = rangeVariables[i];
Expression in = inExpressions[i];
if (in != null) {
Index index = rangeVar.rangeTable.getIndexForColumn(
in.getLeftNode().nodes[0].getColumnIndex());
RangeVariable newRangeVar =
new RangeVariable(in.getRightNode().subQuery.getTable(),
null, null, null, compileContext);
RangeVariable[] newList =
new RangeVariable[rangeVariables.length + 1];
ArrayUtil.copyAdjustArray(rangeVariables, newList,
newRangeVar, i, 1);
rangeVariables = newList;
// make two columns as arg
ColumnSchema left = rangeVar.rangeTable.getColumn(
in.getLeftNode().nodes[0].getColumnIndex());
ColumnSchema right = newRangeVar.rangeTable.getColumn(0);
Expression e = new ExpressionLogical(rangeVar, left,
newRangeVar, right);
rangeVar.addIndexCondition(e, index, flags[i]);
}
}
} | java | void setInConditionsAsTables() {
for (int i = rangeVariables.length - 1; i >= 0; i--) {
RangeVariable rangeVar = rangeVariables[i];
Expression in = inExpressions[i];
if (in != null) {
Index index = rangeVar.rangeTable.getIndexForColumn(
in.getLeftNode().nodes[0].getColumnIndex());
RangeVariable newRangeVar =
new RangeVariable(in.getRightNode().subQuery.getTable(),
null, null, null, compileContext);
RangeVariable[] newList =
new RangeVariable[rangeVariables.length + 1];
ArrayUtil.copyAdjustArray(rangeVariables, newList,
newRangeVar, i, 1);
rangeVariables = newList;
// make two columns as arg
ColumnSchema left = rangeVar.rangeTable.getColumn(
in.getLeftNode().nodes[0].getColumnIndex());
ColumnSchema right = newRangeVar.rangeTable.getColumn(0);
Expression e = new ExpressionLogical(rangeVar, left,
newRangeVar, right);
rangeVar.addIndexCondition(e, index, flags[i]);
}
}
} | [
"void",
"setInConditionsAsTables",
"(",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"rangeVariables",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"RangeVariable",
"rangeVar",
"=",
"rangeVariables",
"[",
"i",
"]",
";",
"Expression... | Converts an IN conditions into a JOIN | [
"Converts",
"an",
"IN",
"conditions",
"into",
"a",
"JOIN"
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/RangeVariableResolver.java#L613-L643 | train |
VoltDB/voltdb | src/frontend/org/voltdb/largequery/LargeBlockTask.java | LargeBlockTask.getStoreTask | public static LargeBlockTask getStoreTask(BlockId blockId, ByteBuffer block) {
return new LargeBlockTask() {
@Override
public LargeBlockResponse call() throws Exception {
Exception theException = null;
try {
LargeBlockManager.getInstance().storeBlock(blockId, block);
}
catch (Exception exc) {
theException = exc;
}
return new LargeBlockResponse(theException);
}
};
} | java | public static LargeBlockTask getStoreTask(BlockId blockId, ByteBuffer block) {
return new LargeBlockTask() {
@Override
public LargeBlockResponse call() throws Exception {
Exception theException = null;
try {
LargeBlockManager.getInstance().storeBlock(blockId, block);
}
catch (Exception exc) {
theException = exc;
}
return new LargeBlockResponse(theException);
}
};
} | [
"public",
"static",
"LargeBlockTask",
"getStoreTask",
"(",
"BlockId",
"blockId",
",",
"ByteBuffer",
"block",
")",
"{",
"return",
"new",
"LargeBlockTask",
"(",
")",
"{",
"@",
"Override",
"public",
"LargeBlockResponse",
"call",
"(",
")",
"throws",
"Exception",
"{"... | Get a new "store" task
@param blockId The block id of the block to store
@param block A ByteBuffer containing the block data
@return An instance of LargeBlockTask that will store a block | [
"Get",
"a",
"new",
"store",
"task"
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/largequery/LargeBlockTask.java#L38-L53 | train |
VoltDB/voltdb | src/frontend/org/voltdb/largequery/LargeBlockTask.java | LargeBlockTask.getReleaseTask | public static LargeBlockTask getReleaseTask(BlockId blockId) {
return new LargeBlockTask() {
@Override
public LargeBlockResponse call() throws Exception {
Exception theException = null;
try {
LargeBlockManager.getInstance().releaseBlock(blockId);
}
catch (Exception exc) {
theException = exc;
}
return new LargeBlockResponse(theException);
}
};
} | java | public static LargeBlockTask getReleaseTask(BlockId blockId) {
return new LargeBlockTask() {
@Override
public LargeBlockResponse call() throws Exception {
Exception theException = null;
try {
LargeBlockManager.getInstance().releaseBlock(blockId);
}
catch (Exception exc) {
theException = exc;
}
return new LargeBlockResponse(theException);
}
};
} | [
"public",
"static",
"LargeBlockTask",
"getReleaseTask",
"(",
"BlockId",
"blockId",
")",
"{",
"return",
"new",
"LargeBlockTask",
"(",
")",
"{",
"@",
"Override",
"public",
"LargeBlockResponse",
"call",
"(",
")",
"throws",
"Exception",
"{",
"Exception",
"theException... | Get a new "release" task
@param blockId The block id of the block to release
@return An instance of LargeBlockTask that will release a block | [
"Get",
"a",
"new",
"release",
"task"
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/largequery/LargeBlockTask.java#L60-L75 | train |
VoltDB/voltdb | src/frontend/org/voltdb/largequery/LargeBlockTask.java | LargeBlockTask.getLoadTask | public static LargeBlockTask getLoadTask(BlockId blockId, ByteBuffer block) {
return new LargeBlockTask() {
@Override
public LargeBlockResponse call() throws Exception {
Exception theException = null;
try {
LargeBlockManager.getInstance().loadBlock(blockId, block);
}
catch (Exception exc) {
theException = exc;
}
return new LargeBlockResponse(theException);
}
};
} | java | public static LargeBlockTask getLoadTask(BlockId blockId, ByteBuffer block) {
return new LargeBlockTask() {
@Override
public LargeBlockResponse call() throws Exception {
Exception theException = null;
try {
LargeBlockManager.getInstance().loadBlock(blockId, block);
}
catch (Exception exc) {
theException = exc;
}
return new LargeBlockResponse(theException);
}
};
} | [
"public",
"static",
"LargeBlockTask",
"getLoadTask",
"(",
"BlockId",
"blockId",
",",
"ByteBuffer",
"block",
")",
"{",
"return",
"new",
"LargeBlockTask",
"(",
")",
"{",
"@",
"Override",
"public",
"LargeBlockResponse",
"call",
"(",
")",
"throws",
"Exception",
"{",... | Get a new "load" task
@param blockId The block id of the block to load
@param block A ByteBuffer to write data intox
@return An instance of LargeBlockTask that will load a block | [
"Get",
"a",
"new",
"load",
"task"
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/largequery/LargeBlockTask.java#L83-L98 | train |
VoltDB/voltdb | src/frontend/org/voltcore/utils/Pair.java | Pair.of | public static <T, U> Pair<T, U> of(T x, U y) {
return new Pair<T, U>(x, y);
} | java | public static <T, U> Pair<T, U> of(T x, U y) {
return new Pair<T, U>(x, y);
} | [
"public",
"static",
"<",
"T",
",",
"U",
">",
"Pair",
"<",
"T",
",",
"U",
">",
"of",
"(",
"T",
"x",
",",
"U",
"y",
")",
"{",
"return",
"new",
"Pair",
"<",
"T",
",",
"U",
">",
"(",
"x",
",",
"y",
")",
";",
"}"
] | Convenience class method for constructing pairs using Java's generic type
inference. | [
"Convenience",
"class",
"method",
"for",
"constructing",
"pairs",
"using",
"Java",
"s",
"generic",
"type",
"inference",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltcore/utils/Pair.java#L105-L107 | train |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/Routine.java | Routine.newRoutine | public static Routine newRoutine(Method method) {
Routine routine = new Routine(SchemaObject.FUNCTION);
int offset = 0;
Class[] params = method.getParameterTypes();
String className = method.getDeclaringClass().getName();
StringBuffer sb = new StringBuffer();
sb.append("CLASSPATH:");
sb.append(method.getDeclaringClass().getName()).append('.');
sb.append(method.getName());
if (params.length > 0 && params[0].equals(java.sql.Connection.class)) {
offset = 1;
}
String name = sb.toString();
if (className.equals("org.hsqldb_voltpatches.Library")
|| className.equals("java.lang.Math")) {
routine.isLibraryRoutine = true;
}
for (int j = offset; j < params.length; j++) {
Type methodParamType = Type.getDefaultTypeWithSize(
Types.getParameterSQLTypeNumber(params[j]));
ColumnSchema param = new ColumnSchema(null, methodParamType,
!params[j].isPrimitive(),
false, null);
routine.addParameter(param);
}
routine.setLanguage(Routine.LANGUAGE_JAVA);
routine.setMethod(method);
routine.setMethodURL(name);
routine.setDataImpact(Routine.NO_SQL);
Type methodReturnType = Type.getDefaultTypeWithSize(
Types.getParameterSQLTypeNumber(method.getReturnType()));
routine.javaMethodWithConnection = offset == 1;;
routine.setReturnType(methodReturnType);
routine.resolve();
return routine;
} | java | public static Routine newRoutine(Method method) {
Routine routine = new Routine(SchemaObject.FUNCTION);
int offset = 0;
Class[] params = method.getParameterTypes();
String className = method.getDeclaringClass().getName();
StringBuffer sb = new StringBuffer();
sb.append("CLASSPATH:");
sb.append(method.getDeclaringClass().getName()).append('.');
sb.append(method.getName());
if (params.length > 0 && params[0].equals(java.sql.Connection.class)) {
offset = 1;
}
String name = sb.toString();
if (className.equals("org.hsqldb_voltpatches.Library")
|| className.equals("java.lang.Math")) {
routine.isLibraryRoutine = true;
}
for (int j = offset; j < params.length; j++) {
Type methodParamType = Type.getDefaultTypeWithSize(
Types.getParameterSQLTypeNumber(params[j]));
ColumnSchema param = new ColumnSchema(null, methodParamType,
!params[j].isPrimitive(),
false, null);
routine.addParameter(param);
}
routine.setLanguage(Routine.LANGUAGE_JAVA);
routine.setMethod(method);
routine.setMethodURL(name);
routine.setDataImpact(Routine.NO_SQL);
Type methodReturnType = Type.getDefaultTypeWithSize(
Types.getParameterSQLTypeNumber(method.getReturnType()));
routine.javaMethodWithConnection = offset == 1;;
routine.setReturnType(methodReturnType);
routine.resolve();
return routine;
} | [
"public",
"static",
"Routine",
"newRoutine",
"(",
"Method",
"method",
")",
"{",
"Routine",
"routine",
"=",
"new",
"Routine",
"(",
"SchemaObject",
".",
"FUNCTION",
")",
";",
"int",
"offset",
"=",
"0",
";",
"Class",
"[",
"]",
"params",
"=",
"method",
".",
... | Returns a new function Routine object based solely on a Java Method object. | [
"Returns",
"a",
"new",
"function",
"Routine",
"object",
"based",
"solely",
"on",
"a",
"Java",
"Method",
"object",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/Routine.java#L634-L681 | train |
VoltDB/voltdb | src/frontend/org/voltdb/sysprocs/saverestore/HashinatorSnapshotData.java | HashinatorSnapshotData.saveToBuffer | public ByteBuffer saveToBuffer(InstanceId instId)
throws IOException
{
if (instId == null) {
throw new IOException("Null instance ID.");
}
if (m_serData == null) {
throw new IOException("Uninitialized hashinator snapshot data.");
}
// Assume config data is the last field.
ByteBuffer buf = ByteBuffer.allocate(m_serData.length + OFFSET_DATA);
// Make sure the CRC starts at zero since those bytes figure into the CRC calculation.
buf.putLong(OFFSET_CRC, 0);
buf.putInt(OFFSET_INSTID_COORD, instId.getCoord());
buf.putLong(OFFSET_INSTID_TIMESTAMP, instId.getTimestamp());
buf.putLong(OFFSET_VERSION, m_version);
buf.position(OFFSET_DATA);
buf.put(m_serData);
// Finalize the CRC based on the entire buffer and reset the current position.
final PureJavaCrc32 crc = new PureJavaCrc32();
crc.update(buf.array());
buf.putLong(OFFSET_CRC, crc.getValue());
buf.rewind();
return buf;
} | java | public ByteBuffer saveToBuffer(InstanceId instId)
throws IOException
{
if (instId == null) {
throw new IOException("Null instance ID.");
}
if (m_serData == null) {
throw new IOException("Uninitialized hashinator snapshot data.");
}
// Assume config data is the last field.
ByteBuffer buf = ByteBuffer.allocate(m_serData.length + OFFSET_DATA);
// Make sure the CRC starts at zero since those bytes figure into the CRC calculation.
buf.putLong(OFFSET_CRC, 0);
buf.putInt(OFFSET_INSTID_COORD, instId.getCoord());
buf.putLong(OFFSET_INSTID_TIMESTAMP, instId.getTimestamp());
buf.putLong(OFFSET_VERSION, m_version);
buf.position(OFFSET_DATA);
buf.put(m_serData);
// Finalize the CRC based on the entire buffer and reset the current position.
final PureJavaCrc32 crc = new PureJavaCrc32();
crc.update(buf.array());
buf.putLong(OFFSET_CRC, crc.getValue());
buf.rewind();
return buf;
} | [
"public",
"ByteBuffer",
"saveToBuffer",
"(",
"InstanceId",
"instId",
")",
"throws",
"IOException",
"{",
"if",
"(",
"instId",
"==",
"null",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Null instance ID.\"",
")",
";",
"}",
"if",
"(",
"m_serData",
"==",
"nu... | Save to output buffer, including header and config data.
@return byte buffer ready to write to a file.
@throws I/O exception on failure | [
"Save",
"to",
"output",
"buffer",
"including",
"header",
"and",
"config",
"data",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/sysprocs/saverestore/HashinatorSnapshotData.java#L75-L102 | train |
VoltDB/voltdb | src/frontend/org/voltdb/sysprocs/saverestore/HashinatorSnapshotData.java | HashinatorSnapshotData.restoreFromBuffer | public InstanceId restoreFromBuffer(ByteBuffer buf)
throws IOException
{
buf.rewind();
// Assumes config data is the last field.
int dataSize = buf.remaining() - OFFSET_DATA;
if (dataSize <= 0) {
throw new IOException("Hashinator snapshot data is too small.");
}
// Get the CRC, zero out its buffer field, and compare to calculated CRC.
long crcHeader = buf.getLong(OFFSET_CRC);
buf.putLong(OFFSET_CRC, 0);
final PureJavaCrc32 crcBuffer = new PureJavaCrc32();
assert(buf.hasArray());
crcBuffer.update(buf.array());
if (crcHeader != crcBuffer.getValue()) {
throw new IOException("Hashinator snapshot data CRC mismatch.");
}
// Slurp the data.
int coord = buf.getInt(OFFSET_INSTID_COORD);
long timestamp = buf.getLong(OFFSET_INSTID_TIMESTAMP);
InstanceId instId = new InstanceId(coord, timestamp);
m_version = buf.getLong(OFFSET_VERSION);
m_serData = new byte[dataSize];
buf.position(OFFSET_DATA);
buf.get(m_serData);
return instId;
} | java | public InstanceId restoreFromBuffer(ByteBuffer buf)
throws IOException
{
buf.rewind();
// Assumes config data is the last field.
int dataSize = buf.remaining() - OFFSET_DATA;
if (dataSize <= 0) {
throw new IOException("Hashinator snapshot data is too small.");
}
// Get the CRC, zero out its buffer field, and compare to calculated CRC.
long crcHeader = buf.getLong(OFFSET_CRC);
buf.putLong(OFFSET_CRC, 0);
final PureJavaCrc32 crcBuffer = new PureJavaCrc32();
assert(buf.hasArray());
crcBuffer.update(buf.array());
if (crcHeader != crcBuffer.getValue()) {
throw new IOException("Hashinator snapshot data CRC mismatch.");
}
// Slurp the data.
int coord = buf.getInt(OFFSET_INSTID_COORD);
long timestamp = buf.getLong(OFFSET_INSTID_TIMESTAMP);
InstanceId instId = new InstanceId(coord, timestamp);
m_version = buf.getLong(OFFSET_VERSION);
m_serData = new byte[dataSize];
buf.position(OFFSET_DATA);
buf.get(m_serData);
return instId;
} | [
"public",
"InstanceId",
"restoreFromBuffer",
"(",
"ByteBuffer",
"buf",
")",
"throws",
"IOException",
"{",
"buf",
".",
"rewind",
"(",
")",
";",
"// Assumes config data is the last field.",
"int",
"dataSize",
"=",
"buf",
".",
"remaining",
"(",
")",
"-",
"OFFSET_DATA... | Restore and check hashinator config data.
@param buf input buffer
@return instance ID read from buffer
@throws I/O exception on failure | [
"Restore",
"and",
"check",
"hashinator",
"config",
"data",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/sysprocs/saverestore/HashinatorSnapshotData.java#L110-L141 | train |
VoltDB/voltdb | src/frontend/org/voltdb/sysprocs/saverestore/HashinatorSnapshotData.java | HashinatorSnapshotData.restoreFromFile | public void restoreFromFile(File file) throws IOException
{
byte[] rawData = new byte[(int) file.length()];
ByteBuffer bufData = null;
FileInputStream fis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
dis = new DataInputStream(fis);
dis.readFully(rawData);
bufData = ByteBuffer.wrap(rawData);
restoreFromBuffer(bufData);
}
finally {
if (dis != null) {
dis.close();
}
if (fis != null) {
fis.close();
}
}
} | java | public void restoreFromFile(File file) throws IOException
{
byte[] rawData = new byte[(int) file.length()];
ByteBuffer bufData = null;
FileInputStream fis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
dis = new DataInputStream(fis);
dis.readFully(rawData);
bufData = ByteBuffer.wrap(rawData);
restoreFromBuffer(bufData);
}
finally {
if (dis != null) {
dis.close();
}
if (fis != null) {
fis.close();
}
}
} | [
"public",
"void",
"restoreFromFile",
"(",
"File",
"file",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"rawData",
"=",
"new",
"byte",
"[",
"(",
"int",
")",
"file",
".",
"length",
"(",
")",
"]",
";",
"ByteBuffer",
"bufData",
"=",
"null",
";",
... | Restore and check hashinator config data from a file.
@param file hashinator config file
@param return the buffer with the raw data
@throws IOException | [
"Restore",
"and",
"check",
"hashinator",
"config",
"data",
"from",
"a",
"file",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/sysprocs/saverestore/HashinatorSnapshotData.java#L149-L170 | train |
VoltDB/voltdb | src/frontend/org/voltdb/compiler/VoltProjectBuilder.java | VoltProjectBuilder.createFileForSchema | public static File createFileForSchema(String ddlText) throws IOException {
File temp = File.createTempFile("literalschema", ".sql");
temp.deleteOnExit();
FileWriter out = new FileWriter(temp);
out.write(ddlText);
out.close();
return temp;
} | java | public static File createFileForSchema(String ddlText) throws IOException {
File temp = File.createTempFile("literalschema", ".sql");
temp.deleteOnExit();
FileWriter out = new FileWriter(temp);
out.write(ddlText);
out.close();
return temp;
} | [
"public",
"static",
"File",
"createFileForSchema",
"(",
"String",
"ddlText",
")",
"throws",
"IOException",
"{",
"File",
"temp",
"=",
"File",
".",
"createTempFile",
"(",
"\"literalschema\"",
",",
"\".sql\"",
")",
";",
"temp",
".",
"deleteOnExit",
"(",
")",
";",... | Creates a temporary file for the supplied schema text.
The file is not left open, and will be deleted upon process exit. | [
"Creates",
"a",
"temporary",
"file",
"for",
"the",
"supplied",
"schema",
"text",
".",
"The",
"file",
"is",
"not",
"left",
"open",
"and",
"will",
"be",
"deleted",
"upon",
"process",
"exit",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/compiler/VoltProjectBuilder.java#L491-L498 | train |
VoltDB/voltdb | src/frontend/org/voltdb/compiler/VoltProjectBuilder.java | VoltProjectBuilder.addLiteralSchema | public void addLiteralSchema(String ddlText) throws IOException {
File temp = createFileForSchema(ddlText);
addSchema(URLEncoder.encode(temp.getAbsolutePath(), "UTF-8"));
} | java | public void addLiteralSchema(String ddlText) throws IOException {
File temp = createFileForSchema(ddlText);
addSchema(URLEncoder.encode(temp.getAbsolutePath(), "UTF-8"));
} | [
"public",
"void",
"addLiteralSchema",
"(",
"String",
"ddlText",
")",
"throws",
"IOException",
"{",
"File",
"temp",
"=",
"createFileForSchema",
"(",
"ddlText",
")",
";",
"addSchema",
"(",
"URLEncoder",
".",
"encode",
"(",
"temp",
".",
"getAbsolutePath",
"(",
")... | Adds the supplied schema by creating a temp file for it. | [
"Adds",
"the",
"supplied",
"schema",
"by",
"creating",
"a",
"temp",
"file",
"for",
"it",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/compiler/VoltProjectBuilder.java#L503-L506 | train |
VoltDB/voltdb | src/frontend/org/voltdb/compiler/VoltProjectBuilder.java | VoltProjectBuilder.addStmtProcedure | public void addStmtProcedure(String name, String sql, String partitionInfoString) {
addProcedures(new ProcedureInfo(new String[0], name, sql,
ProcedurePartitionData.fromPartitionInfoString(partitionInfoString)));
} | java | public void addStmtProcedure(String name, String sql, String partitionInfoString) {
addProcedures(new ProcedureInfo(new String[0], name, sql,
ProcedurePartitionData.fromPartitionInfoString(partitionInfoString)));
} | [
"public",
"void",
"addStmtProcedure",
"(",
"String",
"name",
",",
"String",
"sql",
",",
"String",
"partitionInfoString",
")",
"{",
"addProcedures",
"(",
"new",
"ProcedureInfo",
"(",
"new",
"String",
"[",
"0",
"]",
",",
"name",
",",
"sql",
",",
"ProcedurePart... | compatible with old deprecated syntax for test ONLY | [
"compatible",
"with",
"old",
"deprecated",
"syntax",
"for",
"test",
"ONLY"
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/compiler/VoltProjectBuilder.java#L535-L538 | train |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringConverter.java | StringConverter.hexStringToByteArray | public static byte[] hexStringToByteArray(String s) throws IOException {
int l = s.length();
byte[] data = new byte[l / 2 + (l % 2)];
int n,
b = 0;
boolean high = true;
int i = 0;
for (int j = 0; j < l; j++) {
char c = s.charAt(j);
if (c == ' ') {
continue;
}
n = getNibble(c);
if (n == -1) {
throw new IOException(
"hexadecimal string contains non hex character"); //NOI18N
}
if (high) {
b = (n & 0xf) << 4;
high = false;
} else {
b += (n & 0xf);
high = true;
data[i++] = (byte) b;
}
}
if (!high) {
throw new IOException(
"hexadecimal string with odd number of characters"); //NOI18N
}
if (i < data.length) {
data = (byte[]) ArrayUtil.resizeArray(data, i);
}
return data;
} | java | public static byte[] hexStringToByteArray(String s) throws IOException {
int l = s.length();
byte[] data = new byte[l / 2 + (l % 2)];
int n,
b = 0;
boolean high = true;
int i = 0;
for (int j = 0; j < l; j++) {
char c = s.charAt(j);
if (c == ' ') {
continue;
}
n = getNibble(c);
if (n == -1) {
throw new IOException(
"hexadecimal string contains non hex character"); //NOI18N
}
if (high) {
b = (n & 0xf) << 4;
high = false;
} else {
b += (n & 0xf);
high = true;
data[i++] = (byte) b;
}
}
if (!high) {
throw new IOException(
"hexadecimal string with odd number of characters"); //NOI18N
}
if (i < data.length) {
data = (byte[]) ArrayUtil.resizeArray(data, i);
}
return data;
} | [
"public",
"static",
"byte",
"[",
"]",
"hexStringToByteArray",
"(",
"String",
"s",
")",
"throws",
"IOException",
"{",
"int",
"l",
"=",
"s",
".",
"length",
"(",
")",
";",
"byte",
"[",
"]",
"data",
"=",
"new",
"byte",
"[",
"l",
"/",
"2",
"+",
"(",
"... | Converts a hexadecimal string into a byte array
@param s hexadecimal string
@return byte array for the hex string
@throws IOException | [
"Converts",
"a",
"hexadecimal",
"string",
"into",
"a",
"byte",
"array"
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringConverter.java#L122-L165 | train |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringConverter.java | StringConverter.sqlBitStringToBitMap | public static BitMap sqlBitStringToBitMap(String s) throws IOException {
int l = s.length();
int n;
int bitIndex = 0;
BitMap map = new BitMap(l);
for (int j = 0; j < l; j++) {
char c = s.charAt(j);
if (c == ' ') {
continue;
}
n = getNibble(c);
if (n != 0 && n != 1) {
throw new IOException(
"hexadecimal string contains non hex character"); //NOI18N
}
if (n == 1) {
map.set(bitIndex);
}
bitIndex++;
}
map.setSize(bitIndex);
return map;
} | java | public static BitMap sqlBitStringToBitMap(String s) throws IOException {
int l = s.length();
int n;
int bitIndex = 0;
BitMap map = new BitMap(l);
for (int j = 0; j < l; j++) {
char c = s.charAt(j);
if (c == ' ') {
continue;
}
n = getNibble(c);
if (n != 0 && n != 1) {
throw new IOException(
"hexadecimal string contains non hex character"); //NOI18N
}
if (n == 1) {
map.set(bitIndex);
}
bitIndex++;
}
map.setSize(bitIndex);
return map;
} | [
"public",
"static",
"BitMap",
"sqlBitStringToBitMap",
"(",
"String",
"s",
")",
"throws",
"IOException",
"{",
"int",
"l",
"=",
"s",
".",
"length",
"(",
")",
";",
"int",
"n",
";",
"int",
"bitIndex",
"=",
"0",
";",
"BitMap",
"map",
"=",
"new",
"BitMap",
... | Compacts a bit string into a BitMap
@param s bit string
@return byte array for the hex string
@throws IOException | [
"Compacts",
"a",
"bit",
"string",
"into",
"a",
"BitMap"
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringConverter.java#L176-L207 | train |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringConverter.java | StringConverter.byteArrayToBitString | public static String byteArrayToBitString(byte[] bytes, int bitCount) {
char[] s = new char[bitCount];
for (int j = 0; j < bitCount; j++) {
byte b = bytes[j / 8];
s[j] = BitMap.isSet(b, j % 8) ? '1'
: '0';
}
return new String(s);
} | java | public static String byteArrayToBitString(byte[] bytes, int bitCount) {
char[] s = new char[bitCount];
for (int j = 0; j < bitCount; j++) {
byte b = bytes[j / 8];
s[j] = BitMap.isSet(b, j % 8) ? '1'
: '0';
}
return new String(s);
} | [
"public",
"static",
"String",
"byteArrayToBitString",
"(",
"byte",
"[",
"]",
"bytes",
",",
"int",
"bitCount",
")",
"{",
"char",
"[",
"]",
"s",
"=",
"new",
"char",
"[",
"bitCount",
"]",
";",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"bitCount... | Converts a byte array into a bit string
@param bytes byte array
@param bitCount number of bits
@return hex string | [
"Converts",
"a",
"byte",
"array",
"into",
"a",
"bit",
"string"
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringConverter.java#L270-L282 | train |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringConverter.java | StringConverter.byteArrayToSQLBitString | public static String byteArrayToSQLBitString(byte[] bytes, int bitCount) {
char[] s = new char[bitCount + 3];
s[0] = 'B';
s[1] = '\'';
int pos = 2;
for (int j = 0; j < bitCount; j++) {
byte b = bytes[j / 8];
s[pos++] = BitMap.isSet(b, j % 8) ? '1'
: '0';
}
s[pos] = '\'';
return new String(s);
} | java | public static String byteArrayToSQLBitString(byte[] bytes, int bitCount) {
char[] s = new char[bitCount + 3];
s[0] = 'B';
s[1] = '\'';
int pos = 2;
for (int j = 0; j < bitCount; j++) {
byte b = bytes[j / 8];
s[pos++] = BitMap.isSet(b, j % 8) ? '1'
: '0';
}
s[pos] = '\'';
return new String(s);
} | [
"public",
"static",
"String",
"byteArrayToSQLBitString",
"(",
"byte",
"[",
"]",
"bytes",
",",
"int",
"bitCount",
")",
"{",
"char",
"[",
"]",
"s",
"=",
"new",
"char",
"[",
"bitCount",
"+",
"3",
"]",
";",
"s",
"[",
"0",
"]",
"=",
"'",
"'",
";",
"s"... | Converts a byte array into an SQL binary string
@param bytes byte array
@param bitCount number of bits
@return hex string | [
"Converts",
"a",
"byte",
"array",
"into",
"an",
"SQL",
"binary",
"string"
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringConverter.java#L292-L311 | train |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringConverter.java | StringConverter.writeHexBytes | public static void writeHexBytes(byte[] o, int from, byte[] b) {
int len = b.length;
for (int i = 0; i < len; i++) {
int c = ((int) b[i]) & 0xff;
o[from++] = HEXBYTES[c >> 4 & 0xf];
o[from++] = HEXBYTES[c & 0xf];
}
} | java | public static void writeHexBytes(byte[] o, int from, byte[] b) {
int len = b.length;
for (int i = 0; i < len; i++) {
int c = ((int) b[i]) & 0xff;
o[from++] = HEXBYTES[c >> 4 & 0xf];
o[from++] = HEXBYTES[c & 0xf];
}
} | [
"public",
"static",
"void",
"writeHexBytes",
"(",
"byte",
"[",
"]",
"o",
",",
"int",
"from",
",",
"byte",
"[",
"]",
"b",
")",
"{",
"int",
"len",
"=",
"b",
".",
"length",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
... | Converts a byte array into hexadecimal characters which are written as
ASCII to the given output stream.
@param o output array
@param from offset into output array
@param b input array | [
"Converts",
"a",
"byte",
"array",
"into",
"hexadecimal",
"characters",
"which",
"are",
"written",
"as",
"ASCII",
"to",
"the",
"given",
"output",
"stream",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringConverter.java#L321-L331 | train |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringConverter.java | StringConverter.stringToUTFBytes | public static int stringToUTFBytes(String str,
HsqlByteArrayOutputStream out) {
int strlen = str.length();
int c,
count = 0;
if (out.count + strlen + 8 > out.buffer.length) {
out.ensureRoom(strlen + 8);
}
char[] arr = str.toCharArray();
for (int i = 0; i < strlen; i++) {
c = arr[i];
if (c >= 0x0001 && c <= 0x007F) {
out.buffer[out.count++] = (byte) c;
count++;
} else if (c > 0x07FF) {
out.buffer[out.count++] = (byte) (0xE0 | ((c >> 12) & 0x0F));
out.buffer[out.count++] = (byte) (0x80 | ((c >> 6) & 0x3F));
out.buffer[out.count++] = (byte) (0x80 | ((c >> 0) & 0x3F));
count += 3;
} else {
out.buffer[out.count++] = (byte) (0xC0 | ((c >> 6) & 0x1F));
out.buffer[out.count++] = (byte) (0x80 | ((c >> 0) & 0x3F));
count += 2;
}
if (out.count + 8 > out.buffer.length) {
out.ensureRoom(strlen - i + 8);
}
}
return count;
} | java | public static int stringToUTFBytes(String str,
HsqlByteArrayOutputStream out) {
int strlen = str.length();
int c,
count = 0;
if (out.count + strlen + 8 > out.buffer.length) {
out.ensureRoom(strlen + 8);
}
char[] arr = str.toCharArray();
for (int i = 0; i < strlen; i++) {
c = arr[i];
if (c >= 0x0001 && c <= 0x007F) {
out.buffer[out.count++] = (byte) c;
count++;
} else if (c > 0x07FF) {
out.buffer[out.count++] = (byte) (0xE0 | ((c >> 12) & 0x0F));
out.buffer[out.count++] = (byte) (0x80 | ((c >> 6) & 0x3F));
out.buffer[out.count++] = (byte) (0x80 | ((c >> 0) & 0x3F));
count += 3;
} else {
out.buffer[out.count++] = (byte) (0xC0 | ((c >> 6) & 0x1F));
out.buffer[out.count++] = (byte) (0x80 | ((c >> 0) & 0x3F));
count += 2;
}
if (out.count + 8 > out.buffer.length) {
out.ensureRoom(strlen - i + 8);
}
}
return count;
} | [
"public",
"static",
"int",
"stringToUTFBytes",
"(",
"String",
"str",
",",
"HsqlByteArrayOutputStream",
"out",
")",
"{",
"int",
"strlen",
"=",
"str",
".",
"length",
"(",
")",
";",
"int",
"c",
",",
"count",
"=",
"0",
";",
"if",
"(",
"out",
".",
"count",
... | Writes a string to the specified DataOutput using UTF-8 encoding in a
machine-independent manner.
@param str a string to be written.
@param out destination to write to
@return The number of bytes written out. | [
"Writes",
"a",
"string",
"to",
"the",
"specified",
"DataOutput",
"using",
"UTF",
"-",
"8",
"encoding",
"in",
"a",
"machine",
"-",
"independent",
"manner",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringConverter.java#L567-L604 | train |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringConverter.java | StringConverter.inputStreamToString | public static String inputStreamToString(InputStream x,
String encoding) throws IOException {
InputStreamReader in = new InputStreamReader(x, encoding);
StringWriter writer = new StringWriter();
int blocksize = 8 * 1024;
char[] buffer = new char[blocksize];
for (;;) {
int read = in.read(buffer);
if (read == -1) {
break;
}
writer.write(buffer, 0, read);
}
writer.close();
return writer.toString();
} | java | public static String inputStreamToString(InputStream x,
String encoding) throws IOException {
InputStreamReader in = new InputStreamReader(x, encoding);
StringWriter writer = new StringWriter();
int blocksize = 8 * 1024;
char[] buffer = new char[blocksize];
for (;;) {
int read = in.read(buffer);
if (read == -1) {
break;
}
writer.write(buffer, 0, read);
}
writer.close();
return writer.toString();
} | [
"public",
"static",
"String",
"inputStreamToString",
"(",
"InputStream",
"x",
",",
"String",
"encoding",
")",
"throws",
"IOException",
"{",
"InputStreamReader",
"in",
"=",
"new",
"InputStreamReader",
"(",
"x",
",",
"encoding",
")",
";",
"StringWriter",
"writer",
... | Using a Reader and a Writer, returns a String from an InputStream.
Method based on Hypersonic Code
@param x InputStream to read from
@throws IOException
@return a Java string | [
"Using",
"a",
"Reader",
"and",
"a",
"Writer",
"returns",
"a",
"String",
"from",
"an",
"InputStream",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringConverter.java#L636-L657 | train |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringConverter.java | StringConverter.count | static int count(final String s, final char c) {
int pos = 0;
int count = 0;
if (s != null) {
while ((pos = s.indexOf(c, pos)) > -1) {
count++;
pos++;
}
}
return count;
} | java | static int count(final String s, final char c) {
int pos = 0;
int count = 0;
if (s != null) {
while ((pos = s.indexOf(c, pos)) > -1) {
count++;
pos++;
}
}
return count;
} | [
"static",
"int",
"count",
"(",
"final",
"String",
"s",
",",
"final",
"char",
"c",
")",
"{",
"int",
"pos",
"=",
"0",
";",
"int",
"count",
"=",
"0",
";",
"if",
"(",
"s",
"!=",
"null",
")",
"{",
"while",
"(",
"(",
"pos",
"=",
"s",
".",
"indexOf"... | Counts Character c in String s
@param s Java string
@param c character to count
@return int count | [
"Counts",
"Character",
"c",
"in",
"String",
"s"
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/lib/StringConverter.java#L712-L725 | train |
VoltDB/voltdb | third_party/java/src/org/apache/zookeeper_voltpatches/jmx/ManagedUtil.java | ManagedUtil.registerLog4jMBeans | public static void registerLog4jMBeans() throws JMException {
if (Boolean.getBoolean("zookeeper.jmx.log4j.disable") == true) {
return;
}
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
// Create and Register the top level Log4J MBean
HierarchyDynamicMBean hdm = new HierarchyDynamicMBean();
ObjectName mbo = new ObjectName("log4j:hiearchy=default");
mbs.registerMBean(hdm, mbo);
// Add the root logger to the Hierarchy MBean
Logger rootLogger = Logger.getRootLogger();
hdm.addLoggerMBean(rootLogger.getName());
// Get each logger from the Log4J Repository and add it to
// the Hierarchy MBean created above.
LoggerRepository r = LogManager.getLoggerRepository();
Enumeration enumer = r.getCurrentLoggers();
Logger logger = null;
while (enumer.hasMoreElements()) {
logger = (Logger) enumer.nextElement();
hdm.addLoggerMBean(logger.getName());
}
} | java | public static void registerLog4jMBeans() throws JMException {
if (Boolean.getBoolean("zookeeper.jmx.log4j.disable") == true) {
return;
}
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
// Create and Register the top level Log4J MBean
HierarchyDynamicMBean hdm = new HierarchyDynamicMBean();
ObjectName mbo = new ObjectName("log4j:hiearchy=default");
mbs.registerMBean(hdm, mbo);
// Add the root logger to the Hierarchy MBean
Logger rootLogger = Logger.getRootLogger();
hdm.addLoggerMBean(rootLogger.getName());
// Get each logger from the Log4J Repository and add it to
// the Hierarchy MBean created above.
LoggerRepository r = LogManager.getLoggerRepository();
Enumeration enumer = r.getCurrentLoggers();
Logger logger = null;
while (enumer.hasMoreElements()) {
logger = (Logger) enumer.nextElement();
hdm.addLoggerMBean(logger.getName());
}
} | [
"public",
"static",
"void",
"registerLog4jMBeans",
"(",
")",
"throws",
"JMException",
"{",
"if",
"(",
"Boolean",
".",
"getBoolean",
"(",
"\"zookeeper.jmx.log4j.disable\"",
")",
"==",
"true",
")",
"{",
"return",
";",
"}",
"MBeanServer",
"mbs",
"=",
"ManagementFac... | Register the log4j JMX mbeans. Set environment variable
"zookeeper.jmx.log4j.disable" to true to disable registration.
@see http://logging.apache.org/log4j/1.2/apidocs/index.html?org/apache/log4j/jmx/package-summary.html
@throws JMException if registration fails | [
"Register",
"the",
"log4j",
"JMX",
"mbeans",
".",
"Set",
"environment",
"variable",
"zookeeper",
".",
"jmx",
".",
"log4j",
".",
"disable",
"to",
"true",
"to",
"disable",
"registration",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/apache/zookeeper_voltpatches/jmx/ManagedUtil.java#L43-L70 | train |
VoltDB/voltdb | third_party/java/src/org/apache/zookeeper_voltpatches/ZooKeeper.java | ZooKeeper.create | public void create(final String path, byte data[], List<ACL> acl,
CreateMode createMode, StringCallback cb, Object ctx) {
verbotenThreadCheck();
final String clientPath = path;
PathUtils.validatePath(clientPath, createMode.isSequential());
final String serverPath = prependChroot(clientPath);
RequestHeader h = new RequestHeader();
h.setType(ZooDefs.OpCode.create);
CreateRequest request = new CreateRequest();
CreateResponse response = new CreateResponse();
ReplyHeader r = new ReplyHeader();
request.setData(data);
request.setFlags(createMode.toFlag());
request.setPath(serverPath);
request.setAcl(acl);
cnxn.queuePacket(h, r, request, response, cb, clientPath, serverPath,
ctx, null);
} | java | public void create(final String path, byte data[], List<ACL> acl,
CreateMode createMode, StringCallback cb, Object ctx) {
verbotenThreadCheck();
final String clientPath = path;
PathUtils.validatePath(clientPath, createMode.isSequential());
final String serverPath = prependChroot(clientPath);
RequestHeader h = new RequestHeader();
h.setType(ZooDefs.OpCode.create);
CreateRequest request = new CreateRequest();
CreateResponse response = new CreateResponse();
ReplyHeader r = new ReplyHeader();
request.setData(data);
request.setFlags(createMode.toFlag());
request.setPath(serverPath);
request.setAcl(acl);
cnxn.queuePacket(h, r, request, response, cb, clientPath, serverPath,
ctx, null);
} | [
"public",
"void",
"create",
"(",
"final",
"String",
"path",
",",
"byte",
"data",
"[",
"]",
",",
"List",
"<",
"ACL",
">",
"acl",
",",
"CreateMode",
"createMode",
",",
"StringCallback",
"cb",
",",
"Object",
"ctx",
")",
"{",
"verbotenThreadCheck",
"(",
")",... | The Asynchronous version of create. The request doesn't actually until
the asynchronous callback is called.
@see #create(String, byte[], List, CreateMode) | [
"The",
"Asynchronous",
"version",
"of",
"create",
".",
"The",
"request",
"doesn",
"t",
"actually",
"until",
"the",
"asynchronous",
"callback",
"is",
"called",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/apache/zookeeper_voltpatches/ZooKeeper.java#L683-L702 | train |
VoltDB/voltdb | third_party/java/src/org/apache/zookeeper_voltpatches/ZooKeeper.java | ZooKeeper.delete | public void delete(final String path, int version, VoidCallback cb,
Object ctx) {
verbotenThreadCheck();
final String clientPath = path;
PathUtils.validatePath(clientPath);
final String serverPath;
// maintain semantics even in chroot case
// specifically - root cannot be deleted
// I think this makes sense even in chroot case.
if (clientPath.equals("/")) {
// a bit of a hack, but delete(/) will never succeed and ensures
// that the same semantics are maintained
serverPath = clientPath;
} else {
serverPath = prependChroot(clientPath);
}
RequestHeader h = new RequestHeader();
h.setType(ZooDefs.OpCode.delete);
DeleteRequest request = new DeleteRequest();
request.setPath(serverPath);
request.setVersion(version);
cnxn.queuePacket(h, new ReplyHeader(), request, null, cb, clientPath,
serverPath, ctx, null);
} | java | public void delete(final String path, int version, VoidCallback cb,
Object ctx) {
verbotenThreadCheck();
final String clientPath = path;
PathUtils.validatePath(clientPath);
final String serverPath;
// maintain semantics even in chroot case
// specifically - root cannot be deleted
// I think this makes sense even in chroot case.
if (clientPath.equals("/")) {
// a bit of a hack, but delete(/) will never succeed and ensures
// that the same semantics are maintained
serverPath = clientPath;
} else {
serverPath = prependChroot(clientPath);
}
RequestHeader h = new RequestHeader();
h.setType(ZooDefs.OpCode.delete);
DeleteRequest request = new DeleteRequest();
request.setPath(serverPath);
request.setVersion(version);
cnxn.queuePacket(h, new ReplyHeader(), request, null, cb, clientPath,
serverPath, ctx, null);
} | [
"public",
"void",
"delete",
"(",
"final",
"String",
"path",
",",
"int",
"version",
",",
"VoidCallback",
"cb",
",",
"Object",
"ctx",
")",
"{",
"verbotenThreadCheck",
"(",
")",
";",
"final",
"String",
"clientPath",
"=",
"path",
";",
"PathUtils",
".",
"valida... | The Asynchronous version of delete. The request doesn't actually until
the asynchronous callback is called.
@see #delete(String, int) | [
"The",
"Asynchronous",
"version",
"of",
"delete",
".",
"The",
"request",
"doesn",
"t",
"actually",
"until",
"the",
"asynchronous",
"callback",
"is",
"called",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/apache/zookeeper_voltpatches/ZooKeeper.java#L770-L796 | train |
VoltDB/voltdb | third_party/java/src/org/apache/zookeeper_voltpatches/ZooKeeper.java | ZooKeeper.setData | public void setData(final String path, byte data[], int version,
StatCallback cb, Object ctx) {
verbotenThreadCheck();
final String clientPath = path;
PathUtils.validatePath(clientPath);
final String serverPath = prependChroot(clientPath);
RequestHeader h = new RequestHeader();
h.setType(ZooDefs.OpCode.setData);
SetDataRequest request = new SetDataRequest();
request.setPath(serverPath);
request.setData(data);
request.setVersion(version);
SetDataResponse response = new SetDataResponse();
cnxn.queuePacket(h, new ReplyHeader(), request, response, cb,
clientPath, serverPath, ctx, null);
} | java | public void setData(final String path, byte data[], int version,
StatCallback cb, Object ctx) {
verbotenThreadCheck();
final String clientPath = path;
PathUtils.validatePath(clientPath);
final String serverPath = prependChroot(clientPath);
RequestHeader h = new RequestHeader();
h.setType(ZooDefs.OpCode.setData);
SetDataRequest request = new SetDataRequest();
request.setPath(serverPath);
request.setData(data);
request.setVersion(version);
SetDataResponse response = new SetDataResponse();
cnxn.queuePacket(h, new ReplyHeader(), request, response, cb,
clientPath, serverPath, ctx, null);
} | [
"public",
"void",
"setData",
"(",
"final",
"String",
"path",
",",
"byte",
"data",
"[",
"]",
",",
"int",
"version",
",",
"StatCallback",
"cb",
",",
"Object",
"ctx",
")",
"{",
"verbotenThreadCheck",
"(",
")",
";",
"final",
"String",
"clientPath",
"=",
"pat... | The Asynchronous version of setData. The request doesn't actually until
the asynchronous callback is called.
@see #setData(String, byte[], int) | [
"The",
"Asynchronous",
"version",
"of",
"setData",
".",
"The",
"request",
"doesn",
"t",
"actually",
"until",
"the",
"asynchronous",
"callback",
"is",
"called",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/apache/zookeeper_voltpatches/ZooKeeper.java#L1103-L1120 | train |
VoltDB/voltdb | third_party/java/src/org/apache/zookeeper_voltpatches/ZooKeeper.java | ZooKeeper.getACL | public void getACL(final String path, Stat stat, ACLCallback cb, Object ctx) {
verbotenThreadCheck();
final String clientPath = path;
PathUtils.validatePath(clientPath);
final String serverPath = prependChroot(clientPath);
RequestHeader h = new RequestHeader();
h.setType(ZooDefs.OpCode.getACL);
GetACLRequest request = new GetACLRequest();
request.setPath(serverPath);
GetACLResponse response = new GetACLResponse();
cnxn.queuePacket(h, new ReplyHeader(), request, response, cb,
clientPath, serverPath, ctx, null);
} | java | public void getACL(final String path, Stat stat, ACLCallback cb, Object ctx) {
verbotenThreadCheck();
final String clientPath = path;
PathUtils.validatePath(clientPath);
final String serverPath = prependChroot(clientPath);
RequestHeader h = new RequestHeader();
h.setType(ZooDefs.OpCode.getACL);
GetACLRequest request = new GetACLRequest();
request.setPath(serverPath);
GetACLResponse response = new GetACLResponse();
cnxn.queuePacket(h, new ReplyHeader(), request, response, cb,
clientPath, serverPath, ctx, null);
} | [
"public",
"void",
"getACL",
"(",
"final",
"String",
"path",
",",
"Stat",
"stat",
",",
"ACLCallback",
"cb",
",",
"Object",
"ctx",
")",
"{",
"verbotenThreadCheck",
"(",
")",
";",
"final",
"String",
"clientPath",
"=",
"path",
";",
"PathUtils",
".",
"validateP... | The Asynchronous version of getACL. The request doesn't actually until
the asynchronous callback is called.
@see #getACL(String, Stat) | [
"The",
"Asynchronous",
"version",
"of",
"getACL",
".",
"The",
"request",
"doesn",
"t",
"actually",
"until",
"the",
"asynchronous",
"callback",
"is",
"called",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/apache/zookeeper_voltpatches/ZooKeeper.java#L1168-L1182 | train |
VoltDB/voltdb | third_party/java/src/org/apache/zookeeper_voltpatches/ZooKeeper.java | ZooKeeper.setACL | public void setACL(final String path, List<ACL> acl, int version,
StatCallback cb, Object ctx) {
verbotenThreadCheck();
final String clientPath = path;
PathUtils.validatePath(clientPath);
final String serverPath = prependChroot(clientPath);
RequestHeader h = new RequestHeader();
h.setType(ZooDefs.OpCode.setACL);
SetACLRequest request = new SetACLRequest();
request.setPath(serverPath);
request.setAcl(acl);
request.setVersion(version);
SetACLResponse response = new SetACLResponse();
cnxn.queuePacket(h, new ReplyHeader(), request, response, cb,
clientPath, serverPath, ctx, null);
} | java | public void setACL(final String path, List<ACL> acl, int version,
StatCallback cb, Object ctx) {
verbotenThreadCheck();
final String clientPath = path;
PathUtils.validatePath(clientPath);
final String serverPath = prependChroot(clientPath);
RequestHeader h = new RequestHeader();
h.setType(ZooDefs.OpCode.setACL);
SetACLRequest request = new SetACLRequest();
request.setPath(serverPath);
request.setAcl(acl);
request.setVersion(version);
SetACLResponse response = new SetACLResponse();
cnxn.queuePacket(h, new ReplyHeader(), request, response, cb,
clientPath, serverPath, ctx, null);
} | [
"public",
"void",
"setACL",
"(",
"final",
"String",
"path",
",",
"List",
"<",
"ACL",
">",
"acl",
",",
"int",
"version",
",",
"StatCallback",
"cb",
",",
"Object",
"ctx",
")",
"{",
"verbotenThreadCheck",
"(",
")",
";",
"final",
"String",
"clientPath",
"=",... | The Asynchronous version of setACL. The request doesn't actually until
the asynchronous callback is called.
@see #setACL(String, List, int) | [
"The",
"Asynchronous",
"version",
"of",
"setACL",
".",
"The",
"request",
"doesn",
"t",
"actually",
"until",
"the",
"asynchronous",
"callback",
"is",
"called",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/apache/zookeeper_voltpatches/ZooKeeper.java#L1240-L1257 | train |
VoltDB/voltdb | third_party/java/src/org/apache/zookeeper_voltpatches/ZooKeeper.java | ZooKeeper.sync | public void sync(final String path, VoidCallback cb, Object ctx) {
verbotenThreadCheck();
final String clientPath = path;
PathUtils.validatePath(clientPath);
final String serverPath = prependChroot(clientPath);
RequestHeader h = new RequestHeader();
h.setType(ZooDefs.OpCode.sync);
SyncRequest request = new SyncRequest();
SyncResponse response = new SyncResponse();
request.setPath(serverPath);
cnxn.queuePacket(h, new ReplyHeader(), request, response, cb,
clientPath, serverPath, ctx, null);
} | java | public void sync(final String path, VoidCallback cb, Object ctx) {
verbotenThreadCheck();
final String clientPath = path;
PathUtils.validatePath(clientPath);
final String serverPath = prependChroot(clientPath);
RequestHeader h = new RequestHeader();
h.setType(ZooDefs.OpCode.sync);
SyncRequest request = new SyncRequest();
SyncResponse response = new SyncResponse();
request.setPath(serverPath);
cnxn.queuePacket(h, new ReplyHeader(), request, response, cb,
clientPath, serverPath, ctx, null);
} | [
"public",
"void",
"sync",
"(",
"final",
"String",
"path",
",",
"VoidCallback",
"cb",
",",
"Object",
"ctx",
")",
"{",
"verbotenThreadCheck",
"(",
")",
";",
"final",
"String",
"clientPath",
"=",
"path",
";",
"PathUtils",
".",
"validatePath",
"(",
"clientPath",... | Asynchronous sync. Flushes channel between process and leader.
@param path
@param cb
a handler for the callback
@param ctx
context to be provided to the callback
@throws IllegalArgumentException
if an invalid path is specified | [
"Asynchronous",
"sync",
".",
"Flushes",
"channel",
"between",
"process",
"and",
"leader",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/apache/zookeeper_voltpatches/ZooKeeper.java#L1529-L1543 | train |
VoltDB/voltdb | src/frontend/org/voltdb/client/ClientImpl.java | ClientImpl.callProcedureWithTimeout | @Override
public final boolean callProcedureWithTimeout(
ProcedureCallback callback,
int batchTimeout,
String procName,
Object... parameters)
throws IOException, NoConnectionsException
{
//Time unit doesn't matter in this case since the timeout isn't being specifie
return callProcedureWithClientTimeout(
callback,
batchTimeout,
false,
procName,
Distributer.USE_DEFAULT_CLIENT_TIMEOUT,
TimeUnit.NANOSECONDS,
parameters);
} | java | @Override
public final boolean callProcedureWithTimeout(
ProcedureCallback callback,
int batchTimeout,
String procName,
Object... parameters)
throws IOException, NoConnectionsException
{
//Time unit doesn't matter in this case since the timeout isn't being specifie
return callProcedureWithClientTimeout(
callback,
batchTimeout,
false,
procName,
Distributer.USE_DEFAULT_CLIENT_TIMEOUT,
TimeUnit.NANOSECONDS,
parameters);
} | [
"@",
"Override",
"public",
"final",
"boolean",
"callProcedureWithTimeout",
"(",
"ProcedureCallback",
"callback",
",",
"int",
"batchTimeout",
",",
"String",
"procName",
",",
"Object",
"...",
"parameters",
")",
"throws",
"IOException",
",",
"NoConnectionsException",
"{"... | Asynchronously invoke a procedure call with timeout.
@param callback TransactionCallback that will be invoked with procedure results.
@param batchTimeout procedure invocation batch timeout.
@param procName class name (not qualified by package) of the procedure to execute.
@param parameters vararg list of procedure's parameter values.
@return True if the procedure was queued and false otherwise | [
"Asynchronously",
"invoke",
"a",
"procedure",
"call",
"with",
"timeout",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/client/ClientImpl.java#L354-L371 | train |
VoltDB/voltdb | src/frontend/org/voltdb/client/ClientImpl.java | ClientImpl.getUpdateCatalogParams | private Object[] getUpdateCatalogParams(File catalogPath, File deploymentPath)
throws IOException {
Object[] params = new Object[2];
if (catalogPath != null) {
params[0] = ClientUtils.fileToBytes(catalogPath);
}
else {
params[0] = null;
}
if (deploymentPath != null) {
params[1] = new String(ClientUtils.fileToBytes(deploymentPath), Constants.UTF8ENCODING);
}
else {
params[1] = null;
}
return params;
} | java | private Object[] getUpdateCatalogParams(File catalogPath, File deploymentPath)
throws IOException {
Object[] params = new Object[2];
if (catalogPath != null) {
params[0] = ClientUtils.fileToBytes(catalogPath);
}
else {
params[0] = null;
}
if (deploymentPath != null) {
params[1] = new String(ClientUtils.fileToBytes(deploymentPath), Constants.UTF8ENCODING);
}
else {
params[1] = null;
}
return params;
} | [
"private",
"Object",
"[",
"]",
"getUpdateCatalogParams",
"(",
"File",
"catalogPath",
",",
"File",
"deploymentPath",
")",
"throws",
"IOException",
"{",
"Object",
"[",
"]",
"params",
"=",
"new",
"Object",
"[",
"2",
"]",
";",
"if",
"(",
"catalogPath",
"!=",
"... | Serializes catalog and deployment file for UpdateApplicationCatalog.
Catalog is serialized into byte array, deployment file is serialized into
string.
@param catalogPath
@param deploymentPath
@return Parameters that can be passed to UpdateApplicationCatalog
@throws IOException If either of the files cannot be read | [
"Serializes",
"catalog",
"and",
"deployment",
"file",
"for",
"UpdateApplicationCatalog",
".",
"Catalog",
"is",
"serialized",
"into",
"byte",
"array",
"deployment",
"file",
"is",
"serialized",
"into",
"string",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/client/ClientImpl.java#L547-L563 | train |
VoltDB/voltdb | src/frontend/org/voltdb/client/ClientImpl.java | ClientImpl.close | @Override
public void close() throws InterruptedException {
if (m_blessedThreadIds.contains(Thread.currentThread().getId())) {
throw new RuntimeException("Can't invoke backpressureBarrier from within the client callback thread " +
" without deadlocking the client library");
}
m_isShutdown = true;
synchronized (m_backpressureLock) {
m_backpressureLock.notifyAll();
}
if (m_reconnectStatusListener != null) {
m_distributer.removeClientStatusListener(m_reconnectStatusListener);
m_reconnectStatusListener.close();
}
if (m_ex != null) {
m_ex.shutdown();
if (CoreUtils.isJunitTest()) {
m_ex.awaitTermination(1, TimeUnit.SECONDS);
} else {
m_ex.awaitTermination(365, TimeUnit.DAYS);
}
}
m_distributer.shutdown();
ClientFactory.decreaseClientNum();
} | java | @Override
public void close() throws InterruptedException {
if (m_blessedThreadIds.contains(Thread.currentThread().getId())) {
throw new RuntimeException("Can't invoke backpressureBarrier from within the client callback thread " +
" without deadlocking the client library");
}
m_isShutdown = true;
synchronized (m_backpressureLock) {
m_backpressureLock.notifyAll();
}
if (m_reconnectStatusListener != null) {
m_distributer.removeClientStatusListener(m_reconnectStatusListener);
m_reconnectStatusListener.close();
}
if (m_ex != null) {
m_ex.shutdown();
if (CoreUtils.isJunitTest()) {
m_ex.awaitTermination(1, TimeUnit.SECONDS);
} else {
m_ex.awaitTermination(365, TimeUnit.DAYS);
}
}
m_distributer.shutdown();
ClientFactory.decreaseClientNum();
} | [
"@",
"Override",
"public",
"void",
"close",
"(",
")",
"throws",
"InterruptedException",
"{",
"if",
"(",
"m_blessedThreadIds",
".",
"contains",
"(",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getId",
"(",
")",
")",
")",
"{",
"throw",
"new",
"RuntimeExc... | Shutdown the client closing all network connections and release
all memory resources.
@throws InterruptedException | [
"Shutdown",
"the",
"client",
"closing",
"all",
"network",
"connections",
"and",
"release",
"all",
"memory",
"resources",
"."
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/client/ClientImpl.java#L622-L648 | train |
VoltDB/voltdb | src/frontend/org/voltdb/client/ClientImpl.java | ClientImpl.backpressureBarrier | public boolean backpressureBarrier(final long start, long timeoutNanos) throws InterruptedException {
if (m_isShutdown) {
return false;
}
if (m_blessedThreadIds.contains(Thread.currentThread().getId())) {
throw new RuntimeException("Can't invoke backpressureBarrier from within the client callback thread " +
" without deadlocking the client library");
}
if (m_backpressure) {
synchronized (m_backpressureLock) {
if (m_backpressure) {
while (m_backpressure && !m_isShutdown) {
if (start != 0) {
if (timeoutNanos <= 0) {
// timeout nano value is negative or zero, indicating it timed out.
return true;
}
//Wait on the condition for the specified timeout remaining
m_backpressureLock.wait(timeoutNanos / TimeUnit.MILLISECONDS.toNanos(1), (int)(timeoutNanos % TimeUnit.MILLISECONDS.toNanos(1)));
//Condition is true, break and return false
if (!m_backpressure) {
break;
}
//Calculate whether the timeout should be triggered
final long nowNanos = System.nanoTime();
final long deltaNanos = Math.max(1, nowNanos - start);
if (deltaNanos >= timeoutNanos) {
return true;
}
//Reassigning timeout nanos with remainder of timeout
timeoutNanos -= deltaNanos;
} else {
m_backpressureLock.wait();
}
}
}
}
}
return false;
} | java | public boolean backpressureBarrier(final long start, long timeoutNanos) throws InterruptedException {
if (m_isShutdown) {
return false;
}
if (m_blessedThreadIds.contains(Thread.currentThread().getId())) {
throw new RuntimeException("Can't invoke backpressureBarrier from within the client callback thread " +
" without deadlocking the client library");
}
if (m_backpressure) {
synchronized (m_backpressureLock) {
if (m_backpressure) {
while (m_backpressure && !m_isShutdown) {
if (start != 0) {
if (timeoutNanos <= 0) {
// timeout nano value is negative or zero, indicating it timed out.
return true;
}
//Wait on the condition for the specified timeout remaining
m_backpressureLock.wait(timeoutNanos / TimeUnit.MILLISECONDS.toNanos(1), (int)(timeoutNanos % TimeUnit.MILLISECONDS.toNanos(1)));
//Condition is true, break and return false
if (!m_backpressure) {
break;
}
//Calculate whether the timeout should be triggered
final long nowNanos = System.nanoTime();
final long deltaNanos = Math.max(1, nowNanos - start);
if (deltaNanos >= timeoutNanos) {
return true;
}
//Reassigning timeout nanos with remainder of timeout
timeoutNanos -= deltaNanos;
} else {
m_backpressureLock.wait();
}
}
}
}
}
return false;
} | [
"public",
"boolean",
"backpressureBarrier",
"(",
"final",
"long",
"start",
",",
"long",
"timeoutNanos",
")",
"throws",
"InterruptedException",
"{",
"if",
"(",
"m_isShutdown",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"m_blessedThreadIds",
".",
"contains"... | Wait on backpressure with a timeout. Returns true on timeout, false otherwise.
Timeout nanos is the initial timeout quantity which will be adjusted to reflect remaining
time on spurious wakeups | [
"Wait",
"on",
"backpressure",
"with",
"a",
"timeout",
".",
"Returns",
"true",
"on",
"timeout",
"false",
"otherwise",
".",
"Timeout",
"nanos",
"is",
"the",
"initial",
"timeout",
"quantity",
"which",
"will",
"be",
"adjusted",
"to",
"reflect",
"remaining",
"time"... | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/client/ClientImpl.java#L660-L703 | train |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/rowio/RowInputBase.java | RowInputBase.readData | public Object[] readData(Type[] colTypes)
throws IOException, HsqlException {
int l = colTypes.length;
Object[] data = new Object[l];
Object o;
Type type;
for (int i = 0; i < l; i++) {
if (checkNull()) {
continue;
}
o = null;
type = colTypes[i];
switch (type.typeCode) {
case Types.SQL_ALL_TYPES :
case Types.SQL_CHAR :
case Types.SQL_VARCHAR :
case Types.VARCHAR_IGNORECASE :
o = readChar(type);
break;
case Types.TINYINT :
case Types.SQL_SMALLINT :
o = readSmallint();
break;
case Types.SQL_INTEGER :
o = readInteger();
break;
case Types.SQL_BIGINT :
o = readBigint();
break;
//fredt although REAL is now Double, it is read / written in
//the old format for compatibility
case Types.SQL_REAL :
case Types.SQL_FLOAT :
case Types.SQL_DOUBLE :
o = readReal();
break;
case Types.SQL_NUMERIC :
case Types.SQL_DECIMAL :
o = readDecimal(type);
break;
case Types.SQL_DATE :
o = readDate(type);
break;
case Types.SQL_TIME :
case Types.SQL_TIME_WITH_TIME_ZONE :
o = readTime(type);
break;
case Types.SQL_TIMESTAMP :
case Types.SQL_TIMESTAMP_WITH_TIME_ZONE :
o = readTimestamp(type);
break;
case Types.SQL_INTERVAL_YEAR :
case Types.SQL_INTERVAL_YEAR_TO_MONTH :
case Types.SQL_INTERVAL_MONTH :
o = readYearMonthInterval(type);
break;
case Types.SQL_INTERVAL_DAY :
case Types.SQL_INTERVAL_DAY_TO_HOUR :
case Types.SQL_INTERVAL_DAY_TO_MINUTE :
case Types.SQL_INTERVAL_DAY_TO_SECOND :
case Types.SQL_INTERVAL_HOUR :
case Types.SQL_INTERVAL_HOUR_TO_MINUTE :
case Types.SQL_INTERVAL_HOUR_TO_SECOND :
case Types.SQL_INTERVAL_MINUTE :
case Types.SQL_INTERVAL_MINUTE_TO_SECOND :
case Types.SQL_INTERVAL_SECOND :
o = readDaySecondInterval(type);
break;
case Types.SQL_BOOLEAN :
o = readBoole();
break;
case Types.OTHER :
o = readOther();
break;
case Types.SQL_CLOB :
o = readClob();
break;
case Types.SQL_BLOB :
o = readBlob();
break;
case Types.SQL_BINARY :
case Types.SQL_VARBINARY :
o = readBinary();
break;
case Types.SQL_BIT :
case Types.SQL_BIT_VARYING :
o = readBit();
break;
default :
throw Error.runtimeError(ErrorCode.U_S0500,
"RowInputBase "
+ type.getNameString());
}
data[i] = o;
}
return data;
} | java | public Object[] readData(Type[] colTypes)
throws IOException, HsqlException {
int l = colTypes.length;
Object[] data = new Object[l];
Object o;
Type type;
for (int i = 0; i < l; i++) {
if (checkNull()) {
continue;
}
o = null;
type = colTypes[i];
switch (type.typeCode) {
case Types.SQL_ALL_TYPES :
case Types.SQL_CHAR :
case Types.SQL_VARCHAR :
case Types.VARCHAR_IGNORECASE :
o = readChar(type);
break;
case Types.TINYINT :
case Types.SQL_SMALLINT :
o = readSmallint();
break;
case Types.SQL_INTEGER :
o = readInteger();
break;
case Types.SQL_BIGINT :
o = readBigint();
break;
//fredt although REAL is now Double, it is read / written in
//the old format for compatibility
case Types.SQL_REAL :
case Types.SQL_FLOAT :
case Types.SQL_DOUBLE :
o = readReal();
break;
case Types.SQL_NUMERIC :
case Types.SQL_DECIMAL :
o = readDecimal(type);
break;
case Types.SQL_DATE :
o = readDate(type);
break;
case Types.SQL_TIME :
case Types.SQL_TIME_WITH_TIME_ZONE :
o = readTime(type);
break;
case Types.SQL_TIMESTAMP :
case Types.SQL_TIMESTAMP_WITH_TIME_ZONE :
o = readTimestamp(type);
break;
case Types.SQL_INTERVAL_YEAR :
case Types.SQL_INTERVAL_YEAR_TO_MONTH :
case Types.SQL_INTERVAL_MONTH :
o = readYearMonthInterval(type);
break;
case Types.SQL_INTERVAL_DAY :
case Types.SQL_INTERVAL_DAY_TO_HOUR :
case Types.SQL_INTERVAL_DAY_TO_MINUTE :
case Types.SQL_INTERVAL_DAY_TO_SECOND :
case Types.SQL_INTERVAL_HOUR :
case Types.SQL_INTERVAL_HOUR_TO_MINUTE :
case Types.SQL_INTERVAL_HOUR_TO_SECOND :
case Types.SQL_INTERVAL_MINUTE :
case Types.SQL_INTERVAL_MINUTE_TO_SECOND :
case Types.SQL_INTERVAL_SECOND :
o = readDaySecondInterval(type);
break;
case Types.SQL_BOOLEAN :
o = readBoole();
break;
case Types.OTHER :
o = readOther();
break;
case Types.SQL_CLOB :
o = readClob();
break;
case Types.SQL_BLOB :
o = readBlob();
break;
case Types.SQL_BINARY :
case Types.SQL_VARBINARY :
o = readBinary();
break;
case Types.SQL_BIT :
case Types.SQL_BIT_VARYING :
o = readBit();
break;
default :
throw Error.runtimeError(ErrorCode.U_S0500,
"RowInputBase "
+ type.getNameString());
}
data[i] = o;
}
return data;
} | [
"public",
"Object",
"[",
"]",
"readData",
"(",
"Type",
"[",
"]",
"colTypes",
")",
"throws",
"IOException",
",",
"HsqlException",
"{",
"int",
"l",
"=",
"colTypes",
".",
"length",
";",
"Object",
"[",
"]",
"data",
"=",
"new",
"Object",
"[",
"l",
"]",
";... | reads row data from a stream using the JDBC types in colTypes
@param colTypes
@throws IOException
@throws HsqlException | [
"reads",
"row",
"data",
"from",
"a",
"stream",
"using",
"the",
"JDBC",
"types",
"in",
"colTypes"
] | 8afc1031e475835344b5497ea9e7203bc95475ac | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/rowio/RowInputBase.java#L150-L270 | train |
mpatric/mp3agic | src/main/java/com/mpatric/mp3agic/ID3v1Genres.java | ID3v1Genres.matchGenreDescription | public static int matchGenreDescription(String description) {
if (description != null && description.length() > 0) {
for (int i = 0; i < ID3v1Genres.GENRES.length; i++) {
if (ID3v1Genres.GENRES[i].equalsIgnoreCase(description)) {
return i;
}
}
}
return -1;
} | java | public static int matchGenreDescription(String description) {
if (description != null && description.length() > 0) {
for (int i = 0; i < ID3v1Genres.GENRES.length; i++) {
if (ID3v1Genres.GENRES[i].equalsIgnoreCase(description)) {
return i;
}
}
}
return -1;
} | [
"public",
"static",
"int",
"matchGenreDescription",
"(",
"String",
"description",
")",
"{",
"if",
"(",
"description",
"!=",
"null",
"&&",
"description",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"ID... | Match provided description against genres, ignoring case.
@param description genre description
@return matching genre index or -1 | [
"Match",
"provided",
"description",
"against",
"genres",
"ignoring",
"case",
"."
] | c3917e8438124142e65e7d816142bff845ac93aa | https://github.com/mpatric/mp3agic/blob/c3917e8438124142e65e7d816142bff845ac93aa/src/main/java/com/mpatric/mp3agic/ID3v1Genres.java#L163-L172 | train |
iwgang/CountdownView | library/src/main/java/cn/iwgang/countdownview/CountdownView.java | CountdownView.measureSize | private int measureSize(int specType, int contentSize, int measureSpec) {
int result;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = Math.max(contentSize, specSize);
} else {
result = contentSize;
if (specType == 1) {
// width
result += (getPaddingLeft() + getPaddingRight());
} else {
// height
result += (getPaddingTop() + getPaddingBottom());
}
}
return result;
} | java | private int measureSize(int specType, int contentSize, int measureSpec) {
int result;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = Math.max(contentSize, specSize);
} else {
result = contentSize;
if (specType == 1) {
// width
result += (getPaddingLeft() + getPaddingRight());
} else {
// height
result += (getPaddingTop() + getPaddingBottom());
}
}
return result;
} | [
"private",
"int",
"measureSize",
"(",
"int",
"specType",
",",
"int",
"contentSize",
",",
"int",
"measureSpec",
")",
"{",
"int",
"result",
";",
"int",
"specMode",
"=",
"MeasureSpec",
".",
"getMode",
"(",
"measureSpec",
")",
";",
"int",
"specSize",
"=",
"Mea... | measure view Size
@param specType 1 width 2 height
@param contentSize all content view size
@param measureSpec spec
@return measureSize | [
"measure",
"view",
"Size"
] | 3433615826b6e0a38b92e3362ba032947d9e8be7 | https://github.com/iwgang/CountdownView/blob/3433615826b6e0a38b92e3362ba032947d9e8be7/library/src/main/java/cn/iwgang/countdownview/CountdownView.java#L66-L86 | train |
iwgang/CountdownView | library/src/main/java/cn/iwgang/countdownview/BaseCountdown.java | BaseCountdown.initSuffixMargin | private void initSuffixMargin() {
int defSuffixLRMargin = Utils.dp2px(mContext, DEFAULT_SUFFIX_LR_MARGIN);
boolean isSuffixLRMarginNull = true;
if (mSuffixLRMargin >= 0) {
isSuffixLRMarginNull = false;
}
if (isShowDay && mSuffixDayTextWidth > 0) {
if (mSuffixDayLeftMargin < 0) {
if (!isSuffixLRMarginNull) {
mSuffixDayLeftMargin = mSuffixLRMargin;
} else {
mSuffixDayLeftMargin = defSuffixLRMargin;
}
}
if (mSuffixDayRightMargin < 0) {
if (!isSuffixLRMarginNull) {
mSuffixDayRightMargin = mSuffixLRMargin;
} else {
mSuffixDayRightMargin = defSuffixLRMargin;
}
}
} else {
mSuffixDayLeftMargin = 0;
mSuffixDayRightMargin = 0;
}
if (isShowHour && mSuffixHourTextWidth > 0) {
if (mSuffixHourLeftMargin < 0) {
if (!isSuffixLRMarginNull) {
mSuffixHourLeftMargin = mSuffixLRMargin;
} else {
mSuffixHourLeftMargin = defSuffixLRMargin;
}
}
if (mSuffixHourRightMargin < 0) {
if (!isSuffixLRMarginNull) {
mSuffixHourRightMargin = mSuffixLRMargin;
} else {
mSuffixHourRightMargin = defSuffixLRMargin;
}
}
} else {
mSuffixHourLeftMargin = 0;
mSuffixHourRightMargin = 0;
}
if (isShowMinute && mSuffixMinuteTextWidth > 0) {
if (mSuffixMinuteLeftMargin < 0) {
if (!isSuffixLRMarginNull) {
mSuffixMinuteLeftMargin = mSuffixLRMargin;
} else {
mSuffixMinuteLeftMargin = defSuffixLRMargin;
}
}
if (isShowSecond) {
if (mSuffixMinuteRightMargin < 0) {
if (!isSuffixLRMarginNull) {
mSuffixMinuteRightMargin = mSuffixLRMargin;
} else {
mSuffixMinuteRightMargin = defSuffixLRMargin;
}
}
} else {
mSuffixMinuteRightMargin = 0;
}
} else {
mSuffixMinuteLeftMargin = 0;
mSuffixMinuteRightMargin = 0;
}
if (isShowSecond) {
if (mSuffixSecondTextWidth > 0) {
if (mSuffixSecondLeftMargin < 0) {
if (!isSuffixLRMarginNull) {
mSuffixSecondLeftMargin = mSuffixLRMargin;
} else {
mSuffixSecondLeftMargin = defSuffixLRMargin;
}
}
if (isShowMillisecond) {
if (mSuffixSecondRightMargin < 0) {
if (!isSuffixLRMarginNull) {
mSuffixSecondRightMargin = mSuffixLRMargin;
} else {
mSuffixSecondRightMargin = defSuffixLRMargin;
}
}
} else {
mSuffixSecondRightMargin = 0;
}
} else {
mSuffixSecondLeftMargin = 0;
mSuffixSecondRightMargin = 0;
}
if (isShowMillisecond && mSuffixMillisecondTextWidth > 0) {
if (mSuffixMillisecondLeftMargin < 0) {
if (!isSuffixLRMarginNull) {
mSuffixMillisecondLeftMargin = mSuffixLRMargin;
} else {
mSuffixMillisecondLeftMargin = defSuffixLRMargin;
}
}
} else {
mSuffixMillisecondLeftMargin = 0;
}
} else {
mSuffixSecondLeftMargin = 0;
mSuffixSecondRightMargin = 0;
mSuffixMillisecondLeftMargin = 0;
}
} | java | private void initSuffixMargin() {
int defSuffixLRMargin = Utils.dp2px(mContext, DEFAULT_SUFFIX_LR_MARGIN);
boolean isSuffixLRMarginNull = true;
if (mSuffixLRMargin >= 0) {
isSuffixLRMarginNull = false;
}
if (isShowDay && mSuffixDayTextWidth > 0) {
if (mSuffixDayLeftMargin < 0) {
if (!isSuffixLRMarginNull) {
mSuffixDayLeftMargin = mSuffixLRMargin;
} else {
mSuffixDayLeftMargin = defSuffixLRMargin;
}
}
if (mSuffixDayRightMargin < 0) {
if (!isSuffixLRMarginNull) {
mSuffixDayRightMargin = mSuffixLRMargin;
} else {
mSuffixDayRightMargin = defSuffixLRMargin;
}
}
} else {
mSuffixDayLeftMargin = 0;
mSuffixDayRightMargin = 0;
}
if (isShowHour && mSuffixHourTextWidth > 0) {
if (mSuffixHourLeftMargin < 0) {
if (!isSuffixLRMarginNull) {
mSuffixHourLeftMargin = mSuffixLRMargin;
} else {
mSuffixHourLeftMargin = defSuffixLRMargin;
}
}
if (mSuffixHourRightMargin < 0) {
if (!isSuffixLRMarginNull) {
mSuffixHourRightMargin = mSuffixLRMargin;
} else {
mSuffixHourRightMargin = defSuffixLRMargin;
}
}
} else {
mSuffixHourLeftMargin = 0;
mSuffixHourRightMargin = 0;
}
if (isShowMinute && mSuffixMinuteTextWidth > 0) {
if (mSuffixMinuteLeftMargin < 0) {
if (!isSuffixLRMarginNull) {
mSuffixMinuteLeftMargin = mSuffixLRMargin;
} else {
mSuffixMinuteLeftMargin = defSuffixLRMargin;
}
}
if (isShowSecond) {
if (mSuffixMinuteRightMargin < 0) {
if (!isSuffixLRMarginNull) {
mSuffixMinuteRightMargin = mSuffixLRMargin;
} else {
mSuffixMinuteRightMargin = defSuffixLRMargin;
}
}
} else {
mSuffixMinuteRightMargin = 0;
}
} else {
mSuffixMinuteLeftMargin = 0;
mSuffixMinuteRightMargin = 0;
}
if (isShowSecond) {
if (mSuffixSecondTextWidth > 0) {
if (mSuffixSecondLeftMargin < 0) {
if (!isSuffixLRMarginNull) {
mSuffixSecondLeftMargin = mSuffixLRMargin;
} else {
mSuffixSecondLeftMargin = defSuffixLRMargin;
}
}
if (isShowMillisecond) {
if (mSuffixSecondRightMargin < 0) {
if (!isSuffixLRMarginNull) {
mSuffixSecondRightMargin = mSuffixLRMargin;
} else {
mSuffixSecondRightMargin = defSuffixLRMargin;
}
}
} else {
mSuffixSecondRightMargin = 0;
}
} else {
mSuffixSecondLeftMargin = 0;
mSuffixSecondRightMargin = 0;
}
if (isShowMillisecond && mSuffixMillisecondTextWidth > 0) {
if (mSuffixMillisecondLeftMargin < 0) {
if (!isSuffixLRMarginNull) {
mSuffixMillisecondLeftMargin = mSuffixLRMargin;
} else {
mSuffixMillisecondLeftMargin = defSuffixLRMargin;
}
}
} else {
mSuffixMillisecondLeftMargin = 0;
}
} else {
mSuffixSecondLeftMargin = 0;
mSuffixSecondRightMargin = 0;
mSuffixMillisecondLeftMargin = 0;
}
} | [
"private",
"void",
"initSuffixMargin",
"(",
")",
"{",
"int",
"defSuffixLRMargin",
"=",
"Utils",
".",
"dp2px",
"(",
"mContext",
",",
"DEFAULT_SUFFIX_LR_MARGIN",
")",
";",
"boolean",
"isSuffixLRMarginNull",
"=",
"true",
";",
"if",
"(",
"mSuffixLRMargin",
">=",
"0"... | initialize suffix margin | [
"initialize",
"suffix",
"margin"
] | 3433615826b6e0a38b92e3362ba032947d9e8be7 | https://github.com/iwgang/CountdownView/blob/3433615826b6e0a38b92e3362ba032947d9e8be7/library/src/main/java/cn/iwgang/countdownview/BaseCountdown.java#L269-L386 | train |
iwgang/CountdownView | library/src/main/java/cn/iwgang/countdownview/BaseCountdown.java | BaseCountdown.getAllContentWidth | public int getAllContentWidth() {
float width = getAllContentWidthBase(mTimeTextWidth);
if (!isConvertDaysToHours && isShowDay) {
if (isDayLargeNinetyNine) {
Rect rect = new Rect();
String tempDay = String.valueOf(mDay);
mTimeTextPaint.getTextBounds(tempDay, 0, tempDay.length(), rect);
mDayTimeTextWidth = rect.width();
width += mDayTimeTextWidth;
} else {
mDayTimeTextWidth = mTimeTextWidth;
width += mTimeTextWidth;
}
}
return (int) Math.ceil(width);
} | java | public int getAllContentWidth() {
float width = getAllContentWidthBase(mTimeTextWidth);
if (!isConvertDaysToHours && isShowDay) {
if (isDayLargeNinetyNine) {
Rect rect = new Rect();
String tempDay = String.valueOf(mDay);
mTimeTextPaint.getTextBounds(tempDay, 0, tempDay.length(), rect);
mDayTimeTextWidth = rect.width();
width += mDayTimeTextWidth;
} else {
mDayTimeTextWidth = mTimeTextWidth;
width += mTimeTextWidth;
}
}
return (int) Math.ceil(width);
} | [
"public",
"int",
"getAllContentWidth",
"(",
")",
"{",
"float",
"width",
"=",
"getAllContentWidthBase",
"(",
"mTimeTextWidth",
")",
";",
"if",
"(",
"!",
"isConvertDaysToHours",
"&&",
"isShowDay",
")",
"{",
"if",
"(",
"isDayLargeNinetyNine",
")",
"{",
"Rect",
"r... | get all view width
@return all view width | [
"get",
"all",
"view",
"width"
] | 3433615826b6e0a38b92e3362ba032947d9e8be7 | https://github.com/iwgang/CountdownView/blob/3433615826b6e0a38b92e3362ba032947d9e8be7/library/src/main/java/cn/iwgang/countdownview/BaseCountdown.java#L504-L521 | train |
iwgang/CountdownView | library/src/main/java/cn/iwgang/countdownview/BackgroundCountdown.java | BackgroundCountdown.initTimeTextBaselineAndTimeBgTopPadding | private float initTimeTextBaselineAndTimeBgTopPadding(int viewHeight, int viewPaddingTop, int viewPaddingBottom, int contentAllHeight) {
float topPaddingSize;
if (viewPaddingTop == viewPaddingBottom) {
// center
topPaddingSize = (viewHeight - contentAllHeight) / 2;
} else {
// padding top
topPaddingSize = viewPaddingTop;
}
if (isShowDay && mSuffixDayTextWidth > 0) {
mSuffixDayTextBaseline = getSuffixTextBaseLine(mSuffixDay, topPaddingSize);
}
if (isShowHour && mSuffixHourTextWidth > 0) {
mSuffixHourTextBaseline = getSuffixTextBaseLine(mSuffixHour, topPaddingSize);
}
if (isShowMinute && mSuffixMinuteTextWidth > 0) {
mSuffixMinuteTextBaseline = getSuffixTextBaseLine(mSuffixMinute, topPaddingSize);
}
if (mSuffixSecondTextWidth > 0) {
mSuffixSecondTextBaseline = getSuffixTextBaseLine(mSuffixSecond, topPaddingSize);
}
if (isShowMillisecond && mSuffixMillisecondTextWidth > 0) {
mSuffixMillisecondTextBaseline = getSuffixTextBaseLine(mSuffixMillisecond, topPaddingSize);
}
return topPaddingSize;
} | java | private float initTimeTextBaselineAndTimeBgTopPadding(int viewHeight, int viewPaddingTop, int viewPaddingBottom, int contentAllHeight) {
float topPaddingSize;
if (viewPaddingTop == viewPaddingBottom) {
// center
topPaddingSize = (viewHeight - contentAllHeight) / 2;
} else {
// padding top
topPaddingSize = viewPaddingTop;
}
if (isShowDay && mSuffixDayTextWidth > 0) {
mSuffixDayTextBaseline = getSuffixTextBaseLine(mSuffixDay, topPaddingSize);
}
if (isShowHour && mSuffixHourTextWidth > 0) {
mSuffixHourTextBaseline = getSuffixTextBaseLine(mSuffixHour, topPaddingSize);
}
if (isShowMinute && mSuffixMinuteTextWidth > 0) {
mSuffixMinuteTextBaseline = getSuffixTextBaseLine(mSuffixMinute, topPaddingSize);
}
if (mSuffixSecondTextWidth > 0) {
mSuffixSecondTextBaseline = getSuffixTextBaseLine(mSuffixSecond, topPaddingSize);
}
if (isShowMillisecond && mSuffixMillisecondTextWidth > 0) {
mSuffixMillisecondTextBaseline = getSuffixTextBaseLine(mSuffixMillisecond, topPaddingSize);
}
return topPaddingSize;
} | [
"private",
"float",
"initTimeTextBaselineAndTimeBgTopPadding",
"(",
"int",
"viewHeight",
",",
"int",
"viewPaddingTop",
",",
"int",
"viewPaddingBottom",
",",
"int",
"contentAllHeight",
")",
"{",
"float",
"topPaddingSize",
";",
"if",
"(",
"viewPaddingTop",
"==",
"viewPa... | initialize time text baseline
and
time background top padding | [
"initialize",
"time",
"text",
"baseline",
"and",
"time",
"background",
"top",
"padding"
] | 3433615826b6e0a38b92e3362ba032947d9e8be7 | https://github.com/iwgang/CountdownView/blob/3433615826b6e0a38b92e3362ba032947d9e8be7/library/src/main/java/cn/iwgang/countdownview/BackgroundCountdown.java#L240-L271 | train |
haraldk/TwelveMonkeys | common/common-image/src/main/java/com/twelvemonkeys/image/BrightnessContrastFilter.java | BrightnessContrastFilter.filterRGB | public int filterRGB(int pX, int pY, int pARGB) {
// Get color components
int r = pARGB >> 16 & 0xFF;
int g = pARGB >> 8 & 0xFF;
int b = pARGB & 0xFF;
// Scale to new contrast
r = LUT[r];
g = LUT[g];
b = LUT[b];
// Return ARGB pixel, leave transparency as is
return (pARGB & 0xFF000000) | (r << 16) | (g << 8) | b;
} | java | public int filterRGB(int pX, int pY, int pARGB) {
// Get color components
int r = pARGB >> 16 & 0xFF;
int g = pARGB >> 8 & 0xFF;
int b = pARGB & 0xFF;
// Scale to new contrast
r = LUT[r];
g = LUT[g];
b = LUT[b];
// Return ARGB pixel, leave transparency as is
return (pARGB & 0xFF000000) | (r << 16) | (g << 8) | b;
} | [
"public",
"int",
"filterRGB",
"(",
"int",
"pX",
",",
"int",
"pY",
",",
"int",
"pARGB",
")",
"{",
"// Get color components\r",
"int",
"r",
"=",
"pARGB",
">>",
"16",
"&",
"0xFF",
";",
"int",
"g",
"=",
"pARGB",
">>",
"8",
"&",
"0xFF",
";",
"int",
"b",... | Filters one pixel, adjusting brightness and contrast according to this
filter.
@param pX x
@param pY y
@param pARGB pixel value in default color space
@return the filtered pixel value in the default color space | [
"Filters",
"one",
"pixel",
"adjusting",
"brightness",
"and",
"contrast",
"according",
"to",
"this",
"filter",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-image/src/main/java/com/twelvemonkeys/image/BrightnessContrastFilter.java#L156-L169 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java | DebugUtil.buildTimestamp | protected static String buildTimestamp(final Calendar pCalendar) {
if (pCalendar == null) {
return CALENDAR_IS_NULL_ERROR_MESSAGE;
}
// The timestamp format
StringBuilder timestamp = new StringBuilder();
//timestamp.append(DateUtil.getMonthName(new Integer(pCalendar.get(Calendar.MONTH)).toString(), "0", "us", "MEDIUM", false) + " ");
timestamp.append(DateFormat.getDateInstance(DateFormat.MEDIUM).format(pCalendar.getTime()));
//timestamp.append(pCalendar.get(Calendar.DAY_OF_MONTH) + " ");
timestamp.append(" ");
timestamp.append(StringUtil.pad(new Integer(pCalendar.get(Calendar.HOUR_OF_DAY)).toString(), 2, "0", true) + ":");
timestamp.append(StringUtil.pad(new Integer(pCalendar.get(Calendar.MINUTE)).toString(), 2, "0", true) + ":");
timestamp.append(StringUtil.pad(new Integer(pCalendar.get(Calendar.SECOND)).toString(), 2, "0", true) + ":");
timestamp.append(StringUtil.pad(new Integer(pCalendar.get(Calendar.MILLISECOND)).toString(), 3, "0", true));
return timestamp.toString();
} | java | protected static String buildTimestamp(final Calendar pCalendar) {
if (pCalendar == null) {
return CALENDAR_IS_NULL_ERROR_MESSAGE;
}
// The timestamp format
StringBuilder timestamp = new StringBuilder();
//timestamp.append(DateUtil.getMonthName(new Integer(pCalendar.get(Calendar.MONTH)).toString(), "0", "us", "MEDIUM", false) + " ");
timestamp.append(DateFormat.getDateInstance(DateFormat.MEDIUM).format(pCalendar.getTime()));
//timestamp.append(pCalendar.get(Calendar.DAY_OF_MONTH) + " ");
timestamp.append(" ");
timestamp.append(StringUtil.pad(new Integer(pCalendar.get(Calendar.HOUR_OF_DAY)).toString(), 2, "0", true) + ":");
timestamp.append(StringUtil.pad(new Integer(pCalendar.get(Calendar.MINUTE)).toString(), 2, "0", true) + ":");
timestamp.append(StringUtil.pad(new Integer(pCalendar.get(Calendar.SECOND)).toString(), 2, "0", true) + ":");
timestamp.append(StringUtil.pad(new Integer(pCalendar.get(Calendar.MILLISECOND)).toString(), 3, "0", true));
return timestamp.toString();
} | [
"protected",
"static",
"String",
"buildTimestamp",
"(",
"final",
"Calendar",
"pCalendar",
")",
"{",
"if",
"(",
"pCalendar",
"==",
"null",
")",
"{",
"return",
"CALENDAR_IS_NULL_ERROR_MESSAGE",
";",
"}",
"// The timestamp format\r",
"StringBuilder",
"timestamp",
"=",
... | Builds a presentation of the given calendar's time. This method contains the common timestamp format used in this class.
@return a presentation of the calendar time. | [
"Builds",
"a",
"presentation",
"of",
"the",
"given",
"calendar",
"s",
"time",
".",
"This",
"method",
"contains",
"the",
"common",
"timestamp",
"format",
"used",
"in",
"this",
"class",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java#L818-L837 | train |
haraldk/TwelveMonkeys | common/common-lang/src/main/java/com/twelvemonkeys/lang/DateUtil.java | DateUtil.roundToHour | public static long roundToHour(final long pTime, final TimeZone pTimeZone) {
int offset = pTimeZone.getOffset(pTime);
return ((pTime / HOUR) * HOUR) - offset;
} | java | public static long roundToHour(final long pTime, final TimeZone pTimeZone) {
int offset = pTimeZone.getOffset(pTime);
return ((pTime / HOUR) * HOUR) - offset;
} | [
"public",
"static",
"long",
"roundToHour",
"(",
"final",
"long",
"pTime",
",",
"final",
"TimeZone",
"pTimeZone",
")",
"{",
"int",
"offset",
"=",
"pTimeZone",
".",
"getOffset",
"(",
"pTime",
")",
";",
"return",
"(",
"(",
"pTime",
"/",
"HOUR",
")",
"*",
... | Rounds the given time down to the closest hour, using the given timezone.
@param pTime time
@param pTimeZone the timezone to use when rounding
@return the time rounded to the closest hour. | [
"Rounds",
"the",
"given",
"time",
"down",
"to",
"the",
"closest",
"hour",
"using",
"the",
"given",
"timezone",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-lang/src/main/java/com/twelvemonkeys/lang/DateUtil.java#L178-L181 | train |
haraldk/TwelveMonkeys | common/common-lang/src/main/java/com/twelvemonkeys/lang/DateUtil.java | DateUtil.roundToDay | public static long roundToDay(final long pTime, final TimeZone pTimeZone) {
int offset = pTimeZone.getOffset(pTime);
return (((pTime + offset) / DAY) * DAY) - offset;
} | java | public static long roundToDay(final long pTime, final TimeZone pTimeZone) {
int offset = pTimeZone.getOffset(pTime);
return (((pTime + offset) / DAY) * DAY) - offset;
} | [
"public",
"static",
"long",
"roundToDay",
"(",
"final",
"long",
"pTime",
",",
"final",
"TimeZone",
"pTimeZone",
")",
"{",
"int",
"offset",
"=",
"pTimeZone",
".",
"getOffset",
"(",
"pTime",
")",
";",
"return",
"(",
"(",
"(",
"pTime",
"+",
"offset",
")",
... | Rounds the given time down to the closest day, using the given timezone.
@param pTime time
@param pTimeZone the timezone to use when rounding
@return the time rounded to the closest day. | [
"Rounds",
"the",
"given",
"time",
"down",
"to",
"the",
"closest",
"day",
"using",
"the",
"given",
"timezone",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-lang/src/main/java/com/twelvemonkeys/lang/DateUtil.java#L200-L203 | train |
haraldk/TwelveMonkeys | common/common-lang/src/main/java/com/twelvemonkeys/util/convert/ConverterImpl.java | ConverterImpl.getConverterForType | private PropertyConverter getConverterForType(Class pType) {
Object converter;
Class cl = pType;
// Loop until we find a suitable converter
do {
// Have a match, return converter
if ((converter = getInstance().converters.get(cl)) != null) {
return (PropertyConverter) converter;
}
}
while ((cl = cl.getSuperclass()) != null);
// No converter found, return null
return null;
} | java | private PropertyConverter getConverterForType(Class pType) {
Object converter;
Class cl = pType;
// Loop until we find a suitable converter
do {
// Have a match, return converter
if ((converter = getInstance().converters.get(cl)) != null) {
return (PropertyConverter) converter;
}
}
while ((cl = cl.getSuperclass()) != null);
// No converter found, return null
return null;
} | [
"private",
"PropertyConverter",
"getConverterForType",
"(",
"Class",
"pType",
")",
"{",
"Object",
"converter",
";",
"Class",
"cl",
"=",
"pType",
";",
"// Loop until we find a suitable converter\r",
"do",
"{",
"// Have a match, return converter\r",
"if",
"(",
"(",
"conve... | Gets the registered converter for the given type.
@param pType the type to convert to
@return an instance of a {@code PropertyConverter} or {@code null} | [
"Gets",
"the",
"registered",
"converter",
"for",
"the",
"given",
"type",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-lang/src/main/java/com/twelvemonkeys/util/convert/ConverterImpl.java#L57-L73 | train |
haraldk/TwelveMonkeys | common/common-lang/src/main/java/com/twelvemonkeys/util/convert/ConverterImpl.java | ConverterImpl.toObject | public Object toObject(String pString, Class pType, String pFormat)
throws ConversionException {
if (pString == null) {
return null;
}
if (pType == null) {
throw new MissingTypeException();
}
// Get converter
PropertyConverter converter = getConverterForType(pType);
if (converter == null) {
throw new NoAvailableConverterException("Cannot convert to object, no converter available for type \"" + pType.getName() + "\"");
}
// Convert and return
return converter.toObject(pString, pType, pFormat);
} | java | public Object toObject(String pString, Class pType, String pFormat)
throws ConversionException {
if (pString == null) {
return null;
}
if (pType == null) {
throw new MissingTypeException();
}
// Get converter
PropertyConverter converter = getConverterForType(pType);
if (converter == null) {
throw new NoAvailableConverterException("Cannot convert to object, no converter available for type \"" + pType.getName() + "\"");
}
// Convert and return
return converter.toObject(pString, pType, pFormat);
} | [
"public",
"Object",
"toObject",
"(",
"String",
"pString",
",",
"Class",
"pType",
",",
"String",
"pFormat",
")",
"throws",
"ConversionException",
"{",
"if",
"(",
"pString",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"pType",
"==",
"nul... | Converts the string to an object of the given type, parsing after the
given format.
@param pString the string to convert
@param pType the type to convert to
@param pFormat the vonversion format
@return the object created from the given string.
@throws ConversionException if the string cannot be converted for any
reason. | [
"Converts",
"the",
"string",
"to",
"an",
"object",
"of",
"the",
"given",
"type",
"parsing",
"after",
"the",
"given",
"format",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-lang/src/main/java/com/twelvemonkeys/util/convert/ConverterImpl.java#L88-L108 | train |
haraldk/TwelveMonkeys | contrib/src/main/java/com/twelvemonkeys/contrib/tiff/TIFFUtilities.java | TIFFUtilities.merge | public static void merge(List<File> inputFiles, File outputFile) throws IOException {
ImageOutputStream output = null;
try {
output = ImageIO.createImageOutputStream(outputFile);
for (File file : inputFiles) {
ImageInputStream input = null;
try {
input = ImageIO.createImageInputStream(file);
List<TIFFPage> pages = getPages(input);
writePages(output, pages);
}
finally {
if (input != null) {
input.close();
}
}
}
}
finally {
if (output != null) {
output.flush();
output.close();
}
}
} | java | public static void merge(List<File> inputFiles, File outputFile) throws IOException {
ImageOutputStream output = null;
try {
output = ImageIO.createImageOutputStream(outputFile);
for (File file : inputFiles) {
ImageInputStream input = null;
try {
input = ImageIO.createImageInputStream(file);
List<TIFFPage> pages = getPages(input);
writePages(output, pages);
}
finally {
if (input != null) {
input.close();
}
}
}
}
finally {
if (output != null) {
output.flush();
output.close();
}
}
} | [
"public",
"static",
"void",
"merge",
"(",
"List",
"<",
"File",
">",
"inputFiles",
",",
"File",
"outputFile",
")",
"throws",
"IOException",
"{",
"ImageOutputStream",
"output",
"=",
"null",
";",
"try",
"{",
"output",
"=",
"ImageIO",
".",
"createImageOutputStream... | Merges all pages from the input TIFF files into one TIFF file at the
output location.
@param inputFiles
@param outputFile
@throws IOException | [
"Merges",
"all",
"pages",
"from",
"the",
"input",
"TIFF",
"files",
"into",
"one",
"TIFF",
"file",
"at",
"the",
"output",
"location",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/contrib/src/main/java/com/twelvemonkeys/contrib/tiff/TIFFUtilities.java#L73-L98 | train |
haraldk/TwelveMonkeys | contrib/src/main/java/com/twelvemonkeys/contrib/tiff/TIFFUtilities.java | TIFFUtilities.split | public static List<File> split(File inputFile, File outputDirectory) throws IOException {
ImageInputStream input = null;
List<File> outputFiles = new ArrayList<>();
try {
input = ImageIO.createImageInputStream(inputFile);
List<TIFFPage> pages = getPages(input);
int pageNo = 1;
for (TIFFPage tiffPage : pages) {
ArrayList<TIFFPage> outputPages = new ArrayList<TIFFPage>(1);
ImageOutputStream outputStream = null;
try {
File outputFile = new File(outputDirectory, String.format("%04d", pageNo) + ".tif");
outputStream = ImageIO.createImageOutputStream(outputFile);
outputPages.clear();
outputPages.add(tiffPage);
writePages(outputStream, outputPages);
outputFiles.add(outputFile);
}
finally {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
}
++pageNo;
}
}
finally {
if (input != null) {
input.close();
}
}
return outputFiles;
} | java | public static List<File> split(File inputFile, File outputDirectory) throws IOException {
ImageInputStream input = null;
List<File> outputFiles = new ArrayList<>();
try {
input = ImageIO.createImageInputStream(inputFile);
List<TIFFPage> pages = getPages(input);
int pageNo = 1;
for (TIFFPage tiffPage : pages) {
ArrayList<TIFFPage> outputPages = new ArrayList<TIFFPage>(1);
ImageOutputStream outputStream = null;
try {
File outputFile = new File(outputDirectory, String.format("%04d", pageNo) + ".tif");
outputStream = ImageIO.createImageOutputStream(outputFile);
outputPages.clear();
outputPages.add(tiffPage);
writePages(outputStream, outputPages);
outputFiles.add(outputFile);
}
finally {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
}
++pageNo;
}
}
finally {
if (input != null) {
input.close();
}
}
return outputFiles;
} | [
"public",
"static",
"List",
"<",
"File",
">",
"split",
"(",
"File",
"inputFile",
",",
"File",
"outputDirectory",
")",
"throws",
"IOException",
"{",
"ImageInputStream",
"input",
"=",
"null",
";",
"List",
"<",
"File",
">",
"outputFiles",
"=",
"new",
"ArrayList... | Splits all pages from the input TIFF file to one file per page in the
output directory.
@param inputFile
@param outputDirectory
@return generated files
@throws IOException | [
"Splits",
"all",
"pages",
"from",
"the",
"input",
"TIFF",
"file",
"to",
"one",
"file",
"per",
"page",
"in",
"the",
"output",
"directory",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/contrib/src/main/java/com/twelvemonkeys/contrib/tiff/TIFFUtilities.java#L109-L142 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java | ObjectReader.getStats | public static String getStats() {
long total = sCacheHit + sCacheMiss + sCacheUn;
double hit = ((double) sCacheHit / (double) total) * 100.0;
double miss = ((double) sCacheMiss / (double) total) * 100.0;
double un = ((double) sCacheUn / (double) total) * 100.0;
// Default locale
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
return "Total: " + total + " reads. "
+ "Cache hits: " + sCacheHit + " (" + nf.format(hit) + "%), "
+ "Cache misses: " + sCacheMiss + " (" + nf.format(miss) + "%), "
+ "Unattempted: " + sCacheUn + " (" + nf.format(un) + "%) ";
} | java | public static String getStats() {
long total = sCacheHit + sCacheMiss + sCacheUn;
double hit = ((double) sCacheHit / (double) total) * 100.0;
double miss = ((double) sCacheMiss / (double) total) * 100.0;
double un = ((double) sCacheUn / (double) total) * 100.0;
// Default locale
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
return "Total: " + total + " reads. "
+ "Cache hits: " + sCacheHit + " (" + nf.format(hit) + "%), "
+ "Cache misses: " + sCacheMiss + " (" + nf.format(miss) + "%), "
+ "Unattempted: " + sCacheUn + " (" + nf.format(un) + "%) ";
} | [
"public",
"static",
"String",
"getStats",
"(",
")",
"{",
"long",
"total",
"=",
"sCacheHit",
"+",
"sCacheMiss",
"+",
"sCacheUn",
";",
"double",
"hit",
"=",
"(",
"(",
"double",
")",
"sCacheHit",
"/",
"(",
"double",
")",
"total",
")",
"*",
"100.0",
";",
... | Gets a string containing the stats for this ObjectReader.
@return A string to display the stats. | [
"Gets",
"a",
"string",
"containing",
"the",
"stats",
"for",
"this",
"ObjectReader",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java#L190-L203 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java | ObjectReader.readIdentities | private Object[] readIdentities(Class pObjClass, Hashtable pMapping,
Hashtable pWhere, ObjectMapper pOM)
throws SQLException {
sCacheUn++;
// Build SQL query string
if (pWhere == null)
pWhere = new Hashtable();
String[] keys = new String[pWhere.size()];
int i = 0;
for (Enumeration en = pWhere.keys(); en.hasMoreElements(); i++) {
keys[i] = (String) en.nextElement();
}
// Get SQL for reading identity column
String sql = pOM.buildIdentitySQL(keys)
+ buildWhereClause(keys, pMapping);
// Log?
mLog.logDebug(sql + " (" + pWhere + ")");
// Prepare statement and set values
PreparedStatement statement = mConnection.prepareStatement(sql);
for (int j = 0; j < keys.length; j++) {
Object key = pWhere.get(keys[j]);
if (key instanceof Integer)
statement.setInt(j + 1, ((Integer) key).intValue());
else if (key instanceof BigDecimal)
statement.setBigDecimal(j + 1, (BigDecimal) key);
else
statement.setString(j + 1, key.toString());
}
// Execute query
ResultSet rs = null;
try {
rs = statement.executeQuery();
}
catch (SQLException e) {
mLog.logError(sql + " (" + pWhere + ")", e);
throw e;
}
Vector result = new Vector();
// Map query to objects
while (rs.next()) {
Object obj = null;
try {
obj = pObjClass.newInstance();
}
catch (IllegalAccessException iae) {
iae.printStackTrace();
}
catch (InstantiationException ie) {
ie.printStackTrace();
}
// Map it
pOM.mapColumnProperty(rs, 1,
pOM.getProperty(pOM.getPrimaryKey()), obj);
result.addElement(obj);
}
// Return array of identifiers
return result.toArray((Object[]) Array.newInstance(pObjClass,
result.size()));
} | java | private Object[] readIdentities(Class pObjClass, Hashtable pMapping,
Hashtable pWhere, ObjectMapper pOM)
throws SQLException {
sCacheUn++;
// Build SQL query string
if (pWhere == null)
pWhere = new Hashtable();
String[] keys = new String[pWhere.size()];
int i = 0;
for (Enumeration en = pWhere.keys(); en.hasMoreElements(); i++) {
keys[i] = (String) en.nextElement();
}
// Get SQL for reading identity column
String sql = pOM.buildIdentitySQL(keys)
+ buildWhereClause(keys, pMapping);
// Log?
mLog.logDebug(sql + " (" + pWhere + ")");
// Prepare statement and set values
PreparedStatement statement = mConnection.prepareStatement(sql);
for (int j = 0; j < keys.length; j++) {
Object key = pWhere.get(keys[j]);
if (key instanceof Integer)
statement.setInt(j + 1, ((Integer) key).intValue());
else if (key instanceof BigDecimal)
statement.setBigDecimal(j + 1, (BigDecimal) key);
else
statement.setString(j + 1, key.toString());
}
// Execute query
ResultSet rs = null;
try {
rs = statement.executeQuery();
}
catch (SQLException e) {
mLog.logError(sql + " (" + pWhere + ")", e);
throw e;
}
Vector result = new Vector();
// Map query to objects
while (rs.next()) {
Object obj = null;
try {
obj = pObjClass.newInstance();
}
catch (IllegalAccessException iae) {
iae.printStackTrace();
}
catch (InstantiationException ie) {
ie.printStackTrace();
}
// Map it
pOM.mapColumnProperty(rs, 1,
pOM.getProperty(pOM.getPrimaryKey()), obj);
result.addElement(obj);
}
// Return array of identifiers
return result.toArray((Object[]) Array.newInstance(pObjClass,
result.size()));
} | [
"private",
"Object",
"[",
"]",
"readIdentities",
"(",
"Class",
"pObjClass",
",",
"Hashtable",
"pMapping",
",",
"Hashtable",
"pWhere",
",",
"ObjectMapper",
"pOM",
")",
"throws",
"SQLException",
"{",
"sCacheUn",
"++",
";",
"// Build SQL query string\r",
"if",
"(",
... | Get an array containing Objects of type objClass, with the
identity values for the given class set. | [
"Get",
"an",
"array",
"containing",
"Objects",
"of",
"type",
"objClass",
"with",
"the",
"identity",
"values",
"for",
"the",
"given",
"class",
"set",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java#L210-L278 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java | ObjectReader.readObject | public Object readObject(DatabaseReadable pReadable) throws SQLException {
return readObject(pReadable.getId(), pReadable.getClass(),
pReadable.getMapping());
} | java | public Object readObject(DatabaseReadable pReadable) throws SQLException {
return readObject(pReadable.getId(), pReadable.getClass(),
pReadable.getMapping());
} | [
"public",
"Object",
"readObject",
"(",
"DatabaseReadable",
"pReadable",
")",
"throws",
"SQLException",
"{",
"return",
"readObject",
"(",
"pReadable",
".",
"getId",
"(",
")",
",",
"pReadable",
".",
"getClass",
"(",
")",
",",
"pReadable",
".",
"getMapping",
"(",... | Reads one object implementing the DatabaseReadable interface from the
database.
@param readable A DatabaseReadable object
@return The Object read, or null in no object is found | [
"Reads",
"one",
"object",
"implementing",
"the",
"DatabaseReadable",
"interface",
"from",
"the",
"database",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java#L289-L292 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java | ObjectReader.readObject | public Object readObject(Object pId, Class pObjClass, Hashtable pMapping)
throws SQLException {
return readObject(pId, pObjClass, pMapping, null);
} | java | public Object readObject(Object pId, Class pObjClass, Hashtable pMapping)
throws SQLException {
return readObject(pId, pObjClass, pMapping, null);
} | [
"public",
"Object",
"readObject",
"(",
"Object",
"pId",
",",
"Class",
"pObjClass",
",",
"Hashtable",
"pMapping",
")",
"throws",
"SQLException",
"{",
"return",
"readObject",
"(",
"pId",
",",
"pObjClass",
",",
"pMapping",
",",
"null",
")",
";",
"}"
] | Reads the object with the given id from the database, using the given
mapping.
@param id An object uniquely identifying the object to read
@param objClass The clas
@return The Object read, or null in no object is found | [
"Reads",
"the",
"object",
"with",
"the",
"given",
"id",
"from",
"the",
"database",
"using",
"the",
"given",
"mapping",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java#L303-L306 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java | ObjectReader.readObjects | public Object[] readObjects(DatabaseReadable pReadable)
throws SQLException {
return readObjects(pReadable.getClass(),
pReadable.getMapping(), null);
} | java | public Object[] readObjects(DatabaseReadable pReadable)
throws SQLException {
return readObjects(pReadable.getClass(),
pReadable.getMapping(), null);
} | [
"public",
"Object",
"[",
"]",
"readObjects",
"(",
"DatabaseReadable",
"pReadable",
")",
"throws",
"SQLException",
"{",
"return",
"readObjects",
"(",
"pReadable",
".",
"getClass",
"(",
")",
",",
"pReadable",
".",
"getMapping",
"(",
")",
",",
"null",
")",
";",... | Reads all the objects of the given type from the
database. The object must implement the DatabaseReadable interface.
@return An array of Objects, or an zero-length array if none was found | [
"Reads",
"all",
"the",
"objects",
"of",
"the",
"given",
"type",
"from",
"the",
"database",
".",
"The",
"object",
"must",
"implement",
"the",
"DatabaseReadable",
"interface",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java#L315-L319 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java | ObjectReader.setPropertyValue | private void setPropertyValue(Object pObj, String pProperty,
Object pValue) {
Method m = null;
Class[] cl = {pValue.getClass()};
try {
//Util.setPropertyValue(pObj, pProperty, pValue);
// Find method
m = pObj.getClass().
getMethod("set" + StringUtil.capitalize(pProperty), cl);
// Invoke it
Object[] args = {pValue};
m.invoke(pObj, args);
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
catch (IllegalAccessException iae) {
iae.printStackTrace();
}
catch (InvocationTargetException ite) {
ite.printStackTrace();
}
} | java | private void setPropertyValue(Object pObj, String pProperty,
Object pValue) {
Method m = null;
Class[] cl = {pValue.getClass()};
try {
//Util.setPropertyValue(pObj, pProperty, pValue);
// Find method
m = pObj.getClass().
getMethod("set" + StringUtil.capitalize(pProperty), cl);
// Invoke it
Object[] args = {pValue};
m.invoke(pObj, args);
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
catch (IllegalAccessException iae) {
iae.printStackTrace();
}
catch (InvocationTargetException ite) {
ite.printStackTrace();
}
} | [
"private",
"void",
"setPropertyValue",
"(",
"Object",
"pObj",
",",
"String",
"pProperty",
",",
"Object",
"pValue",
")",
"{",
"Method",
"m",
"=",
"null",
";",
"Class",
"[",
"]",
"cl",
"=",
"{",
"pValue",
".",
"getClass",
"(",
")",
"}",
";",
"try",
"{"... | Sets the property value to an object using reflection
@param obj The object to get a property from
@param property The name of the property
@param value The property value | [
"Sets",
"the",
"property",
"value",
"to",
"an",
"object",
"using",
"reflection"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java#L330-L357 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java | ObjectReader.getPropertyValue | private Object getPropertyValue(Object pObj, String pProperty) {
Method m = null;
Class[] cl = new Class[0];
try {
//return Util.getPropertyValue(pObj, pProperty);
// Find method
m = pObj.getClass().
getMethod("get" + StringUtil.capitalize(pProperty),
new Class[0]);
// Invoke it
Object result = m.invoke(pObj, new Object[0]);
return result;
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
catch (IllegalAccessException iae) {
iae.printStackTrace();
}
catch (InvocationTargetException ite) {
ite.printStackTrace();
}
return null;
} | java | private Object getPropertyValue(Object pObj, String pProperty) {
Method m = null;
Class[] cl = new Class[0];
try {
//return Util.getPropertyValue(pObj, pProperty);
// Find method
m = pObj.getClass().
getMethod("get" + StringUtil.capitalize(pProperty),
new Class[0]);
// Invoke it
Object result = m.invoke(pObj, new Object[0]);
return result;
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
catch (IllegalAccessException iae) {
iae.printStackTrace();
}
catch (InvocationTargetException ite) {
ite.printStackTrace();
}
return null;
} | [
"private",
"Object",
"getPropertyValue",
"(",
"Object",
"pObj",
",",
"String",
"pProperty",
")",
"{",
"Method",
"m",
"=",
"null",
";",
"Class",
"[",
"]",
"cl",
"=",
"new",
"Class",
"[",
"0",
"]",
";",
"try",
"{",
"//return Util.getPropertyValue(pObj, pProper... | Gets the property value from an object using reflection
@param obj The object to get a property from
@param property The name of the property
@return The property value as an Object | [
"Gets",
"the",
"property",
"value",
"from",
"an",
"object",
"using",
"reflection"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java#L368-L395 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java | ObjectReader.setChildObjects | private void setChildObjects(Object pParent, ObjectMapper pOM)
throws SQLException {
if (pOM == null) {
throw new NullPointerException("ObjectMapper in readChildObjects "
+ "cannot be null!!");
}
for (Enumeration keys = pOM.mMapTypes.keys(); keys.hasMoreElements();) {
String property = (String) keys.nextElement();
String mapType = (String) pOM.mMapTypes.get(property);
if (property.length() <= 0 || mapType == null) {
continue;
}
// Get the id of the parent
Object id = getPropertyValue(pParent,
pOM.getProperty(pOM.getPrimaryKey()));
if (mapType.equals(ObjectMapper.OBJECTMAP)) {
// OBJECT Mapping
// Get the class for this property
Class objectClass = (Class) pOM.mClasses.get(property);
DatabaseReadable dbr = null;
try {
dbr = (DatabaseReadable) objectClass.newInstance();
}
catch (Exception e) {
mLog.logError(e);
}
/*
Properties mapping = readMapping(objectClass);
*/
// Get property mapping for child object
if (pOM.mJoins.containsKey(property))
// mapping.setProperty(".join", (String) pOM.joins.get(property));
dbr.getMapping().put(".join", pOM.mJoins.get(property));
// Find id and put in where hash
Hashtable where = new Hashtable();
// String foreignKey = mapping.getProperty(".foreignKey");
String foreignKey = (String)
dbr.getMapping().get(".foreignKey");
if (foreignKey != null) {
where.put(".foreignKey", id);
}
Object[] child = readObjects(dbr, where);
// Object[] child = readObjects(objectClass, mapping, where);
if (child.length < 1)
throw new SQLException("No child object with foreign key "
+ foreignKey + "=" + id);
else if (child.length != 1)
throw new SQLException("More than one object with foreign "
+ "key " + foreignKey + "=" + id);
// Set child object to the parent
setPropertyValue(pParent, property, child[0]);
}
else if (mapType.equals(ObjectMapper.COLLECTIONMAP)) {
// COLLECTION Mapping
// Get property mapping for child object
Hashtable mapping = pOM.getPropertyMapping(property);
// Find id and put in where hash
Hashtable where = new Hashtable();
String foreignKey = (String) mapping.get(".foreignKey");
if (foreignKey != null) {
where.put(".foreignKey", id);
}
DBObject dbr = new DBObject();
dbr.mapping = mapping; // ugh...
// Read the objects
Object[] objs = readObjects(dbr, where);
// Put the objects in a hash
Hashtable children = new Hashtable();
for (int i = 0; i < objs.length; i++) {
children.put(((DBObject) objs[i]).getId(),
((DBObject) objs[i]).getObject());
}
// Set child properties to parent object
setPropertyValue(pParent, property, children);
}
}
} | java | private void setChildObjects(Object pParent, ObjectMapper pOM)
throws SQLException {
if (pOM == null) {
throw new NullPointerException("ObjectMapper in readChildObjects "
+ "cannot be null!!");
}
for (Enumeration keys = pOM.mMapTypes.keys(); keys.hasMoreElements();) {
String property = (String) keys.nextElement();
String mapType = (String) pOM.mMapTypes.get(property);
if (property.length() <= 0 || mapType == null) {
continue;
}
// Get the id of the parent
Object id = getPropertyValue(pParent,
pOM.getProperty(pOM.getPrimaryKey()));
if (mapType.equals(ObjectMapper.OBJECTMAP)) {
// OBJECT Mapping
// Get the class for this property
Class objectClass = (Class) pOM.mClasses.get(property);
DatabaseReadable dbr = null;
try {
dbr = (DatabaseReadable) objectClass.newInstance();
}
catch (Exception e) {
mLog.logError(e);
}
/*
Properties mapping = readMapping(objectClass);
*/
// Get property mapping for child object
if (pOM.mJoins.containsKey(property))
// mapping.setProperty(".join", (String) pOM.joins.get(property));
dbr.getMapping().put(".join", pOM.mJoins.get(property));
// Find id and put in where hash
Hashtable where = new Hashtable();
// String foreignKey = mapping.getProperty(".foreignKey");
String foreignKey = (String)
dbr.getMapping().get(".foreignKey");
if (foreignKey != null) {
where.put(".foreignKey", id);
}
Object[] child = readObjects(dbr, where);
// Object[] child = readObjects(objectClass, mapping, where);
if (child.length < 1)
throw new SQLException("No child object with foreign key "
+ foreignKey + "=" + id);
else if (child.length != 1)
throw new SQLException("More than one object with foreign "
+ "key " + foreignKey + "=" + id);
// Set child object to the parent
setPropertyValue(pParent, property, child[0]);
}
else if (mapType.equals(ObjectMapper.COLLECTIONMAP)) {
// COLLECTION Mapping
// Get property mapping for child object
Hashtable mapping = pOM.getPropertyMapping(property);
// Find id and put in where hash
Hashtable where = new Hashtable();
String foreignKey = (String) mapping.get(".foreignKey");
if (foreignKey != null) {
where.put(".foreignKey", id);
}
DBObject dbr = new DBObject();
dbr.mapping = mapping; // ugh...
// Read the objects
Object[] objs = readObjects(dbr, where);
// Put the objects in a hash
Hashtable children = new Hashtable();
for (int i = 0; i < objs.length; i++) {
children.put(((DBObject) objs[i]).getId(),
((DBObject) objs[i]).getObject());
}
// Set child properties to parent object
setPropertyValue(pParent, property, children);
}
}
} | [
"private",
"void",
"setChildObjects",
"(",
"Object",
"pParent",
",",
"ObjectMapper",
"pOM",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"pOM",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"ObjectMapper in readChildObjects \"",
"+",
"\"... | Reads and sets the child properties of the given parent object.
@param parent The object to set the child obects to.
@param om The ObjectMapper of the parent object. | [
"Reads",
"and",
"sets",
"the",
"child",
"properties",
"of",
"the",
"given",
"parent",
"object",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java#L404-L499 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java | ObjectReader.buildWhereClause | private String buildWhereClause(String[] pKeys, Hashtable pMapping) {
StringBuilder sqlBuf = new StringBuilder();
for (int i = 0; i < pKeys.length; i++) {
String column = (String) pMapping.get(pKeys[i]);
sqlBuf.append(" AND ");
sqlBuf.append(column);
sqlBuf.append(" = ?");
}
return sqlBuf.toString();
} | java | private String buildWhereClause(String[] pKeys, Hashtable pMapping) {
StringBuilder sqlBuf = new StringBuilder();
for (int i = 0; i < pKeys.length; i++) {
String column = (String) pMapping.get(pKeys[i]);
sqlBuf.append(" AND ");
sqlBuf.append(column);
sqlBuf.append(" = ?");
}
return sqlBuf.toString();
} | [
"private",
"String",
"buildWhereClause",
"(",
"String",
"[",
"]",
"pKeys",
",",
"Hashtable",
"pMapping",
")",
"{",
"StringBuilder",
"sqlBuf",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"pKeys",
".",
"le... | Builds extra SQL WHERE clause
@param keys An array of ID names
@param mapping The hashtable containing the object mapping
@return A string containing valid SQL | [
"Builds",
"extra",
"SQL",
"WHERE",
"clause"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java#L524-L536 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java | ObjectReader.loadMapping | public static Properties loadMapping(Class pClass) {
try {
return SystemUtil.loadProperties(pClass);
}
catch (FileNotFoundException fnf) {
// System.err... err...
System.err.println("ERROR: " + fnf.getMessage());
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return new Properties();
} | java | public static Properties loadMapping(Class pClass) {
try {
return SystemUtil.loadProperties(pClass);
}
catch (FileNotFoundException fnf) {
// System.err... err...
System.err.println("ERROR: " + fnf.getMessage());
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return new Properties();
} | [
"public",
"static",
"Properties",
"loadMapping",
"(",
"Class",
"pClass",
")",
"{",
"try",
"{",
"return",
"SystemUtil",
".",
"loadProperties",
"(",
"pClass",
")",
";",
"}",
"catch",
"(",
"FileNotFoundException",
"fnf",
")",
"{",
"// System.err... err... \r",
"Sys... | Utility method for reading a property mapping from a properties-file | [
"Utility",
"method",
"for",
"reading",
"a",
"property",
"mapping",
"from",
"a",
"properties",
"-",
"file"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectReader.java#L822-L834 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectManager.java | ObjectManager.getType | protected Class getType(String pType) {
Class cl = (Class) mTypes.get(pType);
if (cl == null) {
// throw new NoSuchTypeException();
}
return cl;
} | java | protected Class getType(String pType) {
Class cl = (Class) mTypes.get(pType);
if (cl == null) {
// throw new NoSuchTypeException();
}
return cl;
} | [
"protected",
"Class",
"getType",
"(",
"String",
"pType",
")",
"{",
"Class",
"cl",
"=",
"(",
"Class",
")",
"mTypes",
".",
"get",
"(",
"pType",
")",
";",
"if",
"(",
"cl",
"==",
"null",
")",
"{",
"// throw new NoSuchTypeException();\r",
"}",
"return",
"cl",... | Gets the class for a type
@return The class for a type. If the type is not found, this method will
throw an excpetion, and will never return null. | [
"Gets",
"the",
"class",
"for",
"a",
"type"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectManager.java#L93-L101 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectManager.java | ObjectManager.getObject | protected Object getObject(String pType)
/*throws XxxException*/ {
// Get class
Class cl = getType(pType);
// Return the new instance (requires empty public constructor)
try {
return cl.newInstance();
}
catch (Exception e) {
// throw new XxxException(e);
throw new RuntimeException(e.getMessage());
}
// Can't happen
//return null;
} | java | protected Object getObject(String pType)
/*throws XxxException*/ {
// Get class
Class cl = getType(pType);
// Return the new instance (requires empty public constructor)
try {
return cl.newInstance();
}
catch (Exception e) {
// throw new XxxException(e);
throw new RuntimeException(e.getMessage());
}
// Can't happen
//return null;
} | [
"protected",
"Object",
"getObject",
"(",
"String",
"pType",
")",
"/*throws XxxException*/",
"{",
"// Get class\r",
"Class",
"cl",
"=",
"getType",
"(",
"pType",
")",
";",
"// Return the new instance (requires empty public constructor)\r",
"try",
"{",
"return",
"cl",
".",... | Gets a java object of the class for a given type. | [
"Gets",
"a",
"java",
"object",
"of",
"the",
"class",
"for",
"a",
"given",
"type",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/sql/ObjectManager.java#L107-L123 | train |
haraldk/TwelveMonkeys | imageio/imageio-core/src/main/java/com/twelvemonkeys/imageio/ImageReaderBase.java | ImageReaderBase.checkBounds | protected void checkBounds(int index) throws IOException {
assertInput();
if (index < getMinIndex()) {
throw new IndexOutOfBoundsException("index < minIndex");
}
int numImages = getNumImages(false);
if (numImages != -1 && index >= numImages) {
throw new IndexOutOfBoundsException("index >= numImages (" + index + " >= " + numImages + ")");
}
} | java | protected void checkBounds(int index) throws IOException {
assertInput();
if (index < getMinIndex()) {
throw new IndexOutOfBoundsException("index < minIndex");
}
int numImages = getNumImages(false);
if (numImages != -1 && index >= numImages) {
throw new IndexOutOfBoundsException("index >= numImages (" + index + " >= " + numImages + ")");
}
} | [
"protected",
"void",
"checkBounds",
"(",
"int",
"index",
")",
"throws",
"IOException",
"{",
"assertInput",
"(",
")",
";",
"if",
"(",
"index",
"<",
"getMinIndex",
"(",
")",
")",
"{",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
"\"index < minIndex\"",
")",... | Convenience method to make sure image index is within bounds.
@param index the image index
@throws java.io.IOException if an error occurs during reading
@throws IndexOutOfBoundsException if not {@code minIndex <= index < numImages} | [
"Convenience",
"method",
"to",
"make",
"sure",
"image",
"index",
"is",
"within",
"bounds",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-core/src/main/java/com/twelvemonkeys/imageio/ImageReaderBase.java#L183-L193 | train |
haraldk/TwelveMonkeys | imageio/imageio-core/src/main/java/com/twelvemonkeys/imageio/ImageReaderBase.java | ImageReaderBase.hasExplicitDestination | protected static boolean hasExplicitDestination(final ImageReadParam pParam) {
return pParam != null &&
(
pParam.getDestination() != null || pParam.getDestinationType() != null ||
!ORIGIN.equals(pParam.getDestinationOffset())
);
} | java | protected static boolean hasExplicitDestination(final ImageReadParam pParam) {
return pParam != null &&
(
pParam.getDestination() != null || pParam.getDestinationType() != null ||
!ORIGIN.equals(pParam.getDestinationOffset())
);
} | [
"protected",
"static",
"boolean",
"hasExplicitDestination",
"(",
"final",
"ImageReadParam",
"pParam",
")",
"{",
"return",
"pParam",
"!=",
"null",
"&&",
"(",
"pParam",
".",
"getDestination",
"(",
")",
"!=",
"null",
"||",
"pParam",
".",
"getDestinationType",
"(",
... | Tests if param has explicit destination.
@param pParam the image read parameter, or {@code null}
@return true if {@code pParam} is non-{@code null} and either its {@code getDestination},
{@code getDestinationType} returns a non-{@code null} value,
or {@code getDestinationOffset} returns a {@link Point} that is not the upper left corner {@code (0, 0)}. | [
"Tests",
"if",
"param",
"has",
"explicit",
"destination",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-core/src/main/java/com/twelvemonkeys/imageio/ImageReaderBase.java#L371-L377 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/image/ImageServletResponseImpl.java | ImageServletResponseImpl.getImage | public BufferedImage getImage() throws IOException {
if (image == null) {
// No content, no image
if (bufferedOut == null) {
return null;
}
// Read from the byte buffer
InputStream byteStream = bufferedOut.createInputStream();
ImageInputStream input = null;
try {
input = ImageIO.createImageInputStream(byteStream);
Iterator readers = ImageIO.getImageReaders(input);
if (readers.hasNext()) {
// Get the correct reader
ImageReader reader = (ImageReader) readers.next();
try {
reader.setInput(input);
ImageReadParam param = reader.getDefaultReadParam();
// Get default size
int originalWidth = reader.getWidth(0);
int originalHeight = reader.getHeight(0);
//////////////////
// PRE-PROCESS (prepare): param, size, format?, request, response?
// TODO: AOI strategy?
// Extract AOI from request
Rectangle aoi = extractAOIFromRequest(originalWidth, originalHeight, originalRequest);
if (aoi != null) {
param.setSourceRegion(aoi);
originalWidth = aoi.width;
originalHeight = aoi.height;
}
// TODO: Size and subsampling strategy?
// If possible, extract size from request
Dimension size = extractSizeFromRequest(originalWidth, originalHeight, originalRequest);
double readSubSamplingFactor = getReadSubsampleFactorFromRequest(originalRequest);
if (size != null) {
//System.out.println("Size: " + size);
if (param.canSetSourceRenderSize()) {
param.setSourceRenderSize(size);
}
else {
int subX = (int) Math.max(originalWidth / (size.width * readSubSamplingFactor), 1.0);
int subY = (int) Math.max(originalHeight / (size.height * readSubSamplingFactor), 1.0);
if (subX > 1 || subY > 1) {
param.setSourceSubsampling(subX, subY, subX > 1 ? subX / 2 : 0, subY > 1 ? subY / 2 : 0);
}
}
}
// Need base URI for SVG with links/stylesheets etc
maybeSetBaseURIFromRequest(param);
/////////////////////
// Finally, read the image using the supplied parameter
BufferedImage image = reader.read(0, param);
// TODO: If we sub-sampled, it would be a good idea to blur before resampling,
// to avoid jagged lines artifacts
// If reader doesn't support dynamic sizing, scale now
image = resampleImage(image, size);
// Fill bgcolor behind image, if transparent
extractAndSetBackgroundColor(image); // TODO: Move to flush/POST-PROCESS
// Set image
this.image = image;
}
finally {
reader.dispose();
}
}
else {
context.log("ERROR: No suitable image reader found (content-type: " + originalContentType + ").");
context.log("ERROR: Available formats: " + getFormatsString());
throw new IIOException("Unable to transcode image: No suitable image reader found (content-type: " + originalContentType + ").");
}
// Free resources, as the image is now either read, or unreadable
bufferedOut = null;
}
finally {
if (input != null) {
input.close();
}
}
}
// Image is usually a BufferedImage, but may also be a RenderedImage
return image != null ? ImageUtil.toBuffered(image) : null;
} | java | public BufferedImage getImage() throws IOException {
if (image == null) {
// No content, no image
if (bufferedOut == null) {
return null;
}
// Read from the byte buffer
InputStream byteStream = bufferedOut.createInputStream();
ImageInputStream input = null;
try {
input = ImageIO.createImageInputStream(byteStream);
Iterator readers = ImageIO.getImageReaders(input);
if (readers.hasNext()) {
// Get the correct reader
ImageReader reader = (ImageReader) readers.next();
try {
reader.setInput(input);
ImageReadParam param = reader.getDefaultReadParam();
// Get default size
int originalWidth = reader.getWidth(0);
int originalHeight = reader.getHeight(0);
//////////////////
// PRE-PROCESS (prepare): param, size, format?, request, response?
// TODO: AOI strategy?
// Extract AOI from request
Rectangle aoi = extractAOIFromRequest(originalWidth, originalHeight, originalRequest);
if (aoi != null) {
param.setSourceRegion(aoi);
originalWidth = aoi.width;
originalHeight = aoi.height;
}
// TODO: Size and subsampling strategy?
// If possible, extract size from request
Dimension size = extractSizeFromRequest(originalWidth, originalHeight, originalRequest);
double readSubSamplingFactor = getReadSubsampleFactorFromRequest(originalRequest);
if (size != null) {
//System.out.println("Size: " + size);
if (param.canSetSourceRenderSize()) {
param.setSourceRenderSize(size);
}
else {
int subX = (int) Math.max(originalWidth / (size.width * readSubSamplingFactor), 1.0);
int subY = (int) Math.max(originalHeight / (size.height * readSubSamplingFactor), 1.0);
if (subX > 1 || subY > 1) {
param.setSourceSubsampling(subX, subY, subX > 1 ? subX / 2 : 0, subY > 1 ? subY / 2 : 0);
}
}
}
// Need base URI for SVG with links/stylesheets etc
maybeSetBaseURIFromRequest(param);
/////////////////////
// Finally, read the image using the supplied parameter
BufferedImage image = reader.read(0, param);
// TODO: If we sub-sampled, it would be a good idea to blur before resampling,
// to avoid jagged lines artifacts
// If reader doesn't support dynamic sizing, scale now
image = resampleImage(image, size);
// Fill bgcolor behind image, if transparent
extractAndSetBackgroundColor(image); // TODO: Move to flush/POST-PROCESS
// Set image
this.image = image;
}
finally {
reader.dispose();
}
}
else {
context.log("ERROR: No suitable image reader found (content-type: " + originalContentType + ").");
context.log("ERROR: Available formats: " + getFormatsString());
throw new IIOException("Unable to transcode image: No suitable image reader found (content-type: " + originalContentType + ").");
}
// Free resources, as the image is now either read, or unreadable
bufferedOut = null;
}
finally {
if (input != null) {
input.close();
}
}
}
// Image is usually a BufferedImage, but may also be a RenderedImage
return image != null ? ImageUtil.toBuffered(image) : null;
} | [
"public",
"BufferedImage",
"getImage",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"image",
"==",
"null",
")",
"{",
"// No content, no image\r",
"if",
"(",
"bufferedOut",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"// Read from the byte buffer\r"... | Gets the decoded image from the response.
@return a {@code BufferedImage} or {@code null} if the image could
not be read.
@throws java.io.IOException if an I/O exception occurs during reading | [
"Gets",
"the",
"decoded",
"image",
"from",
"the",
"response",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/image/ImageServletResponseImpl.java#L331-L430 | train |
haraldk/TwelveMonkeys | imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/QuickTime.java | QuickTime.getDecompressor | private static QTDecompressor getDecompressor(final ImageDesc pDescription) {
for (QTDecompressor decompressor : sDecompressors) {
if (decompressor.canDecompress(pDescription)) {
return decompressor;
}
}
return null;
} | java | private static QTDecompressor getDecompressor(final ImageDesc pDescription) {
for (QTDecompressor decompressor : sDecompressors) {
if (decompressor.canDecompress(pDescription)) {
return decompressor;
}
}
return null;
} | [
"private",
"static",
"QTDecompressor",
"getDecompressor",
"(",
"final",
"ImageDesc",
"pDescription",
")",
"{",
"for",
"(",
"QTDecompressor",
"decompressor",
":",
"sDecompressors",
")",
"{",
"if",
"(",
"decompressor",
".",
"canDecompress",
"(",
"pDescription",
")",
... | Gets a decompressor that can decompress the described data.
@param pDescription the image description ({@code 'idsc'} Atom).
@return a decompressor that can decompress data decribed by the given {@link ImageDesc description},
or {@code null} if no decompressor is found | [
"Gets",
"a",
"decompressor",
"that",
"can",
"decompress",
"the",
"described",
"data",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/QuickTime.java#L124-L132 | train |
haraldk/TwelveMonkeys | imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/QuickTime.java | QuickTime.decompress | public static BufferedImage decompress(final ImageInputStream pStream) throws IOException {
ImageDesc description = ImageDesc.read(pStream);
if (PICTImageReader.DEBUG) {
System.out.println(description);
}
QTDecompressor decompressor = getDecompressor(description);
if (decompressor == null) {
return null;
}
InputStream streamAdapter = IIOUtil.createStreamAdapter(pStream, description.dataSize);
try {
return decompressor.decompress(description, streamAdapter);
}
finally {
streamAdapter.close();
}
} | java | public static BufferedImage decompress(final ImageInputStream pStream) throws IOException {
ImageDesc description = ImageDesc.read(pStream);
if (PICTImageReader.DEBUG) {
System.out.println(description);
}
QTDecompressor decompressor = getDecompressor(description);
if (decompressor == null) {
return null;
}
InputStream streamAdapter = IIOUtil.createStreamAdapter(pStream, description.dataSize);
try {
return decompressor.decompress(description, streamAdapter);
}
finally {
streamAdapter.close();
}
} | [
"public",
"static",
"BufferedImage",
"decompress",
"(",
"final",
"ImageInputStream",
"pStream",
")",
"throws",
"IOException",
"{",
"ImageDesc",
"description",
"=",
"ImageDesc",
".",
"read",
"(",
"pStream",
")",
";",
"if",
"(",
"PICTImageReader",
".",
"DEBUG",
")... | Decompresses the QuickTime image data from the given stream.
@param pStream the image input stream
@return a {@link BufferedImage} containing the image data, or {@code null} if no decompressor is capable of
decompressing the image.
@throws IOException if an I/O exception occurs during read | [
"Decompresses",
"the",
"QuickTime",
"image",
"data",
"from",
"the",
"given",
"stream",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/QuickTime.java#L142-L162 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/image/ContentNegotiationFilter.java | ContentNegotiationFilter.trigger | protected boolean trigger(ServletRequest pRequest) {
boolean trigger = false;
if (pRequest instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) pRequest;
String accept = getAcceptedFormats(request);
String originalFormat = getServletContext().getMimeType(request.getRequestURI());
//System.out.println("Accept: " + accept);
//System.out.println("Original format: " + originalFormat);
// Only override original format if it is not accpeted by the client
// Note: Only explicit matches are okay, */* or image/* is not.
if (!StringUtil.contains(accept, originalFormat)) {
trigger = true;
}
}
// Call super, to allow content negotiation even though format is supported
return trigger || super.trigger(pRequest);
} | java | protected boolean trigger(ServletRequest pRequest) {
boolean trigger = false;
if (pRequest instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) pRequest;
String accept = getAcceptedFormats(request);
String originalFormat = getServletContext().getMimeType(request.getRequestURI());
//System.out.println("Accept: " + accept);
//System.out.println("Original format: " + originalFormat);
// Only override original format if it is not accpeted by the client
// Note: Only explicit matches are okay, */* or image/* is not.
if (!StringUtil.contains(accept, originalFormat)) {
trigger = true;
}
}
// Call super, to allow content negotiation even though format is supported
return trigger || super.trigger(pRequest);
} | [
"protected",
"boolean",
"trigger",
"(",
"ServletRequest",
"pRequest",
")",
"{",
"boolean",
"trigger",
"=",
"false",
";",
"if",
"(",
"pRequest",
"instanceof",
"HttpServletRequest",
")",
"{",
"HttpServletRequest",
"request",
"=",
"(",
"HttpServletRequest",
")",
"pRe... | Makes sure the filter triggers for unknown file formats.
@param pRequest the request
@return {@code true} if the filter should execute, {@code false}
otherwise | [
"Makes",
"sure",
"the",
"filter",
"triggers",
"for",
"unknown",
"file",
"formats",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/image/ContentNegotiationFilter.java#L155-L175 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/image/ContentNegotiationFilter.java | ContentNegotiationFilter.findBestFormat | private static String findBestFormat(Map<String, Float> pFormatQuality) {
String acceptable = null;
float acceptQuality = 0.0f;
for (Map.Entry<String, Float> entry : pFormatQuality.entrySet()) {
float qValue = entry.getValue();
if (qValue > acceptQuality) {
acceptQuality = qValue;
acceptable = entry.getKey();
}
}
//System.out.println("Accepted format: " + acceptable);
//System.out.println("Accepted quality: " + acceptQuality);
return acceptable;
} | java | private static String findBestFormat(Map<String, Float> pFormatQuality) {
String acceptable = null;
float acceptQuality = 0.0f;
for (Map.Entry<String, Float> entry : pFormatQuality.entrySet()) {
float qValue = entry.getValue();
if (qValue > acceptQuality) {
acceptQuality = qValue;
acceptable = entry.getKey();
}
}
//System.out.println("Accepted format: " + acceptable);
//System.out.println("Accepted quality: " + acceptQuality);
return acceptable;
} | [
"private",
"static",
"String",
"findBestFormat",
"(",
"Map",
"<",
"String",
",",
"Float",
">",
"pFormatQuality",
")",
"{",
"String",
"acceptable",
"=",
"null",
";",
"float",
"acceptQuality",
"=",
"0.0f",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",... | Finds the best available format.
@param pFormatQuality the format to quality mapping
@return the mime type of the best available format | [
"Finds",
"the",
"best",
"available",
"format",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/image/ContentNegotiationFilter.java#L275-L289 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/image/ContentNegotiationFilter.java | ContentNegotiationFilter.adjustQualityFromAccept | private void adjustQualityFromAccept(Map<String, Float> pFormatQuality, HttpServletRequest pRequest) {
// Multiply all q factors with qs factors
// No q=.. should be interpreted as q=1.0
// Apache does some extras; if both explicit types and wildcards
// (without qaulity factor) are present, */* is interpreted as
// */*;q=0.01 and image/* is interpreted as image/*;q=0.02
// See: http://httpd.apache.org/docs-2.0/content-negotiation.html
String accept = getAcceptedFormats(pRequest);
//System.out.println("Accept: " + accept);
float anyImageFactor = getQualityFactor(accept, MIME_TYPE_IMAGE_ANY);
anyImageFactor = (anyImageFactor == 1) ? 0.02f : anyImageFactor;
float anyFactor = getQualityFactor(accept, MIME_TYPE_ANY);
anyFactor = (anyFactor == 1) ? 0.01f : anyFactor;
for (String format : pFormatQuality.keySet()) {
//System.out.println("Trying format: " + format);
String formatMIME = MIME_TYPE_IMAGE_PREFIX + format;
float qFactor = getQualityFactor(accept, formatMIME);
qFactor = (qFactor == 0f) ? Math.max(anyFactor, anyImageFactor) : qFactor;
adjustQuality(pFormatQuality, format, qFactor);
}
} | java | private void adjustQualityFromAccept(Map<String, Float> pFormatQuality, HttpServletRequest pRequest) {
// Multiply all q factors with qs factors
// No q=.. should be interpreted as q=1.0
// Apache does some extras; if both explicit types and wildcards
// (without qaulity factor) are present, */* is interpreted as
// */*;q=0.01 and image/* is interpreted as image/*;q=0.02
// See: http://httpd.apache.org/docs-2.0/content-negotiation.html
String accept = getAcceptedFormats(pRequest);
//System.out.println("Accept: " + accept);
float anyImageFactor = getQualityFactor(accept, MIME_TYPE_IMAGE_ANY);
anyImageFactor = (anyImageFactor == 1) ? 0.02f : anyImageFactor;
float anyFactor = getQualityFactor(accept, MIME_TYPE_ANY);
anyFactor = (anyFactor == 1) ? 0.01f : anyFactor;
for (String format : pFormatQuality.keySet()) {
//System.out.println("Trying format: " + format);
String formatMIME = MIME_TYPE_IMAGE_PREFIX + format;
float qFactor = getQualityFactor(accept, formatMIME);
qFactor = (qFactor == 0f) ? Math.max(anyFactor, anyImageFactor) : qFactor;
adjustQuality(pFormatQuality, format, qFactor);
}
} | [
"private",
"void",
"adjustQualityFromAccept",
"(",
"Map",
"<",
"String",
",",
"Float",
">",
"pFormatQuality",
",",
"HttpServletRequest",
"pRequest",
")",
"{",
"// Multiply all q factors with qs factors\r",
"// No q=.. should be interpreted as q=1.0\r",
"// Apache does some extras... | Adjust quality from HTTP Accept header
@param pFormatQuality the format to quality mapping
@param pRequest the request | [
"Adjust",
"quality",
"from",
"HTTP",
"Accept",
"header"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/image/ContentNegotiationFilter.java#L297-L323 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/image/ContentNegotiationFilter.java | ContentNegotiationFilter.adjustQualityFromImage | private static void adjustQualityFromImage(Map<String, Float> pFormatQuality, BufferedImage pImage) {
// NOTE: The values are all made-up. May need tuning.
// If pImage.getColorModel() instanceof IndexColorModel
// JPEG qs*=0.6
// If NOT binary or 2 color index
// WBMP qs*=0.5
// Else
// GIF qs*=0.02
// PNG qs*=0.9 // JPEG is smaller/faster
if (pImage.getColorModel() instanceof IndexColorModel) {
adjustQuality(pFormatQuality, FORMAT_JPEG, 0.6f);
if (pImage.getType() != BufferedImage.TYPE_BYTE_BINARY || ((IndexColorModel) pImage.getColorModel()).getMapSize() != 2) {
adjustQuality(pFormatQuality, FORMAT_WBMP, 0.5f);
}
}
else {
adjustQuality(pFormatQuality, FORMAT_GIF, 0.01f);
adjustQuality(pFormatQuality, FORMAT_PNG, 0.99f); // JPEG is smaller/faster
}
// If pImage.getColorModel().hasTransparentPixels()
// JPEG qs*=0.05
// WBMP qs*=0.05
// If NOT transparency == BITMASK
// GIF qs*=0.8
if (ImageUtil.hasTransparentPixels(pImage, true)) {
adjustQuality(pFormatQuality, FORMAT_JPEG, 0.009f);
adjustQuality(pFormatQuality, FORMAT_WBMP, 0.009f);
if (pImage.getColorModel().getTransparency() != Transparency.BITMASK) {
adjustQuality(pFormatQuality, FORMAT_GIF, 0.8f);
}
}
} | java | private static void adjustQualityFromImage(Map<String, Float> pFormatQuality, BufferedImage pImage) {
// NOTE: The values are all made-up. May need tuning.
// If pImage.getColorModel() instanceof IndexColorModel
// JPEG qs*=0.6
// If NOT binary or 2 color index
// WBMP qs*=0.5
// Else
// GIF qs*=0.02
// PNG qs*=0.9 // JPEG is smaller/faster
if (pImage.getColorModel() instanceof IndexColorModel) {
adjustQuality(pFormatQuality, FORMAT_JPEG, 0.6f);
if (pImage.getType() != BufferedImage.TYPE_BYTE_BINARY || ((IndexColorModel) pImage.getColorModel()).getMapSize() != 2) {
adjustQuality(pFormatQuality, FORMAT_WBMP, 0.5f);
}
}
else {
adjustQuality(pFormatQuality, FORMAT_GIF, 0.01f);
adjustQuality(pFormatQuality, FORMAT_PNG, 0.99f); // JPEG is smaller/faster
}
// If pImage.getColorModel().hasTransparentPixels()
// JPEG qs*=0.05
// WBMP qs*=0.05
// If NOT transparency == BITMASK
// GIF qs*=0.8
if (ImageUtil.hasTransparentPixels(pImage, true)) {
adjustQuality(pFormatQuality, FORMAT_JPEG, 0.009f);
adjustQuality(pFormatQuality, FORMAT_WBMP, 0.009f);
if (pImage.getColorModel().getTransparency() != Transparency.BITMASK) {
adjustQuality(pFormatQuality, FORMAT_GIF, 0.8f);
}
}
} | [
"private",
"static",
"void",
"adjustQualityFromImage",
"(",
"Map",
"<",
"String",
",",
"Float",
">",
"pFormatQuality",
",",
"BufferedImage",
"pImage",
")",
"{",
"// NOTE: The values are all made-up. May need tuning.\r",
"// If pImage.getColorModel() instanceof IndexColorModel\r",... | Adjusts source quality settings from image properties.
@param pFormatQuality the format to quality mapping
@param pImage the image | [
"Adjusts",
"source",
"quality",
"settings",
"from",
"image",
"properties",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/image/ContentNegotiationFilter.java#L375-L410 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/image/ContentNegotiationFilter.java | ContentNegotiationFilter.adjustQuality | private static void adjustQuality(Map<String, Float> pFormatQuality, String pFormat, float pFactor) {
Float oldValue = pFormatQuality.get(pFormat);
if (oldValue != null) {
pFormatQuality.put(pFormat, oldValue * pFactor);
//System.out.println("New vallue after multiplying with " + pFactor + " is " + pFormatQuality.get(pFormat));
}
} | java | private static void adjustQuality(Map<String, Float> pFormatQuality, String pFormat, float pFactor) {
Float oldValue = pFormatQuality.get(pFormat);
if (oldValue != null) {
pFormatQuality.put(pFormat, oldValue * pFactor);
//System.out.println("New vallue after multiplying with " + pFactor + " is " + pFormatQuality.get(pFormat));
}
} | [
"private",
"static",
"void",
"adjustQuality",
"(",
"Map",
"<",
"String",
",",
"Float",
">",
"pFormatQuality",
",",
"String",
"pFormat",
",",
"float",
"pFactor",
")",
"{",
"Float",
"oldValue",
"=",
"pFormatQuality",
".",
"get",
"(",
"pFormat",
")",
";",
"if... | Updates the quality in the map.
@param pFormatQuality Map<String,Float>
@param pFormat the format
@param pFactor the quality factor | [
"Updates",
"the",
"quality",
"in",
"the",
"map",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/image/ContentNegotiationFilter.java#L419-L425 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/image/ContentNegotiationFilter.java | ContentNegotiationFilter.getKnownFormatQuality | private float getKnownFormatQuality(String pFormat) {
for (int i = 0; i < sKnownFormats.length; i++) {
if (pFormat.equals(sKnownFormats[i])) {
return knownFormatQuality[i];
}
}
return 0.1f;
} | java | private float getKnownFormatQuality(String pFormat) {
for (int i = 0; i < sKnownFormats.length; i++) {
if (pFormat.equals(sKnownFormats[i])) {
return knownFormatQuality[i];
}
}
return 0.1f;
} | [
"private",
"float",
"getKnownFormatQuality",
"(",
"String",
"pFormat",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"sKnownFormats",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"pFormat",
".",
"equals",
"(",
"sKnownFormats",
"[",
... | Gets the initial quality if this is a known format, otherwise 0.1
@param pFormat the format name
@return the q factor of the given format | [
"Gets",
"the",
"initial",
"quality",
"if",
"this",
"is",
"a",
"known",
"format",
"otherwise",
"0",
".",
"1"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/image/ContentNegotiationFilter.java#L434-L441 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/OutputStreamAdapter.java | OutputStreamAdapter.write | public void write(final byte pBytes[], final int pOff, final int pLen) throws IOException {
out.write(pBytes, pOff, pLen);
} | java | public void write(final byte pBytes[], final int pOff, final int pLen) throws IOException {
out.write(pBytes, pOff, pLen);
} | [
"public",
"void",
"write",
"(",
"final",
"byte",
"pBytes",
"[",
"]",
",",
"final",
"int",
"pOff",
",",
"final",
"int",
"pLen",
")",
"throws",
"IOException",
"{",
"out",
".",
"write",
"(",
"pBytes",
",",
"pOff",
",",
"pLen",
")",
";",
"}"
] | Overide for efficiency | [
"Overide",
"for",
"efficiency"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/OutputStreamAdapter.java#L119-L121 | train |
haraldk/TwelveMonkeys | common/common-io/src/main/java/com/twelvemonkeys/io/enc/PackBitsDecoder.java | PackBitsDecoder.decode | public int decode(final InputStream stream, final ByteBuffer buffer) throws IOException {
if (reachedEOF) {
return -1;
}
// TODO: Don't decode more than single runs, because some writers add pad bytes inside the stream...
while (buffer.hasRemaining()) {
int n;
if (splitRun) {
// Continue run
n = leftOfRun;
splitRun = false;
}
else {
// Start new run
int b = stream.read();
if (b < 0) {
reachedEOF = true;
break;
}
n = (byte) b;
}
// Split run at or before max
if (n >= 0 && n + 1 > buffer.remaining()) {
leftOfRun = n;
splitRun = true;
break;
}
else if (n < 0 && -n + 1 > buffer.remaining()) {
leftOfRun = n;
splitRun = true;
break;
}
try {
if (n >= 0) {
// Copy next n + 1 bytes literally
readFully(stream, buffer, sample.length * (n + 1));
}
// Allow -128 for compatibility, see above
else if (disableNoOp || n != -128) {
// Replicate the next byte -n + 1 times
for (int s = 0; s < sample.length; s++) {
sample[s] = readByte(stream);
}
for (int i = -n + 1; i > 0; i--) {
buffer.put(sample);
}
}
// else NOOP (-128)
}
catch (IndexOutOfBoundsException e) {
throw new DecodeException("Error in PackBits decompression, data seems corrupt", e);
}
}
return buffer.position();
} | java | public int decode(final InputStream stream, final ByteBuffer buffer) throws IOException {
if (reachedEOF) {
return -1;
}
// TODO: Don't decode more than single runs, because some writers add pad bytes inside the stream...
while (buffer.hasRemaining()) {
int n;
if (splitRun) {
// Continue run
n = leftOfRun;
splitRun = false;
}
else {
// Start new run
int b = stream.read();
if (b < 0) {
reachedEOF = true;
break;
}
n = (byte) b;
}
// Split run at or before max
if (n >= 0 && n + 1 > buffer.remaining()) {
leftOfRun = n;
splitRun = true;
break;
}
else if (n < 0 && -n + 1 > buffer.remaining()) {
leftOfRun = n;
splitRun = true;
break;
}
try {
if (n >= 0) {
// Copy next n + 1 bytes literally
readFully(stream, buffer, sample.length * (n + 1));
}
// Allow -128 for compatibility, see above
else if (disableNoOp || n != -128) {
// Replicate the next byte -n + 1 times
for (int s = 0; s < sample.length; s++) {
sample[s] = readByte(stream);
}
for (int i = -n + 1; i > 0; i--) {
buffer.put(sample);
}
}
// else NOOP (-128)
}
catch (IndexOutOfBoundsException e) {
throw new DecodeException("Error in PackBits decompression, data seems corrupt", e);
}
}
return buffer.position();
} | [
"public",
"int",
"decode",
"(",
"final",
"InputStream",
"stream",
",",
"final",
"ByteBuffer",
"buffer",
")",
"throws",
"IOException",
"{",
"if",
"(",
"reachedEOF",
")",
"{",
"return",
"-",
"1",
";",
"}",
"// TODO: Don't decode more than single runs, because some wri... | Decodes bytes from the given input stream, to the given buffer.
@param stream the stream to decode from
@param buffer a byte array, minimum 128 (or 129 if no-op is disabled) bytes long
@return The number of bytes decoded
@throws java.io.IOException | [
"Decodes",
"bytes",
"from",
"the",
"given",
"input",
"stream",
"to",
"the",
"given",
"buffer",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-io/src/main/java/com/twelvemonkeys/io/enc/PackBitsDecoder.java#L119-L179 | train |
haraldk/TwelveMonkeys | imageio/imageio-core/src/main/java/com/twelvemonkeys/imageio/color/CIELabColorConverter.java | CIELabColorConverter.LABtoXYZ | private float[] LABtoXYZ(float L, float a, float b, float[] xyzResult) {
// Significant speedup: Removing Math.pow
float y = (L + 16.0f) / 116.0f;
float y3 = y * y * y; // Math.pow(y, 3.0);
float x = (a / 500.0f) + y;
float x3 = x * x * x; // Math.pow(x, 3.0);
float z = y - (b / 200.0f);
float z3 = z * z * z; // Math.pow(z, 3.0);
if (y3 > 0.008856f) {
y = y3;
}
else {
y = (y - (16.0f / 116.0f)) / 7.787f;
}
if (x3 > 0.008856f) {
x = x3;
}
else {
x = (x - (16.0f / 116.0f)) / 7.787f;
}
if (z3 > 0.008856f) {
z = z3;
}
else {
z = (z - (16.0f / 116.0f)) / 7.787f;
}
xyzResult[0] = x * whitePoint[0];
xyzResult[1] = y * whitePoint[1];
xyzResult[2] = z * whitePoint[2];
return xyzResult;
} | java | private float[] LABtoXYZ(float L, float a, float b, float[] xyzResult) {
// Significant speedup: Removing Math.pow
float y = (L + 16.0f) / 116.0f;
float y3 = y * y * y; // Math.pow(y, 3.0);
float x = (a / 500.0f) + y;
float x3 = x * x * x; // Math.pow(x, 3.0);
float z = y - (b / 200.0f);
float z3 = z * z * z; // Math.pow(z, 3.0);
if (y3 > 0.008856f) {
y = y3;
}
else {
y = (y - (16.0f / 116.0f)) / 7.787f;
}
if (x3 > 0.008856f) {
x = x3;
}
else {
x = (x - (16.0f / 116.0f)) / 7.787f;
}
if (z3 > 0.008856f) {
z = z3;
}
else {
z = (z - (16.0f / 116.0f)) / 7.787f;
}
xyzResult[0] = x * whitePoint[0];
xyzResult[1] = y * whitePoint[1];
xyzResult[2] = z * whitePoint[2];
return xyzResult;
} | [
"private",
"float",
"[",
"]",
"LABtoXYZ",
"(",
"float",
"L",
",",
"float",
"a",
",",
"float",
"b",
",",
"float",
"[",
"]",
"xyzResult",
")",
"{",
"// Significant speedup: Removing Math.pow",
"float",
"y",
"=",
"(",
"L",
"+",
"16.0f",
")",
"/",
"116.0f",
... | Convert LAB to XYZ.
@param L
@param a
@param b
@return XYZ values | [
"Convert",
"LAB",
"to",
"XYZ",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-core/src/main/java/com/twelvemonkeys/imageio/color/CIELabColorConverter.java#L88-L123 | train |
haraldk/TwelveMonkeys | common/common-lang/src/main/java/com/twelvemonkeys/util/convert/NumberConverter.java | NumberConverter.toObject | public Object toObject(final String pString, final Class pType, final String pFormat) throws ConversionException {
if (StringUtil.isEmpty(pString)) {
return null;
}
try {
if (pType.equals(BigInteger.class)) {
return new BigInteger(pString); // No format?
}
if (pType.equals(BigDecimal.class)) {
return new BigDecimal(pString); // No format?
}
NumberFormat format;
if (pFormat == null) {
// Use system default format, using default locale
format = sDefaultFormat;
}
else {
// Get format from cache
format = getNumberFormat(pFormat);
}
Number num;
synchronized (format) {
num = format.parse(pString);
}
if (pType == Integer.TYPE || pType == Integer.class) {
return num.intValue();
}
else if (pType == Long.TYPE || pType == Long.class) {
return num.longValue();
}
else if (pType == Double.TYPE || pType == Double.class) {
return num.doubleValue();
}
else if (pType == Float.TYPE || pType == Float.class) {
return num.floatValue();
}
else if (pType == Byte.TYPE || pType == Byte.class) {
return num.byteValue();
}
else if (pType == Short.TYPE || pType == Short.class) {
return num.shortValue();
}
return num;
}
catch (ParseException pe) {
throw new ConversionException(pe);
}
catch (RuntimeException rte) {
throw new ConversionException(rte);
}
} | java | public Object toObject(final String pString, final Class pType, final String pFormat) throws ConversionException {
if (StringUtil.isEmpty(pString)) {
return null;
}
try {
if (pType.equals(BigInteger.class)) {
return new BigInteger(pString); // No format?
}
if (pType.equals(BigDecimal.class)) {
return new BigDecimal(pString); // No format?
}
NumberFormat format;
if (pFormat == null) {
// Use system default format, using default locale
format = sDefaultFormat;
}
else {
// Get format from cache
format = getNumberFormat(pFormat);
}
Number num;
synchronized (format) {
num = format.parse(pString);
}
if (pType == Integer.TYPE || pType == Integer.class) {
return num.intValue();
}
else if (pType == Long.TYPE || pType == Long.class) {
return num.longValue();
}
else if (pType == Double.TYPE || pType == Double.class) {
return num.doubleValue();
}
else if (pType == Float.TYPE || pType == Float.class) {
return num.floatValue();
}
else if (pType == Byte.TYPE || pType == Byte.class) {
return num.byteValue();
}
else if (pType == Short.TYPE || pType == Short.class) {
return num.shortValue();
}
return num;
}
catch (ParseException pe) {
throw new ConversionException(pe);
}
catch (RuntimeException rte) {
throw new ConversionException(rte);
}
} | [
"public",
"Object",
"toObject",
"(",
"final",
"String",
"pString",
",",
"final",
"Class",
"pType",
",",
"final",
"String",
"pFormat",
")",
"throws",
"ConversionException",
"{",
"if",
"(",
"StringUtil",
".",
"isEmpty",
"(",
"pString",
")",
")",
"{",
"return",... | Converts the string to a number, using the given format for parsing.
@param pString the string to convert.
@param pType the type to convert to. PropertyConverter
implementations may choose to ignore this parameter.
@param pFormat the format used for parsing. PropertyConverter
implementations may choose to ignore this parameter. Also,
implementations that require a parser format, should provide a default
format, and allow {@code null} as the format argument.
@return the object created from the given string. May safely be typecast
to {@code java.lang.Number} or the class of the {@code type} parameter.
@see Number
@see java.text.NumberFormat
@throws ConversionException | [
"Converts",
"the",
"string",
"to",
"a",
"number",
"using",
"the",
"given",
"format",
"for",
"parsing",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-lang/src/main/java/com/twelvemonkeys/util/convert/NumberConverter.java#L83-L139 | train |
haraldk/TwelveMonkeys | imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/QuickDrawContext.java | QuickDrawContext.setPenSize | public void setPenSize(Dimension2D pSize) {
penSize.setSize(pSize);
graphics.setStroke(getStroke(penSize));
} | java | public void setPenSize(Dimension2D pSize) {
penSize.setSize(pSize);
graphics.setStroke(getStroke(penSize));
} | [
"public",
"void",
"setPenSize",
"(",
"Dimension2D",
"pSize",
")",
"{",
"penSize",
".",
"setSize",
"(",
"pSize",
")",
";",
"graphics",
".",
"setStroke",
"(",
"getStroke",
"(",
"penSize",
")",
")",
";",
"}"
] | Sets the pen size.
PenSize
@param pSize the new size | [
"Sets",
"the",
"pen",
"size",
".",
"PenSize"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/QuickDrawContext.java#L274-L277 | train |
haraldk/TwelveMonkeys | imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/QuickDrawContext.java | QuickDrawContext.setupForFill | protected void setupForFill(final Pattern pPattern) {
graphics.setPaint(pPattern);
graphics.setComposite(getCompositeFor(QuickDraw.PAT_COPY));
} | java | protected void setupForFill(final Pattern pPattern) {
graphics.setPaint(pPattern);
graphics.setComposite(getCompositeFor(QuickDraw.PAT_COPY));
} | [
"protected",
"void",
"setupForFill",
"(",
"final",
"Pattern",
"pPattern",
")",
"{",
"graphics",
".",
"setPaint",
"(",
"pPattern",
")",
";",
"graphics",
".",
"setComposite",
"(",
"getCompositeFor",
"(",
"QuickDraw",
".",
"PAT_COPY",
")",
")",
";",
"}"
] | Sets up paint context for fill.
@param pPattern the pattern to use for filling. | [
"Sets",
"up",
"paint",
"context",
"for",
"fill",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/QuickDrawContext.java#L440-L443 | train |
haraldk/TwelveMonkeys | imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/QuickDrawContext.java | QuickDrawContext.toArc | private static Arc2D.Double toArc(final Rectangle2D pRectangle, int pStartAngle, int pArcAngle, final boolean pClosed) {
return new Arc2D.Double(pRectangle, 90 - pStartAngle, -pArcAngle, pClosed ? Arc2D.PIE : Arc2D.OPEN);
} | java | private static Arc2D.Double toArc(final Rectangle2D pRectangle, int pStartAngle, int pArcAngle, final boolean pClosed) {
return new Arc2D.Double(pRectangle, 90 - pStartAngle, -pArcAngle, pClosed ? Arc2D.PIE : Arc2D.OPEN);
} | [
"private",
"static",
"Arc2D",
".",
"Double",
"toArc",
"(",
"final",
"Rectangle2D",
"pRectangle",
",",
"int",
"pStartAngle",
",",
"int",
"pArcAngle",
",",
"final",
"boolean",
"pClosed",
")",
"{",
"return",
"new",
"Arc2D",
".",
"Double",
"(",
"pRectangle",
","... | Converts a rectangle to an arc.
@param pRectangle the framing rectangle
@param pStartAngle start angle in degrees (starting from 12'o clock, this differs from Java)
@param pArcAngle rotation angle in degrees (starting from {@code pStartAngle}, this differs from Java arcs)
@param pClosed specifies if the arc should be closed
@return the arc | [
"Converts",
"a",
"rectangle",
"to",
"an",
"arc",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/QuickDrawContext.java#L716-L718 | train |
haraldk/TwelveMonkeys | imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/QuickDrawContext.java | QuickDrawContext.drawString | public void drawString(String pString) {
setupForText();
graphics.drawString(pString, (float) getPenPosition().getX(), (float) getPenPosition().getY());
} | java | public void drawString(String pString) {
setupForText();
graphics.drawString(pString, (float) getPenPosition().getX(), (float) getPenPosition().getY());
} | [
"public",
"void",
"drawString",
"(",
"String",
"pString",
")",
"{",
"setupForText",
"(",
")",
";",
"graphics",
".",
"drawString",
"(",
"pString",
",",
"(",
"float",
")",
"getPenPosition",
"(",
")",
".",
"getX",
"(",
")",
",",
"(",
"float",
")",
"getPen... | DrawString - draws the text of a Pascal string.
@param pString a Pascal string (a string of length less than or equal to 255 chars). | [
"DrawString",
"-",
"draws",
"the",
"text",
"of",
"a",
"Pascal",
"string",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/QuickDrawContext.java#L1012-L1015 | train |
haraldk/TwelveMonkeys | imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/PICTUtil.java | PICTUtil.readDimension | public static Dimension readDimension(final DataInput pStream) throws IOException {
int h = pStream.readShort();
int v = pStream.readShort();
return new Dimension(h, v);
} | java | public static Dimension readDimension(final DataInput pStream) throws IOException {
int h = pStream.readShort();
int v = pStream.readShort();
return new Dimension(h, v);
} | [
"public",
"static",
"Dimension",
"readDimension",
"(",
"final",
"DataInput",
"pStream",
")",
"throws",
"IOException",
"{",
"int",
"h",
"=",
"pStream",
".",
"readShort",
"(",
")",
";",
"int",
"v",
"=",
"pStream",
".",
"readShort",
"(",
")",
";",
"return",
... | Reads a dimension from the given stream.
@param pStream the input stream
@return the dimension read
@throws java.io.IOException if an I/O error occurs during read | [
"Reads",
"a",
"dimension",
"from",
"the",
"given",
"stream",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/PICTUtil.java#L90-L94 | train |
haraldk/TwelveMonkeys | imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/PICTUtil.java | PICTUtil.readStr31 | public static String readStr31(final DataInput pStream) throws IOException {
String text = readPascalString(pStream);
int length = 31 - text.length();
if (length < 0) {
throw new IOException("String length exceeds maximum (31): " + text.length());
}
pStream.skipBytes(length);
return text;
} | java | public static String readStr31(final DataInput pStream) throws IOException {
String text = readPascalString(pStream);
int length = 31 - text.length();
if (length < 0) {
throw new IOException("String length exceeds maximum (31): " + text.length());
}
pStream.skipBytes(length);
return text;
} | [
"public",
"static",
"String",
"readStr31",
"(",
"final",
"DataInput",
"pStream",
")",
"throws",
"IOException",
"{",
"String",
"text",
"=",
"readPascalString",
"(",
"pStream",
")",
";",
"int",
"length",
"=",
"31",
"-",
"text",
".",
"length",
"(",
")",
";",
... | Reads a 32 byte fixed length Pascal string from the given input.
The input stream must be positioned at the length byte of the text,
the text will be no longer than 31 characters long.
@param pStream the input stream
@return the text read
@throws IOException if an I/O exception occurs during reading | [
"Reads",
"a",
"32",
"byte",
"fixed",
"length",
"Pascal",
"string",
"from",
"the",
"given",
"input",
".",
"The",
"input",
"stream",
"must",
"be",
"positioned",
"at",
"the",
"length",
"byte",
"of",
"the",
"text",
"the",
"text",
"will",
"be",
"no",
"longer"... | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/PICTUtil.java#L106-L114 | train |
haraldk/TwelveMonkeys | imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/PICTUtil.java | PICTUtil.readPascalString | public static String readPascalString(final DataInput pStream) throws IOException {
// Get as many bytes as indicated by byte count
int length = pStream.readUnsignedByte();
byte[] bytes = new byte[length];
pStream.readFully(bytes, 0, length);
return new String(bytes, ENCODING);
} | java | public static String readPascalString(final DataInput pStream) throws IOException {
// Get as many bytes as indicated by byte count
int length = pStream.readUnsignedByte();
byte[] bytes = new byte[length];
pStream.readFully(bytes, 0, length);
return new String(bytes, ENCODING);
} | [
"public",
"static",
"String",
"readPascalString",
"(",
"final",
"DataInput",
"pStream",
")",
"throws",
"IOException",
"{",
"// Get as many bytes as indicated by byte count",
"int",
"length",
"=",
"pStream",
".",
"readUnsignedByte",
"(",
")",
";",
"byte",
"[",
"]",
"... | Reads a Pascal String from the given stream.
The input stream must be positioned at the length byte of the text,
which can thus be a maximum of 255 characters long.
@param pStream the input stream
@return the text read
@throws IOException if an I/O exception occurs during reading | [
"Reads",
"a",
"Pascal",
"String",
"from",
"the",
"given",
"stream",
".",
"The",
"input",
"stream",
"must",
"be",
"positioned",
"at",
"the",
"length",
"byte",
"of",
"the",
"text",
"which",
"can",
"thus",
"be",
"a",
"maximum",
"of",
"255",
"characters",
"l... | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-pict/src/main/java/com/twelvemonkeys/imageio/plugins/pict/PICTUtil.java#L126-L134 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/image/SourceRenderFilter.java | SourceRenderFilter.doFilterImpl | protected void doFilterImpl(ServletRequest pRequest, ServletResponse pResponse, FilterChain pChain) throws IOException, ServletException {
// TODO: Max size configuration, to avoid DOS attacks? OutOfMemory
// Size parameters
int width = ServletUtil.getIntParameter(pRequest, sizeWidthParam, -1);
int height = ServletUtil.getIntParameter(pRequest, sizeHeightParam, -1);
if (width > 0 || height > 0) {
pRequest.setAttribute(ImageServletResponse.ATTRIB_SIZE, new Dimension(width, height));
}
// Size uniform/percent
boolean uniform = ServletUtil.getBooleanParameter(pRequest, sizeUniformParam, true);
if (!uniform) {
pRequest.setAttribute(ImageServletResponse.ATTRIB_SIZE_UNIFORM, Boolean.FALSE);
}
boolean percent = ServletUtil.getBooleanParameter(pRequest, sizePercentParam, false);
if (percent) {
pRequest.setAttribute(ImageServletResponse.ATTRIB_SIZE_PERCENT, Boolean.TRUE);
}
// Area of interest parameters
int x = ServletUtil.getIntParameter(pRequest, regionLeftParam, -1); // Default is center
int y = ServletUtil.getIntParameter(pRequest, regionTopParam, -1); // Default is center
width = ServletUtil.getIntParameter(pRequest, regionWidthParam, -1);
height = ServletUtil.getIntParameter(pRequest, regionHeightParam, -1);
if (width > 0 || height > 0) {
pRequest.setAttribute(ImageServletResponse.ATTRIB_AOI, new Rectangle(x, y, width, height));
}
// AOI uniform/percent
uniform = ServletUtil.getBooleanParameter(pRequest, regionUniformParam, false);
if (uniform) {
pRequest.setAttribute(ImageServletResponse.ATTRIB_SIZE_UNIFORM, Boolean.TRUE);
}
percent = ServletUtil.getBooleanParameter(pRequest, regionPercentParam, false);
if (percent) {
pRequest.setAttribute(ImageServletResponse.ATTRIB_SIZE_PERCENT, Boolean.TRUE);
}
super.doFilterImpl(pRequest, pResponse, pChain);
} | java | protected void doFilterImpl(ServletRequest pRequest, ServletResponse pResponse, FilterChain pChain) throws IOException, ServletException {
// TODO: Max size configuration, to avoid DOS attacks? OutOfMemory
// Size parameters
int width = ServletUtil.getIntParameter(pRequest, sizeWidthParam, -1);
int height = ServletUtil.getIntParameter(pRequest, sizeHeightParam, -1);
if (width > 0 || height > 0) {
pRequest.setAttribute(ImageServletResponse.ATTRIB_SIZE, new Dimension(width, height));
}
// Size uniform/percent
boolean uniform = ServletUtil.getBooleanParameter(pRequest, sizeUniformParam, true);
if (!uniform) {
pRequest.setAttribute(ImageServletResponse.ATTRIB_SIZE_UNIFORM, Boolean.FALSE);
}
boolean percent = ServletUtil.getBooleanParameter(pRequest, sizePercentParam, false);
if (percent) {
pRequest.setAttribute(ImageServletResponse.ATTRIB_SIZE_PERCENT, Boolean.TRUE);
}
// Area of interest parameters
int x = ServletUtil.getIntParameter(pRequest, regionLeftParam, -1); // Default is center
int y = ServletUtil.getIntParameter(pRequest, regionTopParam, -1); // Default is center
width = ServletUtil.getIntParameter(pRequest, regionWidthParam, -1);
height = ServletUtil.getIntParameter(pRequest, regionHeightParam, -1);
if (width > 0 || height > 0) {
pRequest.setAttribute(ImageServletResponse.ATTRIB_AOI, new Rectangle(x, y, width, height));
}
// AOI uniform/percent
uniform = ServletUtil.getBooleanParameter(pRequest, regionUniformParam, false);
if (uniform) {
pRequest.setAttribute(ImageServletResponse.ATTRIB_SIZE_UNIFORM, Boolean.TRUE);
}
percent = ServletUtil.getBooleanParameter(pRequest, regionPercentParam, false);
if (percent) {
pRequest.setAttribute(ImageServletResponse.ATTRIB_SIZE_PERCENT, Boolean.TRUE);
}
super.doFilterImpl(pRequest, pResponse, pChain);
} | [
"protected",
"void",
"doFilterImpl",
"(",
"ServletRequest",
"pRequest",
",",
"ServletResponse",
"pResponse",
",",
"FilterChain",
"pChain",
")",
"throws",
"IOException",
",",
"ServletException",
"{",
"// TODO: Max size configuration, to avoid DOS attacks? OutOfMemory\r",
"// Siz... | Extracts request parameters, and sets the corresponding request
attributes if specified.
@param pRequest
@param pResponse
@param pChain
@throws IOException
@throws ServletException | [
"Extracts",
"request",
"parameters",
"and",
"sets",
"the",
"corresponding",
"request",
"attributes",
"if",
"specified",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/image/SourceRenderFilter.java#L130-L170 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java | HttpURLConnection.setTimeout | public void setTimeout(int pTimeout) {
if (pTimeout < 0) { // Must be positive
throw new IllegalArgumentException("Timeout must be positive.");
}
timeout = pTimeout;
if (socket != null) {
try {
socket.setSoTimeout(pTimeout);
}
catch (SocketException se) {
// Not much to do about that...
}
}
} | java | public void setTimeout(int pTimeout) {
if (pTimeout < 0) { // Must be positive
throw new IllegalArgumentException("Timeout must be positive.");
}
timeout = pTimeout;
if (socket != null) {
try {
socket.setSoTimeout(pTimeout);
}
catch (SocketException se) {
// Not much to do about that...
}
}
} | [
"public",
"void",
"setTimeout",
"(",
"int",
"pTimeout",
")",
"{",
"if",
"(",
"pTimeout",
"<",
"0",
")",
"{",
"// Must be positive",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Timeout must be positive.\"",
")",
";",
"}",
"timeout",
"=",
"pTimeout",
";",
... | Sets the read timeout for the undelying socket.
A timeout of zero is interpreted as an
infinite timeout.
@param pTimeout the maximum time the socket will block for read
operations, in milliseconds. | [
"Sets",
"the",
"read",
"timeout",
"for",
"the",
"undelying",
"socket",
".",
"A",
"timeout",
"of",
"zero",
"is",
"interpreted",
"as",
"an",
"infinite",
"timeout",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java#L280-L293 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java | HttpURLConnection.getInputStream | public synchronized InputStream getInputStream() throws IOException {
if (!connected) {
connect();
}
// Nothing to return
if (responseCode == HTTP_NOT_FOUND) {
throw new FileNotFoundException(url.toString());
}
int length;
if (inputStream == null) {
return null;
}
// "De-chunk" the output stream
else if ("chunked".equalsIgnoreCase(getHeaderField("Transfer-Encoding"))) {
if (!(inputStream instanceof ChunkedInputStream)) {
inputStream = new ChunkedInputStream(inputStream);
}
}
// Make sure we don't wait forever, if the content-length is known
else if ((length = getHeaderFieldInt("Content-Length", -1)) >= 0) {
if (!(inputStream instanceof FixedLengthInputStream)) {
inputStream = new FixedLengthInputStream(inputStream, length);
}
}
return inputStream;
} | java | public synchronized InputStream getInputStream() throws IOException {
if (!connected) {
connect();
}
// Nothing to return
if (responseCode == HTTP_NOT_FOUND) {
throw new FileNotFoundException(url.toString());
}
int length;
if (inputStream == null) {
return null;
}
// "De-chunk" the output stream
else if ("chunked".equalsIgnoreCase(getHeaderField("Transfer-Encoding"))) {
if (!(inputStream instanceof ChunkedInputStream)) {
inputStream = new ChunkedInputStream(inputStream);
}
}
// Make sure we don't wait forever, if the content-length is known
else if ((length = getHeaderFieldInt("Content-Length", -1)) >= 0) {
if (!(inputStream instanceof FixedLengthInputStream)) {
inputStream = new FixedLengthInputStream(inputStream, length);
}
}
return inputStream;
} | [
"public",
"synchronized",
"InputStream",
"getInputStream",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"connected",
")",
"{",
"connect",
"(",
")",
";",
"}",
"// Nothing to return",
"if",
"(",
"responseCode",
"==",
"HTTP_NOT_FOUND",
")",
"{",
"throw... | Returns an input stream that reads from this open connection.
@return an input stream that reads from this open connection.
@throws IOException if an I/O error occurs while
creating the input stream. | [
"Returns",
"an",
"input",
"stream",
"that",
"reads",
"from",
"this",
"open",
"connection",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java#L322-L351 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java | HttpURLConnection.connect | private void connect(final URL pURL, PasswordAuthentication pAuth, String pAuthType, int pRetries) throws IOException {
// Find correct port
final int port = (pURL.getPort() > 0)
? pURL.getPort()
: HTTP_DEFAULT_PORT;
// Create socket if we don't have one
if (socket == null) {
//socket = new Socket(pURL.getHost(), port); // Blocks...
socket = createSocket(pURL, port, connectTimeout);
socket.setSoTimeout(timeout);
}
// Get Socket output stream
OutputStream os = socket.getOutputStream();
// Connect using HTTP
writeRequestHeaders(os, pURL, method, requestProperties, usingProxy(), pAuth, pAuthType);
// Get response input stream
InputStream sis = socket.getInputStream();
BufferedInputStream is = new BufferedInputStream(sis);
// Detatch reponse headers from reponse input stream
InputStream header = detatchResponseHeader(is);
// Parse headers and set response code/message
responseHeaders = parseResponseHeader(header);
responseHeaderFields = parseHeaderFields(responseHeaders);
//System.err.println("Headers fields:");
//responseHeaderFields.list(System.err);
// Test HTTP response code, to see if further action is needed
switch (getResponseCode()) {
case HTTP_OK:
// 200 OK
inputStream = is;
errorStream = null;
break;
/*
case HTTP_PROXY_AUTH:
// 407 Proxy Authentication Required
*/
case HTTP_UNAUTHORIZED:
// 401 Unauthorized
// Set authorization and try again.. Slightly more compatible
responseCode = -1;
// IS THIS REDIRECTION??
//if (instanceFollowRedirects) { ???
String auth = getHeaderField(HEADER_WWW_AUTH);
// Missing WWW-Authenticate header for 401 response is an error
if (StringUtil.isEmpty(auth)) {
throw new ProtocolException("Missing \"" + HEADER_WWW_AUTH + "\" header for response: 401 " + responseMessage);
}
// Get real mehtod from WWW-Authenticate header
int SP = auth.indexOf(" ");
String method;
String realm = null;
if (SP >= 0) {
method = auth.substring(0, SP);
if (auth.length() >= SP + 7) {
realm = auth.substring(SP + 7); // " realm=".lenght() == 7
}
// else no realm
}
else {
// Default mehtod is Basic
method = SimpleAuthenticator.BASIC;
}
// Get PasswordAuthentication
PasswordAuthentication pa = Authenticator.requestPasswordAuthentication(NetUtil.createInetAddressFromURL(pURL), port,
pURL.getProtocol(), realm, method);
// Avoid infinite loop
if (pRetries++ <= 0) {
throw new ProtocolException("Server redirected too many times (" + maxRedirects + ") (Authentication required: " + auth + ")"); // This is what sun.net.www.protocol.http.HttpURLConnection does
}
else if (pa != null) {
connect(pURL, pa, method, pRetries);
}
break;
case HTTP_MOVED_PERM:
// 301 Moved Permanently
case HTTP_MOVED_TEMP:
// 302 Found
case HTTP_SEE_OTHER:
// 303 See Other
/*
case HTTP_USE_PROXY:
// 305 Use Proxy
// How do we handle this?
*/
case HTTP_REDIRECT:
// 307 Temporary Redirect
//System.err.println("Redirecting " + getResponseCode());
if (instanceFollowRedirects) {
// Redirect
responseCode = -1; // Because of the java.net.URLConnection
// getResponseCode implementation...
// ---
// I think redirects must be get?
//setRequestMethod("GET");
// ---
String location = getHeaderField("Location");
URL newLoc = new URL(pURL, location);
// Test if we can reuse the Socket
if (!(newLoc.getAuthority().equals(pURL.getAuthority()) && (newLoc.getPort() == pURL.getPort()))) {
socket.close(); // Close the socket, won't need it anymore
socket = null;
}
if (location != null) {
//System.err.println("Redirecting to " + location);
// Avoid infinite loop
if (--pRetries <= 0) {
throw new ProtocolException("Server redirected too many times (5)");
}
else {
connect(newLoc, pAuth, pAuthType, pRetries);
}
}
break;
}
// ...else, fall through default (if no Location: header)
default :
// Not 200 OK, or any of the redirect responses
// Probably an error...
errorStream = is;
inputStream = null;
}
// --- Need rethinking...
// No further questions, let the Socket wait forever (until the server
// closes the connection)
//socket.setSoTimeout(0);
// Probably not... The timeout should only kick if the read BLOCKS.
// Shutdown output, meaning any writes to the outputstream below will
// probably fail...
//socket.shutdownOutput();
// Not a good idea at all... POSTs need the outputstream to send the
// form-data.
// --- /Need rethinking.
outputStream = os;
} | java | private void connect(final URL pURL, PasswordAuthentication pAuth, String pAuthType, int pRetries) throws IOException {
// Find correct port
final int port = (pURL.getPort() > 0)
? pURL.getPort()
: HTTP_DEFAULT_PORT;
// Create socket if we don't have one
if (socket == null) {
//socket = new Socket(pURL.getHost(), port); // Blocks...
socket = createSocket(pURL, port, connectTimeout);
socket.setSoTimeout(timeout);
}
// Get Socket output stream
OutputStream os = socket.getOutputStream();
// Connect using HTTP
writeRequestHeaders(os, pURL, method, requestProperties, usingProxy(), pAuth, pAuthType);
// Get response input stream
InputStream sis = socket.getInputStream();
BufferedInputStream is = new BufferedInputStream(sis);
// Detatch reponse headers from reponse input stream
InputStream header = detatchResponseHeader(is);
// Parse headers and set response code/message
responseHeaders = parseResponseHeader(header);
responseHeaderFields = parseHeaderFields(responseHeaders);
//System.err.println("Headers fields:");
//responseHeaderFields.list(System.err);
// Test HTTP response code, to see if further action is needed
switch (getResponseCode()) {
case HTTP_OK:
// 200 OK
inputStream = is;
errorStream = null;
break;
/*
case HTTP_PROXY_AUTH:
// 407 Proxy Authentication Required
*/
case HTTP_UNAUTHORIZED:
// 401 Unauthorized
// Set authorization and try again.. Slightly more compatible
responseCode = -1;
// IS THIS REDIRECTION??
//if (instanceFollowRedirects) { ???
String auth = getHeaderField(HEADER_WWW_AUTH);
// Missing WWW-Authenticate header for 401 response is an error
if (StringUtil.isEmpty(auth)) {
throw new ProtocolException("Missing \"" + HEADER_WWW_AUTH + "\" header for response: 401 " + responseMessage);
}
// Get real mehtod from WWW-Authenticate header
int SP = auth.indexOf(" ");
String method;
String realm = null;
if (SP >= 0) {
method = auth.substring(0, SP);
if (auth.length() >= SP + 7) {
realm = auth.substring(SP + 7); // " realm=".lenght() == 7
}
// else no realm
}
else {
// Default mehtod is Basic
method = SimpleAuthenticator.BASIC;
}
// Get PasswordAuthentication
PasswordAuthentication pa = Authenticator.requestPasswordAuthentication(NetUtil.createInetAddressFromURL(pURL), port,
pURL.getProtocol(), realm, method);
// Avoid infinite loop
if (pRetries++ <= 0) {
throw new ProtocolException("Server redirected too many times (" + maxRedirects + ") (Authentication required: " + auth + ")"); // This is what sun.net.www.protocol.http.HttpURLConnection does
}
else if (pa != null) {
connect(pURL, pa, method, pRetries);
}
break;
case HTTP_MOVED_PERM:
// 301 Moved Permanently
case HTTP_MOVED_TEMP:
// 302 Found
case HTTP_SEE_OTHER:
// 303 See Other
/*
case HTTP_USE_PROXY:
// 305 Use Proxy
// How do we handle this?
*/
case HTTP_REDIRECT:
// 307 Temporary Redirect
//System.err.println("Redirecting " + getResponseCode());
if (instanceFollowRedirects) {
// Redirect
responseCode = -1; // Because of the java.net.URLConnection
// getResponseCode implementation...
// ---
// I think redirects must be get?
//setRequestMethod("GET");
// ---
String location = getHeaderField("Location");
URL newLoc = new URL(pURL, location);
// Test if we can reuse the Socket
if (!(newLoc.getAuthority().equals(pURL.getAuthority()) && (newLoc.getPort() == pURL.getPort()))) {
socket.close(); // Close the socket, won't need it anymore
socket = null;
}
if (location != null) {
//System.err.println("Redirecting to " + location);
// Avoid infinite loop
if (--pRetries <= 0) {
throw new ProtocolException("Server redirected too many times (5)");
}
else {
connect(newLoc, pAuth, pAuthType, pRetries);
}
}
break;
}
// ...else, fall through default (if no Location: header)
default :
// Not 200 OK, or any of the redirect responses
// Probably an error...
errorStream = is;
inputStream = null;
}
// --- Need rethinking...
// No further questions, let the Socket wait forever (until the server
// closes the connection)
//socket.setSoTimeout(0);
// Probably not... The timeout should only kick if the read BLOCKS.
// Shutdown output, meaning any writes to the outputstream below will
// probably fail...
//socket.shutdownOutput();
// Not a good idea at all... POSTs need the outputstream to send the
// form-data.
// --- /Need rethinking.
outputStream = os;
} | [
"private",
"void",
"connect",
"(",
"final",
"URL",
"pURL",
",",
"PasswordAuthentication",
"pAuth",
",",
"String",
"pAuthType",
",",
"int",
"pRetries",
")",
"throws",
"IOException",
"{",
"// Find correct port",
"final",
"int",
"port",
"=",
"(",
"pURL",
".",
"ge... | Internal connect method. | [
"Internal",
"connect",
"method",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java#L391-L543 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java | HttpURLConnection.createSocket | private Socket createSocket(final URL pURL, final int pPort, int pConnectTimeout) throws IOException {
Socket socket;
final Object current = this;
SocketConnector connector;
Thread t = new Thread(connector = new SocketConnector() {
private IOException mConnectException = null;
private Socket mLocalSocket = null;
public Socket getSocket() throws IOException {
if (mConnectException != null) {
throw mConnectException;
}
return mLocalSocket;
}
// Run method
public void run() {
try {
mLocalSocket = new Socket(pURL.getHost(), pPort); // Blocks...
}
catch (IOException ioe) {
// Store this exception for later
mConnectException = ioe;
}
// Signal that we are done
synchronized (current) {
current.notify();
}
}
});
t.start();
// Wait for connect
synchronized (this) {
try {
/// Only wait if thread is alive!
if (t.isAlive()) {
if (pConnectTimeout > 0) {
wait(pConnectTimeout);
}
else {
wait();
}
}
}
catch (InterruptedException ie) {
// Continue excecution on interrupt? Hmmm..
}
}
// Throw exception if the socket didn't connect fast enough
if ((socket = connector.getSocket()) == null) {
throw new ConnectException("Socket connect timed out!");
}
return socket;
} | java | private Socket createSocket(final URL pURL, final int pPort, int pConnectTimeout) throws IOException {
Socket socket;
final Object current = this;
SocketConnector connector;
Thread t = new Thread(connector = new SocketConnector() {
private IOException mConnectException = null;
private Socket mLocalSocket = null;
public Socket getSocket() throws IOException {
if (mConnectException != null) {
throw mConnectException;
}
return mLocalSocket;
}
// Run method
public void run() {
try {
mLocalSocket = new Socket(pURL.getHost(), pPort); // Blocks...
}
catch (IOException ioe) {
// Store this exception for later
mConnectException = ioe;
}
// Signal that we are done
synchronized (current) {
current.notify();
}
}
});
t.start();
// Wait for connect
synchronized (this) {
try {
/// Only wait if thread is alive!
if (t.isAlive()) {
if (pConnectTimeout > 0) {
wait(pConnectTimeout);
}
else {
wait();
}
}
}
catch (InterruptedException ie) {
// Continue excecution on interrupt? Hmmm..
}
}
// Throw exception if the socket didn't connect fast enough
if ((socket = connector.getSocket()) == null) {
throw new ConnectException("Socket connect timed out!");
}
return socket;
} | [
"private",
"Socket",
"createSocket",
"(",
"final",
"URL",
"pURL",
",",
"final",
"int",
"pPort",
",",
"int",
"pConnectTimeout",
")",
"throws",
"IOException",
"{",
"Socket",
"socket",
";",
"final",
"Object",
"current",
"=",
"this",
";",
"SocketConnector",
"conne... | Creates a socket to the given URL and port, with the given connect
timeout. If the socket waits more than the given timout to connect,
an ConnectException is thrown.
@param pURL the URL to connect to
@param pPort the port to connect to
@param pConnectTimeout the connect timeout
@return the created Socket.
@throws ConnectException if the connection is refused or otherwise
times out.
@throws UnknownHostException if the IP address of the host could not be
determined.
@throws IOException if an I/O error occurs when creating the socket.
@todo Move this code to a SocetImpl or similar?
@see Socket#Socket(String,int) | [
"Creates",
"a",
"socket",
"to",
"the",
"given",
"URL",
"and",
"port",
"with",
"the",
"given",
"connect",
"timeout",
".",
"If",
"the",
"socket",
"waits",
"more",
"than",
"the",
"given",
"timout",
"to",
"connect",
"an",
"ConnectException",
"is",
"thrown",
".... | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java#L573-L636 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java | HttpURLConnection.writeRequestHeaders | private static void writeRequestHeaders(OutputStream pOut, URL pURL, String pMethod, Properties pProps, boolean pUsingProxy,
PasswordAuthentication pAuth, String pAuthType) {
PrintWriter out = new PrintWriter(pOut, true); // autoFlush
if (!pUsingProxy) {
out.println(pMethod + " " + (!StringUtil.isEmpty(pURL.getPath())
? pURL.getPath()
: "/") + ((pURL.getQuery() != null)
? "?" + pURL.getQuery()
: "") + " HTTP/1.1"); // HTTP/1.1
// out.println("Connection: close"); // No persistent connections yet
/*
System.err.println(pMethod + " "
+ (!StringUtil.isEmpty(pURL.getPath()) ? pURL.getPath() : "/")
+ (pURL.getQuery() != null ? "?" + pURL.getQuery() : "")
+ " HTTP/1.1"); // HTTP/1.1
*/
// Authority (Host: HTTP/1.1 field, but seems to work for HTTP/1.0)
out.println("Host: " + pURL.getHost() + ((pURL.getPort() != -1)
? ":" + pURL.getPort()
: ""));
/*
System.err.println("Host: " + pURL.getHost()
+ (pURL.getPort() != -1 ? ":" + pURL.getPort() : ""));
*/
}
else {
////-- PROXY (absolute) VERSION
out.println(pMethod + " " + pURL.getProtocol() + "://" + pURL.getHost() + ((pURL.getPort() != -1)
? ":" + pURL.getPort()
: "") + pURL.getPath() + ((pURL.getQuery() != null)
? "?" + pURL.getQuery()
: "") + " HTTP/1.1");
}
// Check if we have authentication
if (pAuth != null) {
// If found, set Authorization header
byte[] userPass = (pAuth.getUserName() + ":" + new String(pAuth.getPassword())).getBytes();
// "Authorization" ":" credentials
out.println("Authorization: " + pAuthType + " " + BASE64.encode(userPass));
/*
System.err.println("Authorization: " + pAuthType + " "
+ BASE64.encode(userPass));
*/
}
// Iterate over properties
for (Map.Entry<Object, Object> property : pProps.entrySet()) {
out.println(property.getKey() + ": " + property.getValue());
//System.err.println(property.getKey() + ": " + property.getValue());
}
out.println(); // Empty line, marks end of request-header
} | java | private static void writeRequestHeaders(OutputStream pOut, URL pURL, String pMethod, Properties pProps, boolean pUsingProxy,
PasswordAuthentication pAuth, String pAuthType) {
PrintWriter out = new PrintWriter(pOut, true); // autoFlush
if (!pUsingProxy) {
out.println(pMethod + " " + (!StringUtil.isEmpty(pURL.getPath())
? pURL.getPath()
: "/") + ((pURL.getQuery() != null)
? "?" + pURL.getQuery()
: "") + " HTTP/1.1"); // HTTP/1.1
// out.println("Connection: close"); // No persistent connections yet
/*
System.err.println(pMethod + " "
+ (!StringUtil.isEmpty(pURL.getPath()) ? pURL.getPath() : "/")
+ (pURL.getQuery() != null ? "?" + pURL.getQuery() : "")
+ " HTTP/1.1"); // HTTP/1.1
*/
// Authority (Host: HTTP/1.1 field, but seems to work for HTTP/1.0)
out.println("Host: " + pURL.getHost() + ((pURL.getPort() != -1)
? ":" + pURL.getPort()
: ""));
/*
System.err.println("Host: " + pURL.getHost()
+ (pURL.getPort() != -1 ? ":" + pURL.getPort() : ""));
*/
}
else {
////-- PROXY (absolute) VERSION
out.println(pMethod + " " + pURL.getProtocol() + "://" + pURL.getHost() + ((pURL.getPort() != -1)
? ":" + pURL.getPort()
: "") + pURL.getPath() + ((pURL.getQuery() != null)
? "?" + pURL.getQuery()
: "") + " HTTP/1.1");
}
// Check if we have authentication
if (pAuth != null) {
// If found, set Authorization header
byte[] userPass = (pAuth.getUserName() + ":" + new String(pAuth.getPassword())).getBytes();
// "Authorization" ":" credentials
out.println("Authorization: " + pAuthType + " " + BASE64.encode(userPass));
/*
System.err.println("Authorization: " + pAuthType + " "
+ BASE64.encode(userPass));
*/
}
// Iterate over properties
for (Map.Entry<Object, Object> property : pProps.entrySet()) {
out.println(property.getKey() + ": " + property.getValue());
//System.err.println(property.getKey() + ": " + property.getValue());
}
out.println(); // Empty line, marks end of request-header
} | [
"private",
"static",
"void",
"writeRequestHeaders",
"(",
"OutputStream",
"pOut",
",",
"URL",
"pURL",
",",
"String",
"pMethod",
",",
"Properties",
"pProps",
",",
"boolean",
"pUsingProxy",
",",
"PasswordAuthentication",
"pAuth",
",",
"String",
"pAuthType",
")",
"{",... | Writes the HTTP request headers, for HTTP GET method.
@see <A href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">RFC 2616</A> | [
"Writes",
"the",
"HTTP",
"request",
"headers",
"for",
"HTTP",
"GET",
"method",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java#L681-L744 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java | HttpURLConnection.findEndOfHeader | private static int findEndOfHeader(byte[] pBytes, int pEnd) {
byte[] header = HTTP_HEADER_END.getBytes();
// Normal condition, check all bytes
for (int i = 0; i < pEnd - 4; i++) { // Need 4 bytes to match
if ((pBytes[i] == header[0]) && (pBytes[i + 1] == header[1]) && (pBytes[i + 2] == header[2]) && (pBytes[i + 3] == header[3])) {
//System.err.println("FOUND END OF HEADER!");
return i + 4;
}
}
// Check last 3 bytes, to check if we have a partial match
if ((pEnd - 1 >= 0) && (pBytes[pEnd - 1] == header[0])) {
//System.err.println("FOUND LAST BYTE");
return -2; // LAST BYTE
}
else if ((pEnd - 2 >= 0) && (pBytes[pEnd - 2] == header[0]) && (pBytes[pEnd - 1] == header[1])) {
//System.err.println("FOUND LAST TWO BYTES");
return -3; // LAST TWO BYTES
}
else if ((pEnd - 3 >= 0) && (pBytes[pEnd - 3] == header[0]) && (pBytes[pEnd - 2] == header[1]) && (pBytes[pEnd - 1] == header[2])) {
//System.err.println("FOUND LAST THREE BYTES");
return -4; // LAST THREE BYTES
}
return -1; // NO BYTES MATCH
} | java | private static int findEndOfHeader(byte[] pBytes, int pEnd) {
byte[] header = HTTP_HEADER_END.getBytes();
// Normal condition, check all bytes
for (int i = 0; i < pEnd - 4; i++) { // Need 4 bytes to match
if ((pBytes[i] == header[0]) && (pBytes[i + 1] == header[1]) && (pBytes[i + 2] == header[2]) && (pBytes[i + 3] == header[3])) {
//System.err.println("FOUND END OF HEADER!");
return i + 4;
}
}
// Check last 3 bytes, to check if we have a partial match
if ((pEnd - 1 >= 0) && (pBytes[pEnd - 1] == header[0])) {
//System.err.println("FOUND LAST BYTE");
return -2; // LAST BYTE
}
else if ((pEnd - 2 >= 0) && (pBytes[pEnd - 2] == header[0]) && (pBytes[pEnd - 1] == header[1])) {
//System.err.println("FOUND LAST TWO BYTES");
return -3; // LAST TWO BYTES
}
else if ((pEnd - 3 >= 0) && (pBytes[pEnd - 3] == header[0]) && (pBytes[pEnd - 2] == header[1]) && (pBytes[pEnd - 1] == header[2])) {
//System.err.println("FOUND LAST THREE BYTES");
return -4; // LAST THREE BYTES
}
return -1; // NO BYTES MATCH
} | [
"private",
"static",
"int",
"findEndOfHeader",
"(",
"byte",
"[",
"]",
"pBytes",
",",
"int",
"pEnd",
")",
"{",
"byte",
"[",
"]",
"header",
"=",
"HTTP_HEADER_END",
".",
"getBytes",
"(",
")",
";",
"// Normal condition, check all bytes",
"for",
"(",
"int",
"i",
... | Finds the end of the HTTP response header in an array of bytes.
@todo This one's a little dirty... | [
"Finds",
"the",
"end",
"of",
"the",
"HTTP",
"response",
"header",
"in",
"an",
"array",
"of",
"bytes",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java#L751-L780 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java | HttpURLConnection.detatchResponseHeader | private static InputStream detatchResponseHeader(BufferedInputStream pIS) throws IOException {
// Store header in byte array
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
pIS.mark(BUF_SIZE);
byte[] buffer = new byte[BUF_SIZE];
int length;
int headerEnd;
// Read from iput, store in bytes
while ((length = pIS.read(buffer)) != -1) {
// End of header?
headerEnd = findEndOfHeader(buffer, length);
if (headerEnd >= 0) {
// Write rest
bytes.write(buffer, 0, headerEnd);
// Go back to last mark
pIS.reset();
// Position stream to right after header, and exit loop
pIS.skip(headerEnd);
break;
}
else if (headerEnd < -1) {
// Write partial (except matching header bytes)
bytes.write(buffer, 0, length - 4);
// Go back to last mark
pIS.reset();
// Position stream to right before potential header end
pIS.skip(length - 4);
}
else {
// Write all
bytes.write(buffer, 0, length);
}
// Can't read more than BUF_SIZE ahead anyway
pIS.mark(BUF_SIZE);
}
return new ByteArrayInputStream(bytes.toByteArray());
} | java | private static InputStream detatchResponseHeader(BufferedInputStream pIS) throws IOException {
// Store header in byte array
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
pIS.mark(BUF_SIZE);
byte[] buffer = new byte[BUF_SIZE];
int length;
int headerEnd;
// Read from iput, store in bytes
while ((length = pIS.read(buffer)) != -1) {
// End of header?
headerEnd = findEndOfHeader(buffer, length);
if (headerEnd >= 0) {
// Write rest
bytes.write(buffer, 0, headerEnd);
// Go back to last mark
pIS.reset();
// Position stream to right after header, and exit loop
pIS.skip(headerEnd);
break;
}
else if (headerEnd < -1) {
// Write partial (except matching header bytes)
bytes.write(buffer, 0, length - 4);
// Go back to last mark
pIS.reset();
// Position stream to right before potential header end
pIS.skip(length - 4);
}
else {
// Write all
bytes.write(buffer, 0, length);
}
// Can't read more than BUF_SIZE ahead anyway
pIS.mark(BUF_SIZE);
}
return new ByteArrayInputStream(bytes.toByteArray());
} | [
"private",
"static",
"InputStream",
"detatchResponseHeader",
"(",
"BufferedInputStream",
"pIS",
")",
"throws",
"IOException",
"{",
"// Store header in byte array",
"ByteArrayOutputStream",
"bytes",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"pIS",
".",
"mark",
... | Reads the header part of the response, and copies it to a different
InputStream. | [
"Reads",
"the",
"header",
"part",
"of",
"the",
"response",
"and",
"copies",
"it",
"to",
"a",
"different",
"InputStream",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java#L786-L833 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java | HttpURLConnection.parseHeaderFields | private static Properties parseHeaderFields(String[] pHeaders) {
Properties headers = new Properties();
// Get header information
int split;
String field;
String value;
for (String header : pHeaders) {
//System.err.println(pHeaders[i]);
if ((split = header.indexOf(":")) > 0) {
// Read & parse..?
field = header.substring(0, split);
value = header.substring(split + 1);
//System.err.println(field + ": " + value.trim());
headers.setProperty(StringUtil.toLowerCase(field), value.trim());
}
}
return headers;
} | java | private static Properties parseHeaderFields(String[] pHeaders) {
Properties headers = new Properties();
// Get header information
int split;
String field;
String value;
for (String header : pHeaders) {
//System.err.println(pHeaders[i]);
if ((split = header.indexOf(":")) > 0) {
// Read & parse..?
field = header.substring(0, split);
value = header.substring(split + 1);
//System.err.println(field + ": " + value.trim());
headers.setProperty(StringUtil.toLowerCase(field), value.trim());
}
}
return headers;
} | [
"private",
"static",
"Properties",
"parseHeaderFields",
"(",
"String",
"[",
"]",
"pHeaders",
")",
"{",
"Properties",
"headers",
"=",
"new",
"Properties",
"(",
")",
";",
"// Get header information",
"int",
"split",
";",
"String",
"field",
";",
"String",
"value",
... | Pareses the response header fields. | [
"Pareses",
"the",
"response",
"header",
"fields",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java#L838-L859 | train |
haraldk/TwelveMonkeys | sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java | HttpURLConnection.parseResponseHeader | private static String[] parseResponseHeader(InputStream pIS) throws IOException {
List<String> headers = new ArrayList<String>();
// Wrap Stream in Reader
BufferedReader in = new BufferedReader(new InputStreamReader(pIS));
// Get response status
String header;
while ((header = in.readLine()) != null) {
//System.err.println(header);
headers.add(header);
}
return headers.toArray(new String[headers.size()]);
} | java | private static String[] parseResponseHeader(InputStream pIS) throws IOException {
List<String> headers = new ArrayList<String>();
// Wrap Stream in Reader
BufferedReader in = new BufferedReader(new InputStreamReader(pIS));
// Get response status
String header;
while ((header = in.readLine()) != null) {
//System.err.println(header);
headers.add(header);
}
return headers.toArray(new String[headers.size()]);
} | [
"private",
"static",
"String",
"[",
"]",
"parseResponseHeader",
"(",
"InputStream",
"pIS",
")",
"throws",
"IOException",
"{",
"List",
"<",
"String",
">",
"headers",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"// Wrap Stream in Reader",
"Buffer... | Parses the response headers. | [
"Parses",
"the",
"response",
"headers",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/net/HttpURLConnection.java#L864-L878 | train |
haraldk/TwelveMonkeys | common/common-image/src/main/java/com/twelvemonkeys/image/GrayFilter.java | GrayFilter.filterRGB | public int filterRGB(int pX, int pY, int pARGB) {
// Get color components
int r = pARGB >> 16 & 0xFF;
int g = pARGB >> 8 & 0xFF;
int b = pARGB & 0xFF;
// ITU standard: Gray scale=(222*Red+707*Green+71*Blue)/1000
int gray = (222 * r + 707 * g + 71 * b) / 1000;
//int gray = (int) ((float) (r + g + b) / 3.0f);
if (range != 1.0f) {
// Apply range
gray = low + (int) (gray * range);
}
// Return ARGB pixel
return (pARGB & 0xFF000000) | (gray << 16) | (gray << 8) | gray;
} | java | public int filterRGB(int pX, int pY, int pARGB) {
// Get color components
int r = pARGB >> 16 & 0xFF;
int g = pARGB >> 8 & 0xFF;
int b = pARGB & 0xFF;
// ITU standard: Gray scale=(222*Red+707*Green+71*Blue)/1000
int gray = (222 * r + 707 * g + 71 * b) / 1000;
//int gray = (int) ((float) (r + g + b) / 3.0f);
if (range != 1.0f) {
// Apply range
gray = low + (int) (gray * range);
}
// Return ARGB pixel
return (pARGB & 0xFF000000) | (gray << 16) | (gray << 8) | gray;
} | [
"public",
"int",
"filterRGB",
"(",
"int",
"pX",
",",
"int",
"pY",
",",
"int",
"pARGB",
")",
"{",
"// Get color components\r",
"int",
"r",
"=",
"pARGB",
">>",
"16",
"&",
"0xFF",
";",
"int",
"g",
"=",
"pARGB",
">>",
"8",
"&",
"0xFF",
";",
"int",
"b",... | Filters one pixel using ITU color-conversion.
@param pX x
@param pY y
@param pARGB pixel value in default color space
@return the filtered pixel value in the default color space | [
"Filters",
"one",
"pixel",
"using",
"ITU",
"color",
"-",
"conversion",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-image/src/main/java/com/twelvemonkeys/image/GrayFilter.java#L112-L130 | train |
haraldk/TwelveMonkeys | imageio/imageio-bmp/src/main/java/com/twelvemonkeys/imageio/plugins/bmp/AbstractRLEDecoder.java | AbstractRLEDecoder.decode | public final int decode(final InputStream stream, final ByteBuffer buffer) throws IOException {
// TODO: Allow decoding < row.length at a time and get rid of this assertion...
if (buffer.capacity() < row.length) {
throw new AssertionError("This decoder needs a buffer.capacity() of at least one row");
}
while (buffer.remaining() >= row.length && srcY >= 0) {
// NOTE: Decode only full rows, don't decode if y delta
if (dstX == 0 && srcY == dstY) {
decodeRow(stream);
}
int length = Math.min(row.length - (dstX * bitsPerSample) / 8, buffer.remaining());
buffer.put(row, 0, length);
dstX += (length * 8) / bitsPerSample;
if (dstX == (row.length * 8) / bitsPerSample) {
dstX = 0;
dstY++;
// NOTE: If src Y is > dst Y, we have a delta, and have to fill the
// gap with zero-bytes
if (srcX > dstX) {
Arrays.fill(row, 0, (srcX * bitsPerSample) / 8, (byte) 0);
}
if (srcY > dstY) {
Arrays.fill(row, (byte) 0);
}
}
}
return buffer.position();
} | java | public final int decode(final InputStream stream, final ByteBuffer buffer) throws IOException {
// TODO: Allow decoding < row.length at a time and get rid of this assertion...
if (buffer.capacity() < row.length) {
throw new AssertionError("This decoder needs a buffer.capacity() of at least one row");
}
while (buffer.remaining() >= row.length && srcY >= 0) {
// NOTE: Decode only full rows, don't decode if y delta
if (dstX == 0 && srcY == dstY) {
decodeRow(stream);
}
int length = Math.min(row.length - (dstX * bitsPerSample) / 8, buffer.remaining());
buffer.put(row, 0, length);
dstX += (length * 8) / bitsPerSample;
if (dstX == (row.length * 8) / bitsPerSample) {
dstX = 0;
dstY++;
// NOTE: If src Y is > dst Y, we have a delta, and have to fill the
// gap with zero-bytes
if (srcX > dstX) {
Arrays.fill(row, 0, (srcX * bitsPerSample) / 8, (byte) 0);
}
if (srcY > dstY) {
Arrays.fill(row, (byte) 0);
}
}
}
return buffer.position();
} | [
"public",
"final",
"int",
"decode",
"(",
"final",
"InputStream",
"stream",
",",
"final",
"ByteBuffer",
"buffer",
")",
"throws",
"IOException",
"{",
"// TODO: Allow decoding < row.length at a time and get rid of this assertion...",
"if",
"(",
"buffer",
".",
"capacity",
"("... | Decodes as much data as possible, from the stream into the buffer.
@param stream the input stream containing RLE data
@param buffer the buffer to decode the data to
@return the number of bytes decoded from the stream, to the buffer
@throws IOException if an I/O related exception occurs while reading | [
"Decodes",
"as",
"much",
"data",
"as",
"possible",
"from",
"the",
"stream",
"into",
"the",
"buffer",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/imageio/imageio-bmp/src/main/java/com/twelvemonkeys/imageio/plugins/bmp/AbstractRLEDecoder.java#L93-L125 | train |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/fileupload/FileUploadFilter.java | FileUploadFilter.init | public void init() throws ServletException {
// Get the name of the upload directory.
String uploadDirParam = getInitParameter("uploadDir");
if (!StringUtil.isEmpty(uploadDirParam)) {
try {
URL uploadDirURL = getServletContext().getResource(uploadDirParam);
uploadDir = FileUtil.toFile(uploadDirURL);
}
catch (MalformedURLException e) {
throw new ServletException(e.getMessage(), e);
}
}
if (uploadDir == null) {
uploadDir = ServletUtil.getTempDir(getServletContext());
}
} | java | public void init() throws ServletException {
// Get the name of the upload directory.
String uploadDirParam = getInitParameter("uploadDir");
if (!StringUtil.isEmpty(uploadDirParam)) {
try {
URL uploadDirURL = getServletContext().getResource(uploadDirParam);
uploadDir = FileUtil.toFile(uploadDirURL);
}
catch (MalformedURLException e) {
throw new ServletException(e.getMessage(), e);
}
}
if (uploadDir == null) {
uploadDir = ServletUtil.getTempDir(getServletContext());
}
} | [
"public",
"void",
"init",
"(",
")",
"throws",
"ServletException",
"{",
"// Get the name of the upload directory.\r",
"String",
"uploadDirParam",
"=",
"getInitParameter",
"(",
"\"uploadDir\"",
")",
";",
"if",
"(",
"!",
"StringUtil",
".",
"isEmpty",
"(",
"uploadDirParam... | This method is called by the server before the filter goes into service,
and here it determines the file upload directory.
@throws ServletException | [
"This",
"method",
"is",
"called",
"by",
"the",
"server",
"before",
"the",
"filter",
"goes",
"into",
"service",
"and",
"here",
"it",
"determines",
"the",
"file",
"upload",
"directory",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/fileupload/FileUploadFilter.java#L68-L85 | train |
haraldk/TwelveMonkeys | common/common-io/src/main/java/com/twelvemonkeys/io/FileUtil.java | FileUtil.copyDir | private static boolean copyDir(File pFrom, File pTo, boolean pOverWrite) throws IOException {
if (pTo.exists() && !pTo.isDirectory()) {
throw new IOException("A directory may only be copied to another directory, not to a file");
}
pTo.mkdirs(); // mkdir?
boolean allOkay = true;
File[] files = pFrom.listFiles();
for (File file : files) {
if (!copy(file, new File(pTo, file.getName()), pOverWrite)) {
allOkay = false;
}
}
return allOkay;
} | java | private static boolean copyDir(File pFrom, File pTo, boolean pOverWrite) throws IOException {
if (pTo.exists() && !pTo.isDirectory()) {
throw new IOException("A directory may only be copied to another directory, not to a file");
}
pTo.mkdirs(); // mkdir?
boolean allOkay = true;
File[] files = pFrom.listFiles();
for (File file : files) {
if (!copy(file, new File(pTo, file.getName()), pOverWrite)) {
allOkay = false;
}
}
return allOkay;
} | [
"private",
"static",
"boolean",
"copyDir",
"(",
"File",
"pFrom",
",",
"File",
"pTo",
",",
"boolean",
"pOverWrite",
")",
"throws",
"IOException",
"{",
"if",
"(",
"pTo",
".",
"exists",
"(",
")",
"&&",
"!",
"pTo",
".",
"isDirectory",
"(",
")",
")",
"{",
... | Copies a directory recursively. If the destination folder does not exist,
it is created
@param pFrom the source directory
@param pTo the destination directory
@param pOverWrite {@code true} if we should allow overwrting existing files
@return {@code true} if all files were copied sucessfully
@throws IOException if {@code pTo} exists, and it not a directory,
or if copying of any of the files in the folder fails | [
"Copies",
"a",
"directory",
"recursively",
".",
"If",
"the",
"destination",
"folder",
"does",
"not",
"exist",
"it",
"is",
"created"
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-io/src/main/java/com/twelvemonkeys/io/FileUtil.java#L282-L296 | train |
haraldk/TwelveMonkeys | common/common-io/src/main/java/com/twelvemonkeys/io/FileUtil.java | FileUtil.copy | public static boolean copy(InputStream pFrom, OutputStream pTo) throws IOException {
Validate.notNull(pFrom, "from");
Validate.notNull(pTo, "to");
// TODO: Consider using file channels for faster copy where possible
// Use buffer size two times byte array, to avoid i/o bottleneck
// TODO: Consider letting the client decide as this is sometimes not a good thing!
InputStream in = new BufferedInputStream(pFrom, BUF_SIZE * 2);
OutputStream out = new BufferedOutputStream(pTo, BUF_SIZE * 2);
byte[] buffer = new byte[BUF_SIZE];
int count;
while ((count = in.read(buffer)) != -1) {
out.write(buffer, 0, count);
}
// Flush out stream, to write any remaining buffered data
out.flush();
return true; // If we got here, everything is probably okay.. ;-)
} | java | public static boolean copy(InputStream pFrom, OutputStream pTo) throws IOException {
Validate.notNull(pFrom, "from");
Validate.notNull(pTo, "to");
// TODO: Consider using file channels for faster copy where possible
// Use buffer size two times byte array, to avoid i/o bottleneck
// TODO: Consider letting the client decide as this is sometimes not a good thing!
InputStream in = new BufferedInputStream(pFrom, BUF_SIZE * 2);
OutputStream out = new BufferedOutputStream(pTo, BUF_SIZE * 2);
byte[] buffer = new byte[BUF_SIZE];
int count;
while ((count = in.read(buffer)) != -1) {
out.write(buffer, 0, count);
}
// Flush out stream, to write any remaining buffered data
out.flush();
return true; // If we got here, everything is probably okay.. ;-)
} | [
"public",
"static",
"boolean",
"copy",
"(",
"InputStream",
"pFrom",
",",
"OutputStream",
"pTo",
")",
"throws",
"IOException",
"{",
"Validate",
".",
"notNull",
"(",
"pFrom",
",",
"\"from\"",
")",
";",
"Validate",
".",
"notNull",
"(",
"pTo",
",",
"\"to\"",
"... | Copies all data from one stream to another.
The data is copied from the fromStream to the toStream using buffered
streams for efficiency.
@param pFrom The input srteam to copy from
@param pTo The output stream to copy to
@return true. Otherwise, an
IOException is thrown, and the method does not return a value.
@throws IOException if an i/o error occurs during copy
@throws IllegalArgumentException if either {@code pFrom} or {@code pTo} is
{@code null} | [
"Copies",
"all",
"data",
"from",
"one",
"stream",
"to",
"another",
".",
"The",
"data",
"is",
"copied",
"from",
"the",
"fromStream",
"to",
"the",
"toStream",
"using",
"buffered",
"streams",
"for",
"efficiency",
"."
] | 7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-io/src/main/java/com/twelvemonkeys/io/FileUtil.java#L311-L333 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.