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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/outputs/GoogleCloudStorageFileOutput.java | GoogleCloudStorageFileOutput.finish | @Override
public GoogleCloudStorageFileSet finish(Collection<? extends OutputWriter<ByteBuffer>> writers) {
List<String> out = Lists.newArrayList();
for (OutputWriter<ByteBuffer> w : writers) {
GoogleCloudStorageFileOutputWriter writer = (GoogleCloudStorageFileOutputWriter) w;
out.add(writer.getFile().getObjectName());
}
return new GoogleCloudStorageFileSet(bucket, out);
} | java | @Override
public GoogleCloudStorageFileSet finish(Collection<? extends OutputWriter<ByteBuffer>> writers) {
List<String> out = Lists.newArrayList();
for (OutputWriter<ByteBuffer> w : writers) {
GoogleCloudStorageFileOutputWriter writer = (GoogleCloudStorageFileOutputWriter) w;
out.add(writer.getFile().getObjectName());
}
return new GoogleCloudStorageFileSet(bucket, out);
} | [
"@",
"Override",
"public",
"GoogleCloudStorageFileSet",
"finish",
"(",
"Collection",
"<",
"?",
"extends",
"OutputWriter",
"<",
"ByteBuffer",
">",
">",
"writers",
")",
"{",
"List",
"<",
"String",
">",
"out",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
... | Returns a list of GcsFilename that has one element for each reduce shard. | [
"Returns",
"a",
"list",
"of",
"GcsFilename",
"that",
"has",
"one",
"element",
"for",
"each",
"reduce",
"shard",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/outputs/GoogleCloudStorageFileOutput.java#L74-L82 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/outputs/SliceSegmentingOutputWriter.java | SliceSegmentingOutputWriter.beginSlice | @Override
public void beginSlice() throws IOException {
writer = createWriter(sliceCount++);
writer.setContext(getContext());
writer.beginShard();
writer.beginSlice();
} | java | @Override
public void beginSlice() throws IOException {
writer = createWriter(sliceCount++);
writer.setContext(getContext());
writer.beginShard();
writer.beginSlice();
} | [
"@",
"Override",
"public",
"void",
"beginSlice",
"(",
")",
"throws",
"IOException",
"{",
"writer",
"=",
"createWriter",
"(",
"sliceCount",
"++",
")",
";",
"writer",
".",
"setContext",
"(",
"getContext",
"(",
")",
")",
";",
"writer",
".",
"beginShard",
"(",... | Creates a new writer. | [
"Creates",
"a",
"new",
"writer",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/outputs/SliceSegmentingOutputWriter.java#L30-L36 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/MapOnlyMapper.java | MapOnlyMapper.forMapper | public static <I, Void, V> MapOnlyMapper<I, V> forMapper(Mapper<I, Void, V> mapper) {
return new MapperAdapter<>(mapper);
} | java | public static <I, Void, V> MapOnlyMapper<I, V> forMapper(Mapper<I, Void, V> mapper) {
return new MapperAdapter<>(mapper);
} | [
"public",
"static",
"<",
"I",
",",
"Void",
",",
"V",
">",
"MapOnlyMapper",
"<",
"I",
",",
"V",
">",
"forMapper",
"(",
"Mapper",
"<",
"I",
",",
"Void",
",",
"V",
">",
"mapper",
")",
"{",
"return",
"new",
"MapperAdapter",
"<>",
"(",
"mapper",
")",
... | Returns a MapOnlyMapper for a given Mapper passing only the values to the output. | [
"Returns",
"a",
"MapOnlyMapper",
"for",
"a",
"given",
"Mapper",
"passing",
"only",
"the",
"values",
"to",
"the",
"output",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/MapOnlyMapper.java#L22-L24 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/shardedjob/ShardedJobRunner.java | ShardedJobRunner.handleLockHeld | private void handleLockHeld(String taskId, ShardedJobStateImpl<T> jobState,
IncrementalTaskState<T> taskState) {
long currentTime = System.currentTimeMillis();
int sliceTimeoutMillis = jobState.getSettings().getSliceTimeoutMillis();
long lockExpiration = taskState.getLockInfo().lockedSince() + sliceTimeoutMillis;
boolean wasRequestCompleted = wasRequestCompleted(taskState.getLockInfo().getRequestId());
if (lockExpiration > currentTime && !wasRequestCompleted) {
// if lock was not expired AND not abandon reschedule in 1 minute.
long eta = Math.min(lockExpiration, currentTime + 60_000);
scheduleWorkerTask(null, jobState.getSettings(), taskState, eta);
log.info("Lock for " + taskId + " is being held. Will retry after " + (eta - currentTime));
} else {
ShardRetryState<T> retryState;
if (wasRequestCompleted) {
retryState = handleSliceFailure(jobState, taskState, new RuntimeException(
"Resuming after abandon lock for " + taskId + " on slice: "
+ taskState.getSequenceNumber()), true);
} else {
retryState = handleShardFailure(jobState, taskState, new RuntimeException(
"Lock for " + taskId + " expired on slice: " + taskState.getSequenceNumber()));
}
updateTask(jobState, taskState, retryState, false);
}
} | java | private void handleLockHeld(String taskId, ShardedJobStateImpl<T> jobState,
IncrementalTaskState<T> taskState) {
long currentTime = System.currentTimeMillis();
int sliceTimeoutMillis = jobState.getSettings().getSliceTimeoutMillis();
long lockExpiration = taskState.getLockInfo().lockedSince() + sliceTimeoutMillis;
boolean wasRequestCompleted = wasRequestCompleted(taskState.getLockInfo().getRequestId());
if (lockExpiration > currentTime && !wasRequestCompleted) {
// if lock was not expired AND not abandon reschedule in 1 minute.
long eta = Math.min(lockExpiration, currentTime + 60_000);
scheduleWorkerTask(null, jobState.getSettings(), taskState, eta);
log.info("Lock for " + taskId + " is being held. Will retry after " + (eta - currentTime));
} else {
ShardRetryState<T> retryState;
if (wasRequestCompleted) {
retryState = handleSliceFailure(jobState, taskState, new RuntimeException(
"Resuming after abandon lock for " + taskId + " on slice: "
+ taskState.getSequenceNumber()), true);
} else {
retryState = handleShardFailure(jobState, taskState, new RuntimeException(
"Lock for " + taskId + " expired on slice: " + taskState.getSequenceNumber()));
}
updateTask(jobState, taskState, retryState, false);
}
} | [
"private",
"void",
"handleLockHeld",
"(",
"String",
"taskId",
",",
"ShardedJobStateImpl",
"<",
"T",
">",
"jobState",
",",
"IncrementalTaskState",
"<",
"T",
">",
"taskState",
")",
"{",
"long",
"currentTime",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";... | Handle a locked slice case. | [
"Handle",
"a",
"locked",
"slice",
"case",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/shardedjob/ShardedJobRunner.java#L301-L325 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/BigQueryMarshallerByType.java | BigQueryMarshallerByType.toBytes | @Override
public ByteBuffer toBytes(T object) {
if (!type.equals(object.getClass())) {
throw new RuntimeException(
"The type of the object does not match the parameter type of this marshaller. ");
}
Map<String, Object> jsonObject = dataMarshaller.mapFieldNameToValue(object);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
objectMapper.writeValue(out, jsonObject);
out.write(NEWLINE_CHARACTER.getBytes());
} catch (IOException e) {
throw new RuntimeException("Error in serializing to bigquery json " + jsonObject, e);
}
return ByteBuffer.wrap(out.toByteArray());
} | java | @Override
public ByteBuffer toBytes(T object) {
if (!type.equals(object.getClass())) {
throw new RuntimeException(
"The type of the object does not match the parameter type of this marshaller. ");
}
Map<String, Object> jsonObject = dataMarshaller.mapFieldNameToValue(object);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
objectMapper.writeValue(out, jsonObject);
out.write(NEWLINE_CHARACTER.getBytes());
} catch (IOException e) {
throw new RuntimeException("Error in serializing to bigquery json " + jsonObject, e);
}
return ByteBuffer.wrap(out.toByteArray());
} | [
"@",
"Override",
"public",
"ByteBuffer",
"toBytes",
"(",
"T",
"object",
")",
"{",
"if",
"(",
"!",
"type",
".",
"equals",
"(",
"object",
".",
"getClass",
"(",
")",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"The type of the object does not matc... | Validates that the type of the object to serialize is the same as the type for which schema was
generated. The type should match exactly as interface and abstract classes are not supported. | [
"Validates",
"that",
"the",
"type",
"of",
"the",
"object",
"to",
"serialize",
"is",
"the",
"same",
"as",
"the",
"type",
"for",
"which",
"schema",
"was",
"generated",
".",
"The",
"type",
"should",
"match",
"exactly",
"as",
"interface",
"and",
"abstract",
"c... | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/BigQueryMarshallerByType.java#L55-L70 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/handlers/StatusHandler.java | StatusHandler.handleCommand | static void handleCommand(
String command, HttpServletRequest request, HttpServletResponse response) {
response.setContentType("application/json");
boolean isPost = "POST".equals(request.getMethod());
JSONObject retValue = null;
try {
if (command.equals(LIST_JOBS_PATH) && !isPost) {
retValue = handleListJobs(request);
} else if (command.equals(CLEANUP_JOB_PATH) && isPost) {
retValue = handleCleanupJob(request.getParameter("mapreduce_id"));
} else if (command.equals(ABORT_JOB_PATH) && isPost) {
retValue = handleAbortJob(request.getParameter("mapreduce_id"));
} else if (command.equals(GET_JOB_DETAIL_PATH) && !isPost) {
retValue = handleGetJobDetail(request.getParameter("mapreduce_id"));
}
} catch (Exception t) {
log.log(Level.SEVERE, "Got exception while running command", t);
try {
retValue = new JSONObject();
retValue.put("error_class", t.getClass().getName());
retValue.put("error_message",
"Full stack trace is available in the server logs. Message: "
+ t.getMessage());
} catch (JSONException e) {
throw new RuntimeException("Couldn't create error JSON object", e);
}
}
try {
if (retValue == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else {
retValue.write(response.getWriter());
response.getWriter().flush();
}
} catch (JSONException | IOException e) {
throw new RuntimeException("Couldn't write command response", e);
}
} | java | static void handleCommand(
String command, HttpServletRequest request, HttpServletResponse response) {
response.setContentType("application/json");
boolean isPost = "POST".equals(request.getMethod());
JSONObject retValue = null;
try {
if (command.equals(LIST_JOBS_PATH) && !isPost) {
retValue = handleListJobs(request);
} else if (command.equals(CLEANUP_JOB_PATH) && isPost) {
retValue = handleCleanupJob(request.getParameter("mapreduce_id"));
} else if (command.equals(ABORT_JOB_PATH) && isPost) {
retValue = handleAbortJob(request.getParameter("mapreduce_id"));
} else if (command.equals(GET_JOB_DETAIL_PATH) && !isPost) {
retValue = handleGetJobDetail(request.getParameter("mapreduce_id"));
}
} catch (Exception t) {
log.log(Level.SEVERE, "Got exception while running command", t);
try {
retValue = new JSONObject();
retValue.put("error_class", t.getClass().getName());
retValue.put("error_message",
"Full stack trace is available in the server logs. Message: "
+ t.getMessage());
} catch (JSONException e) {
throw new RuntimeException("Couldn't create error JSON object", e);
}
}
try {
if (retValue == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else {
retValue.write(response.getWriter());
response.getWriter().flush();
}
} catch (JSONException | IOException e) {
throw new RuntimeException("Couldn't write command response", e);
}
} | [
"static",
"void",
"handleCommand",
"(",
"String",
"command",
",",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"{",
"response",
".",
"setContentType",
"(",
"\"application/json\"",
")",
";",
"boolean",
"isPost",
"=",
"\"POST\"",
".",
... | Handles all status page commands. | [
"Handles",
"all",
"status",
"page",
"commands",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/handlers/StatusHandler.java#L79-L116 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/inputs/DatastoreShardStrategy.java | DatastoreShardStrategy.getScatterSplitPoints | private List<Range> getScatterSplitPoints(String namespace, String kind, final int numSegments) {
Query query = createQuery(namespace, kind).addSort(SCATTER_RESERVED_PROPERTY).setKeysOnly();
List<Key> splitPoints = sortKeys(runQuery(query, numSegments - 1));
List<Range> result = new ArrayList<>(splitPoints.size() + 1);
FilterPredicate lower = null;
for (Key k : splitPoints) {
result.add(new Range(lower, new FilterPredicate(KEY_RESERVED_PROPERTY, LESS_THAN, k)));
lower = new FilterPredicate(KEY_RESERVED_PROPERTY, GREATER_THAN_OR_EQUAL, k);
}
result.add(new Range(lower, null));
logger.info("Requested " + numSegments + " segments, retrieved " + result.size());
return result;
} | java | private List<Range> getScatterSplitPoints(String namespace, String kind, final int numSegments) {
Query query = createQuery(namespace, kind).addSort(SCATTER_RESERVED_PROPERTY).setKeysOnly();
List<Key> splitPoints = sortKeys(runQuery(query, numSegments - 1));
List<Range> result = new ArrayList<>(splitPoints.size() + 1);
FilterPredicate lower = null;
for (Key k : splitPoints) {
result.add(new Range(lower, new FilterPredicate(KEY_RESERVED_PROPERTY, LESS_THAN, k)));
lower = new FilterPredicate(KEY_RESERVED_PROPERTY, GREATER_THAN_OR_EQUAL, k);
}
result.add(new Range(lower, null));
logger.info("Requested " + numSegments + " segments, retrieved " + result.size());
return result;
} | [
"private",
"List",
"<",
"Range",
">",
"getScatterSplitPoints",
"(",
"String",
"namespace",
",",
"String",
"kind",
",",
"final",
"int",
"numSegments",
")",
"{",
"Query",
"query",
"=",
"createQuery",
"(",
"namespace",
",",
"kind",
")",
".",
"addSort",
"(",
"... | Uses the scatter property to distribute ranges to segments.
A random scatter property is added to 1 out of every 512 entities see:
https://github.com/GoogleCloudPlatform/appengine-mapreduce/wiki/ScatterPropertyImplementation
Retrieving the entities with the highest scatter values provides a random sample of entities.
Because they are randomly selected, their distribution in keyspace should be the same as other
entities.
Looking at Keyspace, It looks something like this:
|---*------*------*---*--------*-----*--------*--| Where "*" is a scatter entity and "-" is
some other entity.
So once sample entities are obtained them by key allows them to serve as boundaries between
ranges of keyspace. | [
"Uses",
"the",
"scatter",
"property",
"to",
"distribute",
"ranges",
"to",
"segments",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/inputs/DatastoreShardStrategy.java#L258-L270 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/handlers/MapReduceServletImpl.java | MapReduceServletImpl.doGet | public static void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String handler = getHandler(request);
if (handler.startsWith(COMMAND_PATH)) {
if (!checkForAjax(request, response)) {
return;
}
StatusHandler.handleCommand(handler.substring(COMMAND_PATH.length() + 1), request, response);
} else {
handleStaticResources(handler, response);
}
} | java | public static void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String handler = getHandler(request);
if (handler.startsWith(COMMAND_PATH)) {
if (!checkForAjax(request, response)) {
return;
}
StatusHandler.handleCommand(handler.substring(COMMAND_PATH.length() + 1), request, response);
} else {
handleStaticResources(handler, response);
}
} | [
"public",
"static",
"void",
"doGet",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"throws",
"IOException",
"{",
"String",
"handler",
"=",
"getHandler",
"(",
"request",
")",
";",
"if",
"(",
"handler",
".",
"startsWith",
"(",
... | Handle GET http requests. | [
"Handle",
"GET",
"http",
"requests",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/handlers/MapReduceServletImpl.java#L79-L90 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/handlers/MapReduceServletImpl.java | MapReduceServletImpl.doPost | public static void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String handler = getHandler(request);
if (handler.startsWith(CONTROLLER_PATH)) {
if (!checkForTaskQueue(request, response)) {
return;
}
new ShardedJobRunner<>().completeShard(
checkNotNull(request.getParameter(JOB_ID_PARAM), "Null job id"),
checkNotNull(request.getParameter(TASK_ID_PARAM), "Null task id"));
} else if (handler.startsWith(WORKER_PATH)) {
if (!checkForTaskQueue(request, response)) {
return;
}
new ShardedJobRunner<>().runTask(
checkNotNull(request.getParameter(JOB_ID_PARAM), "Null job id"),
checkNotNull(request.getParameter(TASK_ID_PARAM), "Null task id"),
Integer.parseInt(request.getParameter(SEQUENCE_NUMBER_PARAM)));
} else if (handler.startsWith(COMMAND_PATH)) {
if (!checkForAjax(request, response)) {
return;
}
StatusHandler.handleCommand(handler.substring(COMMAND_PATH.length() + 1), request, response);
} else {
throw new RuntimeException(
"Received an unknown MapReduce request handler. See logs for more detail.");
}
} | java | public static void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String handler = getHandler(request);
if (handler.startsWith(CONTROLLER_PATH)) {
if (!checkForTaskQueue(request, response)) {
return;
}
new ShardedJobRunner<>().completeShard(
checkNotNull(request.getParameter(JOB_ID_PARAM), "Null job id"),
checkNotNull(request.getParameter(TASK_ID_PARAM), "Null task id"));
} else if (handler.startsWith(WORKER_PATH)) {
if (!checkForTaskQueue(request, response)) {
return;
}
new ShardedJobRunner<>().runTask(
checkNotNull(request.getParameter(JOB_ID_PARAM), "Null job id"),
checkNotNull(request.getParameter(TASK_ID_PARAM), "Null task id"),
Integer.parseInt(request.getParameter(SEQUENCE_NUMBER_PARAM)));
} else if (handler.startsWith(COMMAND_PATH)) {
if (!checkForAjax(request, response)) {
return;
}
StatusHandler.handleCommand(handler.substring(COMMAND_PATH.length() + 1), request, response);
} else {
throw new RuntimeException(
"Received an unknown MapReduce request handler. See logs for more detail.");
}
} | [
"public",
"static",
"void",
"doPost",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"throws",
"IOException",
"{",
"String",
"handler",
"=",
"getHandler",
"(",
"request",
")",
";",
"if",
"(",
"handler",
".",
"startsWith",
"(",... | Handle POST http requests. | [
"Handle",
"POST",
"http",
"requests",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/handlers/MapReduceServletImpl.java#L95-L122 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/handlers/MapReduceServletImpl.java | MapReduceServletImpl.checkForAjax | private static boolean checkForAjax(HttpServletRequest request, HttpServletResponse response)
throws IOException {
if (!"XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
log.log(
Level.SEVERE, "Received unexpected non-XMLHttpRequest command. Possible CSRF attack.");
response.sendError(HttpServletResponse.SC_FORBIDDEN,
"Received unexpected non-XMLHttpRequest command.");
return false;
}
return true;
} | java | private static boolean checkForAjax(HttpServletRequest request, HttpServletResponse response)
throws IOException {
if (!"XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
log.log(
Level.SEVERE, "Received unexpected non-XMLHttpRequest command. Possible CSRF attack.");
response.sendError(HttpServletResponse.SC_FORBIDDEN,
"Received unexpected non-XMLHttpRequest command.");
return false;
}
return true;
} | [
"private",
"static",
"boolean",
"checkForAjax",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"\"XMLHttpRequest\"",
".",
"equals",
"(",
"request",
".",
"getHeader",
"(",
"\"X-Requeste... | Checks to ensure that the current request was sent via an AJAX request.
If the request was not sent by an AJAX request, returns false, and sets
the response status code to 403. This protects against CSRF attacks against
AJAX only handlers.
@return true if the request is a task queue request | [
"Checks",
"to",
"ensure",
"that",
"the",
"current",
"request",
"was",
"sent",
"via",
"an",
"AJAX",
"request",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/handlers/MapReduceServletImpl.java#L133-L143 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/handlers/MapReduceServletImpl.java | MapReduceServletImpl.checkForTaskQueue | private static boolean checkForTaskQueue(HttpServletRequest request,
HttpServletResponse response) throws IOException {
if (request.getHeader("X-AppEngine-QueueName") == null) {
log.log(Level.SEVERE, "Received unexpected non-task queue request. Possible CSRF attack.");
response.sendError(
HttpServletResponse.SC_FORBIDDEN, "Received unexpected non-task queue request.");
return false;
}
return true;
} | java | private static boolean checkForTaskQueue(HttpServletRequest request,
HttpServletResponse response) throws IOException {
if (request.getHeader("X-AppEngine-QueueName") == null) {
log.log(Level.SEVERE, "Received unexpected non-task queue request. Possible CSRF attack.");
response.sendError(
HttpServletResponse.SC_FORBIDDEN, "Received unexpected non-task queue request.");
return false;
}
return true;
} | [
"private",
"static",
"boolean",
"checkForTaskQueue",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"throws",
"IOException",
"{",
"if",
"(",
"request",
".",
"getHeader",
"(",
"\"X-AppEngine-QueueName\"",
")",
"==",
"null",
")",
"{... | Checks to ensure that the current request was sent via the task queue.
If the request is not in the task queue, returns false, and sets the
response status code to 403. This protects against CSRF attacks against
task queue-only handlers.
@return true if the request is a task queue request | [
"Checks",
"to",
"ensure",
"that",
"the",
"current",
"request",
"was",
"sent",
"via",
"the",
"task",
"queue",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/handlers/MapReduceServletImpl.java#L154-L163 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/handlers/MapReduceServletImpl.java | MapReduceServletImpl.getHandler | private static String getHandler(HttpServletRequest request) {
String pathInfo = request.getPathInfo();
return pathInfo == null ? "" : pathInfo.substring(1);
} | java | private static String getHandler(HttpServletRequest request) {
String pathInfo = request.getPathInfo();
return pathInfo == null ? "" : pathInfo.substring(1);
} | [
"private",
"static",
"String",
"getHandler",
"(",
"HttpServletRequest",
"request",
")",
"{",
"String",
"pathInfo",
"=",
"request",
".",
"getPathInfo",
"(",
")",
";",
"return",
"pathInfo",
"==",
"null",
"?",
"\"\"",
":",
"pathInfo",
".",
"substring",
"(",
"1"... | Returns the handler portion of the URL path.
For examples (for a servlet mapped as /foo/*):
getHandler(https://www.google.com/foo/bar) -> bar
getHandler(https://www.google.com/foo/bar/id) -> bar/id | [
"Returns",
"the",
"handler",
"portion",
"of",
"the",
"URL",
"path",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/handlers/MapReduceServletImpl.java#L172-L175 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/handlers/MemoryLimiter.java | MemoryLimiter.claim | public long claim(long toClaimMb) throws RejectRequestException {
Preconditions.checkArgument(toClaimMb >= 0);
if (toClaimMb == 0) {
return 0;
}
int neededForRequest = capRequestedSize(toClaimMb);
boolean acquired = false;
try {
acquired = amountRemaining.tryAcquire(neededForRequest, TIME_TO_WAIT, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RejectRequestException("Was interupted", e);
}
int remaining = amountRemaining.availablePermits();
if (acquired) {
log.info("Target available memory was " + (neededForRequest + remaining) + "mb is now "
+ remaining + "mb");
return neededForRequest;
} else {
throw new RejectRequestException("Not enough estimated memory for request: "
+ (neededForRequest) + "mb only have " + remaining + "mb remaining out of "
+ TOTAL_CLAIMABLE_MEMORY_SIZE_MB + "mb");
}
} | java | public long claim(long toClaimMb) throws RejectRequestException {
Preconditions.checkArgument(toClaimMb >= 0);
if (toClaimMb == 0) {
return 0;
}
int neededForRequest = capRequestedSize(toClaimMb);
boolean acquired = false;
try {
acquired = amountRemaining.tryAcquire(neededForRequest, TIME_TO_WAIT, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RejectRequestException("Was interupted", e);
}
int remaining = amountRemaining.availablePermits();
if (acquired) {
log.info("Target available memory was " + (neededForRequest + remaining) + "mb is now "
+ remaining + "mb");
return neededForRequest;
} else {
throw new RejectRequestException("Not enough estimated memory for request: "
+ (neededForRequest) + "mb only have " + remaining + "mb remaining out of "
+ TOTAL_CLAIMABLE_MEMORY_SIZE_MB + "mb");
}
} | [
"public",
"long",
"claim",
"(",
"long",
"toClaimMb",
")",
"throws",
"RejectRequestException",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"toClaimMb",
">=",
"0",
")",
";",
"if",
"(",
"toClaimMb",
"==",
"0",
")",
"{",
"return",
"0",
";",
"}",
"int",
... | This method attempts to claim ram to the provided request. This may block waiting for some to
be available. Ultimately it is either granted memory or an exception is thrown.
@param toClaimMb The amount of memory the request wishes to claim. (In Megabytes)
@return The amount of memory which was claimed. (This may be different from the amount
requested.) This value needs to be passed to {@link #release} when the request exits.
@throws RejectRequestException If the request should be rejected because it could not be given
the resources requested. | [
"This",
"method",
"attempts",
"to",
"claim",
"ram",
"to",
"the",
"provided",
"request",
".",
"This",
"may",
"block",
"waiting",
"for",
"some",
"to",
"be",
"available",
".",
"Ultimately",
"it",
"is",
"either",
"granted",
"memory",
"or",
"an",
"exception",
"... | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/handlers/MemoryLimiter.java#L44-L67 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/shardedjob/IncrementalTaskState.java | IncrementalTaskState.create | static <T extends IncrementalTask> IncrementalTaskState<T> create(
String taskId, String jobId, long createTime, T initialTask) {
return new IncrementalTaskState<>(taskId, jobId, createTime, new LockInfo(null, null),
checkNotNull(initialTask), new Status(StatusCode.RUNNING));
} | java | static <T extends IncrementalTask> IncrementalTaskState<T> create(
String taskId, String jobId, long createTime, T initialTask) {
return new IncrementalTaskState<>(taskId, jobId, createTime, new LockInfo(null, null),
checkNotNull(initialTask), new Status(StatusCode.RUNNING));
} | [
"static",
"<",
"T",
"extends",
"IncrementalTask",
">",
"IncrementalTaskState",
"<",
"T",
">",
"create",
"(",
"String",
"taskId",
",",
"String",
"jobId",
",",
"long",
"createTime",
",",
"T",
"initialTask",
")",
"{",
"return",
"new",
"IncrementalTaskState",
"<>"... | Returns a new running IncrementalTaskState. | [
"Returns",
"a",
"new",
"running",
"IncrementalTaskState",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/shardedjob/IncrementalTaskState.java#L79-L83 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/DatastoreMutationPool.java | DatastoreMutationPool.delete | public void delete(Key key) {
// This is probably a serious overestimation, but I can't see a good
// way to find the size in the public API.
int bytesHere = KeyFactory.keyToString(key).length();
// Do this before the add so that we guarantee that size is never > sizeLimit
if (deletesBytes + bytesHere >= params.getBytesLimit()) {
flushDeletes();
}
deletesBytes += bytesHere;
deletes.add(key);
if (deletes.size() >= params.getCountLimit()) {
flushDeletes();
}
} | java | public void delete(Key key) {
// This is probably a serious overestimation, but I can't see a good
// way to find the size in the public API.
int bytesHere = KeyFactory.keyToString(key).length();
// Do this before the add so that we guarantee that size is never > sizeLimit
if (deletesBytes + bytesHere >= params.getBytesLimit()) {
flushDeletes();
}
deletesBytes += bytesHere;
deletes.add(key);
if (deletes.size() >= params.getCountLimit()) {
flushDeletes();
}
} | [
"public",
"void",
"delete",
"(",
"Key",
"key",
")",
"{",
"// This is probably a serious overestimation, but I can't see a good",
"// way to find the size in the public API.",
"int",
"bytesHere",
"=",
"KeyFactory",
".",
"keyToString",
"(",
"key",
")",
".",
"length",
"(",
"... | Adds a mutation to put the given entity to the datastore. | [
"Adds",
"a",
"mutation",
"to",
"put",
"the",
"given",
"entity",
"to",
"the",
"datastore",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/DatastoreMutationPool.java#L151-L167 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/DatastoreMutationPool.java | DatastoreMutationPool.put | public void put(Entity entity) {
int bytesHere = EntityTranslator.convertToPb(entity).getSerializedSize();
// Do this before the add so that we guarantee that size is never > sizeLimit
if (putsBytes + bytesHere >= params.getBytesLimit()) {
flushPuts();
}
putsBytes += bytesHere;
puts.add(entity);
if (puts.size() >= params.getCountLimit()) {
flushPuts();
}
} | java | public void put(Entity entity) {
int bytesHere = EntityTranslator.convertToPb(entity).getSerializedSize();
// Do this before the add so that we guarantee that size is never > sizeLimit
if (putsBytes + bytesHere >= params.getBytesLimit()) {
flushPuts();
}
putsBytes += bytesHere;
puts.add(entity);
if (puts.size() >= params.getCountLimit()) {
flushPuts();
}
} | [
"public",
"void",
"put",
"(",
"Entity",
"entity",
")",
"{",
"int",
"bytesHere",
"=",
"EntityTranslator",
".",
"convertToPb",
"(",
"entity",
")",
".",
"getSerializedSize",
"(",
")",
";",
"// Do this before the add so that we guarantee that size is never > sizeLimit",
"if... | Adds a mutation deleting the entity with the given key. | [
"Adds",
"a",
"mutation",
"deleting",
"the",
"entity",
"with",
"the",
"given",
"key",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/DatastoreMutationPool.java#L172-L186 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java | SortWorker.writeOutData | private void writeOutData() {
if (valuesHeld == 0) {
return;
}
int batchSize = batchItemSizePerEmmit == null ? DEFAULT_SORT_BATCH_PER_EMIT_BYTES
: batchItemSizePerEmmit;
ByteBuffer currentKey = getKeyValueFromPointer(0).getKey();
List<ByteBuffer> currentValues = new ArrayList<>();
int totalSize = 0;
for (int i = 0; i < valuesHeld; i++) {
KeyValue<ByteBuffer, ByteBuffer> keyValue = getKeyValueFromPointer(i);
int compare = LexicographicalComparator.compareBuffers(keyValue.getKey(), currentKey);
if (compare == 0) {
if (!currentValues.isEmpty() && totalSize >= batchSize) {
emitCurrentOrLeftover(currentKey, currentValues);
totalSize = 0;
}
currentValues.add(keyValue.getValue());
totalSize += Math.max(1, keyValue.getValue().remaining());
} else if (compare > 0) {
emitCurrentOrLeftover(currentKey, currentValues);
currentKey = keyValue.getKey();
currentValues.add(keyValue.getValue());
totalSize = Math.max(1, keyValue.getValue().remaining());
} else {
throw new IllegalStateException("Sort failed to properly order output");
}
}
emitCurrentOrLeftover(currentKey, currentValues);
if (leftover != null) {
emit(leftover.getKey(), leftover.getValue());
}
} | java | private void writeOutData() {
if (valuesHeld == 0) {
return;
}
int batchSize = batchItemSizePerEmmit == null ? DEFAULT_SORT_BATCH_PER_EMIT_BYTES
: batchItemSizePerEmmit;
ByteBuffer currentKey = getKeyValueFromPointer(0).getKey();
List<ByteBuffer> currentValues = new ArrayList<>();
int totalSize = 0;
for (int i = 0; i < valuesHeld; i++) {
KeyValue<ByteBuffer, ByteBuffer> keyValue = getKeyValueFromPointer(i);
int compare = LexicographicalComparator.compareBuffers(keyValue.getKey(), currentKey);
if (compare == 0) {
if (!currentValues.isEmpty() && totalSize >= batchSize) {
emitCurrentOrLeftover(currentKey, currentValues);
totalSize = 0;
}
currentValues.add(keyValue.getValue());
totalSize += Math.max(1, keyValue.getValue().remaining());
} else if (compare > 0) {
emitCurrentOrLeftover(currentKey, currentValues);
currentKey = keyValue.getKey();
currentValues.add(keyValue.getValue());
totalSize = Math.max(1, keyValue.getValue().remaining());
} else {
throw new IllegalStateException("Sort failed to properly order output");
}
}
emitCurrentOrLeftover(currentKey, currentValues);
if (leftover != null) {
emit(leftover.getKey(), leftover.getValue());
}
} | [
"private",
"void",
"writeOutData",
"(",
")",
"{",
"if",
"(",
"valuesHeld",
"==",
"0",
")",
"{",
"return",
";",
"}",
"int",
"batchSize",
"=",
"batchItemSizePerEmmit",
"==",
"null",
"?",
"DEFAULT_SORT_BATCH_PER_EMIT_BYTES",
":",
"batchItemSizePerEmmit",
";",
"Byte... | Writes out the key value pairs in order.
If there are multiple consecutive values with the same key, they can be combined to avoid
repeating the key.
In the event the buffer is full, there is one leftover item which did not go into it,
and hence was not sorted. So a merge between this one item and the sorted list is done on the
way out. | [
"Writes",
"out",
"the",
"key",
"value",
"pairs",
"in",
"order",
".",
"If",
"there",
"are",
"multiple",
"consecutive",
"values",
"with",
"the",
"same",
"key",
"they",
"can",
"be",
"combined",
"to",
"avoid",
"repeating",
"the",
"key",
".",
"In",
"the",
"ev... | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java#L149-L183 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java | SortWorker.addValue | public void addValue(ByteBuffer key, ByteBuffer value) {
if (isFull) {
throw new IllegalArgumentException("Already full");
}
if (value.remaining() + key.remaining() + POINTER_SIZE_BYTES > memoryBuffer.remaining()) {
leftover = new KeyValue<>(key, value);
isFull = true;
} else {
int keyPos = spliceIn(key, memoryBuffer);
int valuePos = spliceIn(value, memoryBuffer);
addPointer(keyPos, key.remaining(), valuePos, value.remaining());
}
} | java | public void addValue(ByteBuffer key, ByteBuffer value) {
if (isFull) {
throw new IllegalArgumentException("Already full");
}
if (value.remaining() + key.remaining() + POINTER_SIZE_BYTES > memoryBuffer.remaining()) {
leftover = new KeyValue<>(key, value);
isFull = true;
} else {
int keyPos = spliceIn(key, memoryBuffer);
int valuePos = spliceIn(value, memoryBuffer);
addPointer(keyPos, key.remaining(), valuePos, value.remaining());
}
} | [
"public",
"void",
"addValue",
"(",
"ByteBuffer",
"key",
",",
"ByteBuffer",
"value",
")",
"{",
"if",
"(",
"isFull",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Already full\"",
")",
";",
"}",
"if",
"(",
"value",
".",
"remaining",
"(",
")",... | Add a new key and value to the in memory buffer. | [
"Add",
"a",
"new",
"key",
"and",
"value",
"to",
"the",
"in",
"memory",
"buffer",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java#L227-L239 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java | SortWorker.getKeyFromPointer | final ByteBuffer getKeyFromPointer(int index) {
int origionalLimit = memoryBuffer.limit();
memoryBuffer.limit(memoryBuffer.capacity());
int pointerOffset = computePointerOffset(index);
int keyPos = memoryBuffer.getInt(pointerOffset);
int valuePos = memoryBuffer.getInt(pointerOffset + 4);
memoryBuffer.limit(origionalLimit);
assert valuePos >= keyPos;
ByteBuffer key = sliceOutRange(keyPos, valuePos);
return key;
} | java | final ByteBuffer getKeyFromPointer(int index) {
int origionalLimit = memoryBuffer.limit();
memoryBuffer.limit(memoryBuffer.capacity());
int pointerOffset = computePointerOffset(index);
int keyPos = memoryBuffer.getInt(pointerOffset);
int valuePos = memoryBuffer.getInt(pointerOffset + 4);
memoryBuffer.limit(origionalLimit);
assert valuePos >= keyPos;
ByteBuffer key = sliceOutRange(keyPos, valuePos);
return key;
} | [
"final",
"ByteBuffer",
"getKeyFromPointer",
"(",
"int",
"index",
")",
"{",
"int",
"origionalLimit",
"=",
"memoryBuffer",
".",
"limit",
"(",
")",
";",
"memoryBuffer",
".",
"limit",
"(",
"memoryBuffer",
".",
"capacity",
"(",
")",
")",
";",
"int",
"pointerOffse... | Get a key given the index of its pointer. | [
"Get",
"a",
"key",
"given",
"the",
"index",
"of",
"its",
"pointer",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java#L244-L254 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java | SortWorker.getKeyValueFromPointer | final KeyValue<ByteBuffer, ByteBuffer> getKeyValueFromPointer(int index) {
int origionalLimit = memoryBuffer.limit();
memoryBuffer.limit(memoryBuffer.capacity());
int pointerOffset = computePointerOffset(index);
int keyPos = memoryBuffer.getInt(pointerOffset);
int valuePos = memoryBuffer.getInt(pointerOffset + 4);
int valueLength = memoryBuffer.getInt(pointerOffset + 8);
memoryBuffer.limit(origionalLimit);
assert valuePos >= keyPos;
ByteBuffer key = sliceOutRange(keyPos, valuePos);
ByteBuffer value = sliceOutRange(valuePos, valuePos + valueLength);
return new KeyValue<>(key, value);
} | java | final KeyValue<ByteBuffer, ByteBuffer> getKeyValueFromPointer(int index) {
int origionalLimit = memoryBuffer.limit();
memoryBuffer.limit(memoryBuffer.capacity());
int pointerOffset = computePointerOffset(index);
int keyPos = memoryBuffer.getInt(pointerOffset);
int valuePos = memoryBuffer.getInt(pointerOffset + 4);
int valueLength = memoryBuffer.getInt(pointerOffset + 8);
memoryBuffer.limit(origionalLimit);
assert valuePos >= keyPos;
ByteBuffer key = sliceOutRange(keyPos, valuePos);
ByteBuffer value = sliceOutRange(valuePos, valuePos + valueLength);
return new KeyValue<>(key, value);
} | [
"final",
"KeyValue",
"<",
"ByteBuffer",
",",
"ByteBuffer",
">",
"getKeyValueFromPointer",
"(",
"int",
"index",
")",
"{",
"int",
"origionalLimit",
"=",
"memoryBuffer",
".",
"limit",
"(",
")",
";",
"memoryBuffer",
".",
"limit",
"(",
"memoryBuffer",
".",
"capacit... | Get a key and its value given the index of its pointer. | [
"Get",
"a",
"key",
"and",
"its",
"value",
"given",
"the",
"index",
"of",
"its",
"pointer",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java#L259-L271 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java | SortWorker.swapPointers | final void swapPointers(int indexA, int indexB) {
assert indexA >= 0 && indexA < valuesHeld;
assert indexB >= 0 && indexB < valuesHeld;
ByteBuffer a = copyPointer(indexA);
ByteBuffer b = readPointer(indexB);
writePointer(indexA, b);
writePointer(indexB, a);
} | java | final void swapPointers(int indexA, int indexB) {
assert indexA >= 0 && indexA < valuesHeld;
assert indexB >= 0 && indexB < valuesHeld;
ByteBuffer a = copyPointer(indexA);
ByteBuffer b = readPointer(indexB);
writePointer(indexA, b);
writePointer(indexB, a);
} | [
"final",
"void",
"swapPointers",
"(",
"int",
"indexA",
",",
"int",
"indexB",
")",
"{",
"assert",
"indexA",
">=",
"0",
"&&",
"indexA",
"<",
"valuesHeld",
";",
"assert",
"indexB",
">=",
"0",
"&&",
"indexB",
"<",
"valuesHeld",
";",
"ByteBuffer",
"a",
"=",
... | Place the pointer at indexA in indexB and vice versa. | [
"Place",
"the",
"pointer",
"at",
"indexA",
"in",
"indexB",
"and",
"vice",
"versa",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java#L292-L300 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java | SortWorker.readPointer | final ByteBuffer readPointer(int index) {
int pointerOffset = computePointerOffset(index);
return sliceOutRange(pointerOffset, pointerOffset + POINTER_SIZE_BYTES);
} | java | final ByteBuffer readPointer(int index) {
int pointerOffset = computePointerOffset(index);
return sliceOutRange(pointerOffset, pointerOffset + POINTER_SIZE_BYTES);
} | [
"final",
"ByteBuffer",
"readPointer",
"(",
"int",
"index",
")",
"{",
"int",
"pointerOffset",
"=",
"computePointerOffset",
"(",
"index",
")",
";",
"return",
"sliceOutRange",
"(",
"pointerOffset",
",",
"pointerOffset",
"+",
"POINTER_SIZE_BYTES",
")",
";",
"}"
] | Read a pointer from the specified index. | [
"Read",
"a",
"pointer",
"from",
"the",
"specified",
"index",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java#L328-L331 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java | SortWorker.copyPointer | final ByteBuffer copyPointer(int index) {
ByteBuffer pointer = readPointer(index);
// Making a copy for so that someone can modify the underlying impl
ByteBuffer result = ByteBuffer.allocate(pointer.capacity());
result.put(pointer);
result.flip();
return result;
} | java | final ByteBuffer copyPointer(int index) {
ByteBuffer pointer = readPointer(index);
// Making a copy for so that someone can modify the underlying impl
ByteBuffer result = ByteBuffer.allocate(pointer.capacity());
result.put(pointer);
result.flip();
return result;
} | [
"final",
"ByteBuffer",
"copyPointer",
"(",
"int",
"index",
")",
"{",
"ByteBuffer",
"pointer",
"=",
"readPointer",
"(",
"index",
")",
";",
"// Making a copy for so that someone can modify the underlying impl",
"ByteBuffer",
"result",
"=",
"ByteBuffer",
".",
"allocate",
"... | Get a Copy of a pointer | [
"Get",
"a",
"Copy",
"of",
"a",
"pointer"
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java#L336-L343 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java | SortWorker.addPointer | final void addPointer(int keyPos, int keySize, int valuePos, int valueSize) {
assert keyPos + keySize == valuePos;
int start = memoryBuffer.limit() - POINTER_SIZE_BYTES;
memoryBuffer.putInt(start, keyPos);
memoryBuffer.putInt(start + 4, valuePos);
memoryBuffer.putInt(start + 8, valueSize);
memoryBuffer.limit(start);
valuesHeld++;
} | java | final void addPointer(int keyPos, int keySize, int valuePos, int valueSize) {
assert keyPos + keySize == valuePos;
int start = memoryBuffer.limit() - POINTER_SIZE_BYTES;
memoryBuffer.putInt(start, keyPos);
memoryBuffer.putInt(start + 4, valuePos);
memoryBuffer.putInt(start + 8, valueSize);
memoryBuffer.limit(start);
valuesHeld++;
} | [
"final",
"void",
"addPointer",
"(",
"int",
"keyPos",
",",
"int",
"keySize",
",",
"int",
"valuePos",
",",
"int",
"valueSize",
")",
"{",
"assert",
"keyPos",
"+",
"keySize",
"==",
"valuePos",
";",
"int",
"start",
"=",
"memoryBuffer",
".",
"limit",
"(",
")",... | Add a pointer to the key value pair with the provided parameters. | [
"Add",
"a",
"pointer",
"to",
"the",
"key",
"value",
"pair",
"with",
"the",
"provided",
"parameters",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java#L348-L356 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java | SortWorker.spliceIn | private static int spliceIn(ByteBuffer src, ByteBuffer dest) {
int position = dest.position();
int srcPos = src.position();
dest.put(src);
src.position(srcPos);
return position;
} | java | private static int spliceIn(ByteBuffer src, ByteBuffer dest) {
int position = dest.position();
int srcPos = src.position();
dest.put(src);
src.position(srcPos);
return position;
} | [
"private",
"static",
"int",
"spliceIn",
"(",
"ByteBuffer",
"src",
",",
"ByteBuffer",
"dest",
")",
"{",
"int",
"position",
"=",
"dest",
".",
"position",
"(",
")",
";",
"int",
"srcPos",
"=",
"src",
".",
"position",
"(",
")",
";",
"dest",
".",
"put",
"(... | Write the contents of src to dest, without messing with src's position.
@param dest (position is advanced)
@return the pos in dest where src is written | [
"Write",
"the",
"contents",
"of",
"src",
"to",
"dest",
"without",
"messing",
"with",
"src",
"s",
"position",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/sort/SortWorker.java#L364-L370 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/shardedjob/InProcessShardedJobRunner.java | InProcessShardedJobRunner.runJob | public static <T extends IncrementalTask> void runJob(
List<T> initialTasks, ShardedJobController<T> controller) {
List<T> results = new ArrayList<>();
for (T task : initialTasks) {
Preconditions.checkNotNull(task, "Null initial task: %s", initialTasks);
task.prepare();
do {
task.run();
} while (!task.isDone());
task.cleanup();
results.add(task);
}
controller.completed(results.iterator());
} | java | public static <T extends IncrementalTask> void runJob(
List<T> initialTasks, ShardedJobController<T> controller) {
List<T> results = new ArrayList<>();
for (T task : initialTasks) {
Preconditions.checkNotNull(task, "Null initial task: %s", initialTasks);
task.prepare();
do {
task.run();
} while (!task.isDone());
task.cleanup();
results.add(task);
}
controller.completed(results.iterator());
} | [
"public",
"static",
"<",
"T",
"extends",
"IncrementalTask",
">",
"void",
"runJob",
"(",
"List",
"<",
"T",
">",
"initialTasks",
",",
"ShardedJobController",
"<",
"T",
">",
"controller",
")",
"{",
"List",
"<",
"T",
">",
"results",
"=",
"new",
"ArrayList",
... | Runs the given job and returns its result. | [
"Runs",
"the",
"given",
"job",
"and",
"returns",
"its",
"result",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/shardedjob/InProcessShardedJobRunner.java#L24-L37 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/Shuffling.java | Shuffling.multimapToList | private static <K, V> List<KeyValue<K, List<V>>> multimapToList(
Marshaller<K> keyMarshaller, ListMultimap<Bytes, V> in) {
List<Bytes> keys = Ordering.natural().sortedCopy(in.keySet());
ImmutableList.Builder<KeyValue<K, List<V>>> out = ImmutableList.builder();
for (Bytes keyBytes : keys) {
K key = keyMarshaller.fromBytes(ByteBuffer.wrap(keyBytes.bytes));
out.add(KeyValue.of(key, in.get(keyBytes)));
}
return out.build();
} | java | private static <K, V> List<KeyValue<K, List<V>>> multimapToList(
Marshaller<K> keyMarshaller, ListMultimap<Bytes, V> in) {
List<Bytes> keys = Ordering.natural().sortedCopy(in.keySet());
ImmutableList.Builder<KeyValue<K, List<V>>> out = ImmutableList.builder();
for (Bytes keyBytes : keys) {
K key = keyMarshaller.fromBytes(ByteBuffer.wrap(keyBytes.bytes));
out.add(KeyValue.of(key, in.get(keyBytes)));
}
return out.build();
} | [
"private",
"static",
"<",
"K",
",",
"V",
">",
"List",
"<",
"KeyValue",
"<",
"K",
",",
"List",
"<",
"V",
">",
">",
">",
"multimapToList",
"(",
"Marshaller",
"<",
"K",
">",
"keyMarshaller",
",",
"ListMultimap",
"<",
"Bytes",
",",
"V",
">",
"in",
")",... | Also turns the keys back from Bytes into K. | [
"Also",
"turns",
"the",
"keys",
"back",
"from",
"Bytes",
"into",
"K",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/Shuffling.java#L99-L108 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/outputs/InMemoryOutput.java | InMemoryOutput.finish | @Override
public List<List<O>> finish(Collection<? extends OutputWriter<O>> writers) {
ImmutableList.Builder<List<O>> out = ImmutableList.builder();
for (OutputWriter<O> w : writers) {
InMemoryOutputWriter<O> writer = (InMemoryOutputWriter<O>) w;
out.add(ImmutableList.copyOf(writer.getResult()));
}
return out.build();
} | java | @Override
public List<List<O>> finish(Collection<? extends OutputWriter<O>> writers) {
ImmutableList.Builder<List<O>> out = ImmutableList.builder();
for (OutputWriter<O> w : writers) {
InMemoryOutputWriter<O> writer = (InMemoryOutputWriter<O>) w;
out.add(ImmutableList.copyOf(writer.getResult()));
}
return out.build();
} | [
"@",
"Override",
"public",
"List",
"<",
"List",
"<",
"O",
">",
">",
"finish",
"(",
"Collection",
"<",
"?",
"extends",
"OutputWriter",
"<",
"O",
">",
">",
"writers",
")",
"{",
"ImmutableList",
".",
"Builder",
"<",
"List",
"<",
"O",
">>",
"out",
"=",
... | Returns a list of lists where the outer list has one element for each
reduce shard, which is a list of the values emitted by that shard, in
order. | [
"Returns",
"a",
"list",
"of",
"lists",
"where",
"the",
"outer",
"list",
"has",
"one",
"element",
"for",
"each",
"reduce",
"shard",
"which",
"is",
"a",
"list",
"of",
"the",
"values",
"emitted",
"by",
"that",
"shard",
"in",
"order",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/outputs/InMemoryOutput.java#L39-L47 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/MergingReader.java | MergingReader.next | @Override
public KeyValue<K, Iterator<V>> next() throws NoSuchElementException {
if (combineValues) {
skipLeftoverItems();
}
PeekingInputReader<KeyValue<ByteBuffer, ? extends Iterable<V>>> reader =
lowestReaderQueue.remove();
KeyValue<ByteBuffer, ? extends Iterable<V>> lowest = reader.next();
ByteBuffer lowestKey = lowest.getKey();
addReaderToQueueIfNotEmpty(reader);
lastKey = SerializableValue.of(getByteBufferMarshaller(), lowestKey);
if (combineValues) {
CombiningReader values = new CombiningReader(lowestKey, lowest.getValue());
return new KeyValue<K, Iterator<V>>(keyMarshaller.fromBytes(lowestKey.slice()), values);
} else {
return new KeyValue<>(keyMarshaller.fromBytes(lowestKey.slice()),
lowest.getValue().iterator());
}
} | java | @Override
public KeyValue<K, Iterator<V>> next() throws NoSuchElementException {
if (combineValues) {
skipLeftoverItems();
}
PeekingInputReader<KeyValue<ByteBuffer, ? extends Iterable<V>>> reader =
lowestReaderQueue.remove();
KeyValue<ByteBuffer, ? extends Iterable<V>> lowest = reader.next();
ByteBuffer lowestKey = lowest.getKey();
addReaderToQueueIfNotEmpty(reader);
lastKey = SerializableValue.of(getByteBufferMarshaller(), lowestKey);
if (combineValues) {
CombiningReader values = new CombiningReader(lowestKey, lowest.getValue());
return new KeyValue<K, Iterator<V>>(keyMarshaller.fromBytes(lowestKey.slice()), values);
} else {
return new KeyValue<>(keyMarshaller.fromBytes(lowestKey.slice()),
lowest.getValue().iterator());
}
} | [
"@",
"Override",
"public",
"KeyValue",
"<",
"K",
",",
"Iterator",
"<",
"V",
">",
">",
"next",
"(",
")",
"throws",
"NoSuchElementException",
"{",
"if",
"(",
"combineValues",
")",
"{",
"skipLeftoverItems",
"(",
")",
";",
"}",
"PeekingInputReader",
"<",
"KeyV... | Returns the next KeyValues object for the reducer. This is the entry point.
@throws NoSuchElementException if there are no more keys in the input. | [
"Returns",
"the",
"next",
"KeyValues",
"object",
"for",
"the",
"reducer",
".",
"This",
"is",
"the",
"entry",
"point",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/MergingReader.java#L167-L185 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/MergingReader.java | MergingReader.skipLeftoverItems | private void skipLeftoverItems() {
if (lastKey == null || lowestReaderQueue.isEmpty()) {
return;
}
boolean itemSkiped;
do {
PeekingInputReader<KeyValue<ByteBuffer, ? extends Iterable<V>>> reader =
lowestReaderQueue.remove();
itemSkiped = skipItemsOnReader(reader);
addReaderToQueueIfNotEmpty(reader);
} while (itemSkiped);
} | java | private void skipLeftoverItems() {
if (lastKey == null || lowestReaderQueue.isEmpty()) {
return;
}
boolean itemSkiped;
do {
PeekingInputReader<KeyValue<ByteBuffer, ? extends Iterable<V>>> reader =
lowestReaderQueue.remove();
itemSkiped = skipItemsOnReader(reader);
addReaderToQueueIfNotEmpty(reader);
} while (itemSkiped);
} | [
"private",
"void",
"skipLeftoverItems",
"(",
")",
"{",
"if",
"(",
"lastKey",
"==",
"null",
"||",
"lowestReaderQueue",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
";",
"}",
"boolean",
"itemSkiped",
";",
"do",
"{",
"PeekingInputReader",
"<",
"KeyValue",
"<... | It is possible that a reducer does not iterate over all of the items given to it for a given
key. However on the next callback they expect to receive items for the following key. this
method skips over all the left over items from the previous key they did not read. | [
"It",
"is",
"possible",
"that",
"a",
"reducer",
"does",
"not",
"iterate",
"over",
"all",
"of",
"the",
"items",
"given",
"to",
"it",
"for",
"a",
"given",
"key",
".",
"However",
"on",
"the",
"next",
"callback",
"they",
"expect",
"to",
"receive",
"items",
... | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/MergingReader.java#L199-L210 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/MergingReader.java | MergingReader.skipItemsOnReader | private boolean skipItemsOnReader(
PeekingInputReader<KeyValue<ByteBuffer, ? extends Iterable<V>>> reader) {
boolean itemSkipped = false;
KeyValue<ByteBuffer, ? extends Iterable<V>> keyValue = reader.peek();
while (keyValue != null && compareBuffers(keyValue.getKey(), lastKey.getValue()) == 0) {
consumePeekedValueFromReader(keyValue, reader);
itemSkipped = true;
keyValue = reader.peek();
}
return itemSkipped;
} | java | private boolean skipItemsOnReader(
PeekingInputReader<KeyValue<ByteBuffer, ? extends Iterable<V>>> reader) {
boolean itemSkipped = false;
KeyValue<ByteBuffer, ? extends Iterable<V>> keyValue = reader.peek();
while (keyValue != null && compareBuffers(keyValue.getKey(), lastKey.getValue()) == 0) {
consumePeekedValueFromReader(keyValue, reader);
itemSkipped = true;
keyValue = reader.peek();
}
return itemSkipped;
} | [
"private",
"boolean",
"skipItemsOnReader",
"(",
"PeekingInputReader",
"<",
"KeyValue",
"<",
"ByteBuffer",
",",
"?",
"extends",
"Iterable",
"<",
"V",
">",
">",
">",
"reader",
")",
"{",
"boolean",
"itemSkipped",
"=",
"false",
";",
"KeyValue",
"<",
"ByteBuffer",
... | Helper function for skipLeftoverItems to skip items matching last key on a single reader. | [
"Helper",
"function",
"for",
"skipLeftoverItems",
"to",
"skip",
"items",
"matching",
"last",
"key",
"on",
"a",
"single",
"reader",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/MergingReader.java#L215-L225 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/inputs/LevelDbInputReader.java | LevelDbInputReader.readPhysicalRecord | private Record readPhysicalRecord(boolean expectEnd) throws IOException {
int bytesToBlockEnd = findBytesToBlockEnd();
if (bytesToBlockEnd < HEADER_LENGTH) {
readToTmp(bytesToBlockEnd, expectEnd);
return createRecordFromTmp(RecordType.NONE);
}
readToTmp(HEADER_LENGTH, expectEnd);
int checksum = tmpBuffer.getInt();
int length = tmpBuffer.getShort();
if (length > bytesToBlockEnd || length < 0) {
throw new CorruptDataException("Length is too large:" + length);
}
RecordType type = RecordType.get(tmpBuffer.get());
if (type == RecordType.NONE && length == 0) {
length = bytesToBlockEnd - HEADER_LENGTH;
}
readToTmp(length, false);
if (!isValidCrc(checksum, tmpBuffer, type.value())) {
throw new CorruptDataException("Checksum doesn't validate.");
}
return createRecordFromTmp(type);
} | java | private Record readPhysicalRecord(boolean expectEnd) throws IOException {
int bytesToBlockEnd = findBytesToBlockEnd();
if (bytesToBlockEnd < HEADER_LENGTH) {
readToTmp(bytesToBlockEnd, expectEnd);
return createRecordFromTmp(RecordType.NONE);
}
readToTmp(HEADER_LENGTH, expectEnd);
int checksum = tmpBuffer.getInt();
int length = tmpBuffer.getShort();
if (length > bytesToBlockEnd || length < 0) {
throw new CorruptDataException("Length is too large:" + length);
}
RecordType type = RecordType.get(tmpBuffer.get());
if (type == RecordType.NONE && length == 0) {
length = bytesToBlockEnd - HEADER_LENGTH;
}
readToTmp(length, false);
if (!isValidCrc(checksum, tmpBuffer, type.value())) {
throw new CorruptDataException("Checksum doesn't validate.");
}
return createRecordFromTmp(type);
} | [
"private",
"Record",
"readPhysicalRecord",
"(",
"boolean",
"expectEnd",
")",
"throws",
"IOException",
"{",
"int",
"bytesToBlockEnd",
"=",
"findBytesToBlockEnd",
"(",
")",
";",
"if",
"(",
"bytesToBlockEnd",
"<",
"HEADER_LENGTH",
")",
"{",
"readToTmp",
"(",
"bytesTo... | Reads the next record from the LevelDb data stream.
@param expectEnd if end of stream encountered will throw {@link NoSuchElementException} when
true and {@link CorruptDataException} when false.
@return Record data of the physical record read.
@throws IOException | [
"Reads",
"the",
"next",
"record",
"from",
"the",
"LevelDb",
"data",
"stream",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/inputs/LevelDbInputReader.java#L188-L211 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/inputs/LevelDbInputReader.java | LevelDbInputReader.copyAll | private static ByteBuffer copyAll(List<ByteBuffer> buffers) {
int size = 0;
for (ByteBuffer b : buffers) {
size += b.remaining();
}
ByteBuffer result = allocate(size);
for (ByteBuffer b : buffers) {
result.put(b);
}
result.flip();
return result;
} | java | private static ByteBuffer copyAll(List<ByteBuffer> buffers) {
int size = 0;
for (ByteBuffer b : buffers) {
size += b.remaining();
}
ByteBuffer result = allocate(size);
for (ByteBuffer b : buffers) {
result.put(b);
}
result.flip();
return result;
} | [
"private",
"static",
"ByteBuffer",
"copyAll",
"(",
"List",
"<",
"ByteBuffer",
">",
"buffers",
")",
"{",
"int",
"size",
"=",
"0",
";",
"for",
"(",
"ByteBuffer",
"b",
":",
"buffers",
")",
"{",
"size",
"+=",
"b",
".",
"remaining",
"(",
")",
";",
"}",
... | Copies a list of byteBuffers into a single new byteBuffer. | [
"Copies",
"a",
"list",
"of",
"byteBuffers",
"into",
"a",
"single",
"new",
"byteBuffer",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/inputs/LevelDbInputReader.java#L268-L279 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/outputs/SizeSegmentedGoogleCloudStorageFileOutput.java | SizeSegmentedGoogleCloudStorageFileOutput.finish | @Override
public GoogleCloudStorageFileSet finish(Collection<? extends OutputWriter<ByteBuffer>> writers)
throws IOException {
List<String> fileNames = new ArrayList<>();
for (OutputWriter<ByteBuffer> writer : writers) {
SizeSegmentingGoogleCloudStorageFileWriter segWriter =
(SizeSegmentingGoogleCloudStorageFileWriter) writer;
for (GoogleCloudStorageFileOutputWriter delegatedWriter : segWriter.getDelegatedWriters()) {
fileNames.add(delegatedWriter.getFile().getObjectName());
}
}
return new GoogleCloudStorageFileSet(bucket, fileNames);
} | java | @Override
public GoogleCloudStorageFileSet finish(Collection<? extends OutputWriter<ByteBuffer>> writers)
throws IOException {
List<String> fileNames = new ArrayList<>();
for (OutputWriter<ByteBuffer> writer : writers) {
SizeSegmentingGoogleCloudStorageFileWriter segWriter =
(SizeSegmentingGoogleCloudStorageFileWriter) writer;
for (GoogleCloudStorageFileOutputWriter delegatedWriter : segWriter.getDelegatedWriters()) {
fileNames.add(delegatedWriter.getFile().getObjectName());
}
}
return new GoogleCloudStorageFileSet(bucket, fileNames);
} | [
"@",
"Override",
"public",
"GoogleCloudStorageFileSet",
"finish",
"(",
"Collection",
"<",
"?",
"extends",
"OutputWriter",
"<",
"ByteBuffer",
">",
">",
"writers",
")",
"throws",
"IOException",
"{",
"List",
"<",
"String",
">",
"fileNames",
"=",
"new",
"ArrayList",... | Returns a list of all the filenames written by the output writers
@throws IOException | [
"Returns",
"a",
"list",
"of",
"all",
"the",
"filenames",
"written",
"by",
"the",
"output",
"writers"
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/outputs/SizeSegmentedGoogleCloudStorageFileOutput.java#L116-L128 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/BigQueryFieldUtil.java | BigQueryFieldUtil.validateNestedParameterizedType | public static void validateNestedParameterizedType(Type parameterType) {
if (isParameterized(parameterType)
|| GenericArrayType.class.isAssignableFrom(parameterType.getClass())) {
throw new IllegalArgumentException(
"Invalid field. Cannot marshal fields of type Collection<GenericType> or GenericType[].");
}
} | java | public static void validateNestedParameterizedType(Type parameterType) {
if (isParameterized(parameterType)
|| GenericArrayType.class.isAssignableFrom(parameterType.getClass())) {
throw new IllegalArgumentException(
"Invalid field. Cannot marshal fields of type Collection<GenericType> or GenericType[].");
}
} | [
"public",
"static",
"void",
"validateNestedParameterizedType",
"(",
"Type",
"parameterType",
")",
"{",
"if",
"(",
"isParameterized",
"(",
"parameterType",
")",
"||",
"GenericArrayType",
".",
"class",
".",
"isAssignableFrom",
"(",
"parameterType",
".",
"getClass",
"(... | Parameterized types nested more than one level cannot be determined at runtime. So cannot be
marshalled. | [
"Parameterized",
"types",
"nested",
"more",
"than",
"one",
"level",
"cannot",
"be",
"determined",
"at",
"runtime",
".",
"So",
"cannot",
"be",
"marshalled",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/BigQueryFieldUtil.java#L206-L212 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/BigQueryFieldUtil.java | BigQueryFieldUtil.getParameterTypeOfRepeatedField | public static Class<?> getParameterTypeOfRepeatedField(Field field) {
Class<?> componentType = null;
if (isCollection(field.getType())) {
validateCollection(field);
Type parameterType = getParameterType((ParameterizedType) field.getGenericType());
validateNestedParameterizedType(parameterType);
componentType = (Class<?>) parameterType;
} else if (field.getType().isArray()) {
componentType = field.getType().getComponentType();
return componentType;
} else {
throw new IllegalArgumentException("Unsupported repeated type " + field.getType()
+ " Allowed repeated fields are Collection<T> and arrays");
}
validateNestedRepeatedType(componentType, field);
return componentType;
} | java | public static Class<?> getParameterTypeOfRepeatedField(Field field) {
Class<?> componentType = null;
if (isCollection(field.getType())) {
validateCollection(field);
Type parameterType = getParameterType((ParameterizedType) field.getGenericType());
validateNestedParameterizedType(parameterType);
componentType = (Class<?>) parameterType;
} else if (field.getType().isArray()) {
componentType = field.getType().getComponentType();
return componentType;
} else {
throw new IllegalArgumentException("Unsupported repeated type " + field.getType()
+ " Allowed repeated fields are Collection<T> and arrays");
}
validateNestedRepeatedType(componentType, field);
return componentType;
} | [
"public",
"static",
"Class",
"<",
"?",
">",
"getParameterTypeOfRepeatedField",
"(",
"Field",
"field",
")",
"{",
"Class",
"<",
"?",
">",
"componentType",
"=",
"null",
";",
"if",
"(",
"isCollection",
"(",
"field",
".",
"getType",
"(",
")",
")",
")",
"{",
... | Returns type of the parameter or component type for the repeated field depending on whether it
is a collection or an array. | [
"Returns",
"type",
"of",
"the",
"parameter",
"or",
"component",
"type",
"for",
"the",
"repeated",
"field",
"depending",
"on",
"whether",
"it",
"is",
"a",
"collection",
"or",
"an",
"array",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/BigQueryFieldUtil.java#L218-L234 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/BigQueryFieldUtil.java | BigQueryFieldUtil.isFieldRequired | static boolean isFieldRequired(Field field) {
BigQueryDataField bqAnnotation = field.getAnnotation(BigQueryDataField.class);
return (bqAnnotation != null && bqAnnotation.mode().equals(BigQueryFieldMode.REQUIRED))
|| field.getType().isPrimitive();
} | java | static boolean isFieldRequired(Field field) {
BigQueryDataField bqAnnotation = field.getAnnotation(BigQueryDataField.class);
return (bqAnnotation != null && bqAnnotation.mode().equals(BigQueryFieldMode.REQUIRED))
|| field.getType().isPrimitive();
} | [
"static",
"boolean",
"isFieldRequired",
"(",
"Field",
"field",
")",
"{",
"BigQueryDataField",
"bqAnnotation",
"=",
"field",
".",
"getAnnotation",
"(",
"BigQueryDataField",
".",
"class",
")",
";",
"return",
"(",
"bqAnnotation",
"!=",
"null",
"&&",
"bqAnnotation",
... | Returns true if the field is annotated as a required bigquery field. | [
"Returns",
"true",
"if",
"the",
"field",
"is",
"annotated",
"as",
"a",
"required",
"bigquery",
"field",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/BigQueryFieldUtil.java#L248-L253 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/outputs/LevelDbOutputWriter.java | LevelDbOutputWriter.padAndWriteBlock | void padAndWriteBlock(boolean writeEmptyBlockIfFull) throws IOException {
int remaining = writeBuffer.remaining();
if (writeEmptyBlockIfFull || remaining < blockSize) {
writeBlanksToBuffer(remaining);
writeBuffer.flip();
delegate.write(writeBuffer);
writeBuffer.clear();
numBlocksWritten++;
}
} | java | void padAndWriteBlock(boolean writeEmptyBlockIfFull) throws IOException {
int remaining = writeBuffer.remaining();
if (writeEmptyBlockIfFull || remaining < blockSize) {
writeBlanksToBuffer(remaining);
writeBuffer.flip();
delegate.write(writeBuffer);
writeBuffer.clear();
numBlocksWritten++;
}
} | [
"void",
"padAndWriteBlock",
"(",
"boolean",
"writeEmptyBlockIfFull",
")",
"throws",
"IOException",
"{",
"int",
"remaining",
"=",
"writeBuffer",
".",
"remaining",
"(",
")",
";",
"if",
"(",
"writeEmptyBlockIfFull",
"||",
"remaining",
"<",
"blockSize",
")",
"{",
"w... | Adds padding to the stream until to the end of the block.
@throws IOException | [
"Adds",
"padding",
"to",
"the",
"stream",
"until",
"to",
"the",
"end",
"of",
"the",
"block",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/outputs/LevelDbOutputWriter.java#L227-L236 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/pipeline/DeleteFilesJob.java | DeleteFilesJob.run | @Override
public Value<Void> run(List<GcsFilename> files) throws Exception {
for (GcsFilename file : files) {
try {
gcs.delete(file);
} catch (RetriesExhaustedException | IOException e) {
log.log(Level.WARNING, "Failed to cleanup file: " + file, e);
}
}
return null;
} | java | @Override
public Value<Void> run(List<GcsFilename> files) throws Exception {
for (GcsFilename file : files) {
try {
gcs.delete(file);
} catch (RetriesExhaustedException | IOException e) {
log.log(Level.WARNING, "Failed to cleanup file: " + file, e);
}
}
return null;
} | [
"@",
"Override",
"public",
"Value",
"<",
"Void",
">",
"run",
"(",
"List",
"<",
"GcsFilename",
">",
"files",
")",
"throws",
"Exception",
"{",
"for",
"(",
"GcsFilename",
"file",
":",
"files",
")",
"{",
"try",
"{",
"gcs",
".",
"delete",
"(",
"file",
")"... | Deletes the files in the provided GoogleCloudStorageFileSet | [
"Deletes",
"the",
"files",
"in",
"the",
"provided",
"GoogleCloudStorageFileSet"
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/pipeline/DeleteFilesJob.java#L29-L39 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/util/Crc32c.java | Crc32c.update | @Override
public void update(int b) {
long newCrc = crc ^ LONG_MASK;
newCrc = updateByte((byte) b, newCrc);
crc = newCrc ^ LONG_MASK;
} | java | @Override
public void update(int b) {
long newCrc = crc ^ LONG_MASK;
newCrc = updateByte((byte) b, newCrc);
crc = newCrc ^ LONG_MASK;
} | [
"@",
"Override",
"public",
"void",
"update",
"(",
"int",
"b",
")",
"{",
"long",
"newCrc",
"=",
"crc",
"^",
"LONG_MASK",
";",
"newCrc",
"=",
"updateByte",
"(",
"(",
"byte",
")",
"b",
",",
"newCrc",
")",
";",
"crc",
"=",
"newCrc",
"^",
"LONG_MASK",
"... | Updates the checksum with a new byte.
@param b the new byte. | [
"Updates",
"the",
"checksum",
"with",
"a",
"new",
"byte",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/util/Crc32c.java#L92-L97 | train |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/util/Crc32c.java | Crc32c.update | @Override
public void update(byte[] bArray, int off, int len) {
long newCrc = crc ^ LONG_MASK;
for (int i = off; i < off + len; i++) {
newCrc = updateByte(bArray[i], newCrc);
}
crc = newCrc ^ LONG_MASK;
} | java | @Override
public void update(byte[] bArray, int off, int len) {
long newCrc = crc ^ LONG_MASK;
for (int i = off; i < off + len; i++) {
newCrc = updateByte(bArray[i], newCrc);
}
crc = newCrc ^ LONG_MASK;
} | [
"@",
"Override",
"public",
"void",
"update",
"(",
"byte",
"[",
"]",
"bArray",
",",
"int",
"off",
",",
"int",
"len",
")",
"{",
"long",
"newCrc",
"=",
"crc",
"^",
"LONG_MASK",
";",
"for",
"(",
"int",
"i",
"=",
"off",
";",
"i",
"<",
"off",
"+",
"l... | Updates the checksum with an array of bytes.
@param bArray the array of bytes.
@param off the offset into the array where the update should begin.
@param len the length of data to examine. | [
"Updates",
"the",
"checksum",
"with",
"an",
"array",
"of",
"bytes",
"."
] | 2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6 | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/util/Crc32c.java#L105-L112 | train |
opengeospatial/teamengine | teamengine-web/src/main/java/com/occamlab/te/web/XMLUtils.java | XMLUtils.getFirstNode | public static Node getFirstNode(Document doc, String xPathExpression) {
try {
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr;
expr = xpath.compile(xPathExpression);
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
return nl.item(0);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return null;
} | java | public static Node getFirstNode(Document doc, String xPathExpression) {
try {
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr;
expr = xpath.compile(xPathExpression);
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
return nl.item(0);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return null;
} | [
"public",
"static",
"Node",
"getFirstNode",
"(",
"Document",
"doc",
",",
"String",
"xPathExpression",
")",
"{",
"try",
"{",
"XPathFactory",
"xPathfactory",
"=",
"XPathFactory",
".",
"newInstance",
"(",
")",
";",
"XPath",
"xpath",
"=",
"xPathfactory",
".",
"new... | Get first node on a Document doc, give a xpath Expression
@param doc
@param xPathExpression
@return a Node or null if not found | [
"Get",
"first",
"node",
"on",
"a",
"Document",
"doc",
"give",
"a",
"xpath",
"Expression"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-web/src/main/java/com/occamlab/te/web/XMLUtils.java#L29-L44 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/SoapParser.java | SoapParser.isSoapFault | private boolean isSoapFault(Document soapMessage) throws Exception {
Element faultElement = DomUtils.getElementByTagNameNS(soapMessage,
SOAP_12_NAMESPACE, "Fault");
if (faultElement != null) {
return true;
} else {
faultElement = DomUtils.getElementByTagNameNS(soapMessage,
SOAP_11_NAMESPACE, "Fault");
if (faultElement != null) {
return true;
}
}
return false;
} | java | private boolean isSoapFault(Document soapMessage) throws Exception {
Element faultElement = DomUtils.getElementByTagNameNS(soapMessage,
SOAP_12_NAMESPACE, "Fault");
if (faultElement != null) {
return true;
} else {
faultElement = DomUtils.getElementByTagNameNS(soapMessage,
SOAP_11_NAMESPACE, "Fault");
if (faultElement != null) {
return true;
}
}
return false;
} | [
"private",
"boolean",
"isSoapFault",
"(",
"Document",
"soapMessage",
")",
"throws",
"Exception",
"{",
"Element",
"faultElement",
"=",
"DomUtils",
".",
"getElementByTagNameNS",
"(",
"soapMessage",
",",
"SOAP_12_NAMESPACE",
",",
"\"Fault\"",
")",
";",
"if",
"(",
"fa... | A method to check if the message received is a SOAP fault.
@param soapMessage
the SOAP message to check.
@author Simone Gianfranceschi | [
"A",
"method",
"to",
"check",
"if",
"the",
"message",
"received",
"is",
"a",
"SOAP",
"fault",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/SoapParser.java#L227-L241 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/SoapParser.java | SoapParser.parseSoapFault | private Document parseSoapFault(Document soapMessage, PrintWriter logger)
throws Exception {
String namespace = soapMessage.getDocumentElement().getNamespaceURI();
if (namespace.equals(SOAP_12_NAMESPACE)) {
parseSoap12Fault(soapMessage, logger);
} else /* if (namespace.equals(SOAP_11_NAMESPACE)) */{
parseSoap11Fault(soapMessage, logger);
}
return soapMessage;
} | java | private Document parseSoapFault(Document soapMessage, PrintWriter logger)
throws Exception {
String namespace = soapMessage.getDocumentElement().getNamespaceURI();
if (namespace.equals(SOAP_12_NAMESPACE)) {
parseSoap12Fault(soapMessage, logger);
} else /* if (namespace.equals(SOAP_11_NAMESPACE)) */{
parseSoap11Fault(soapMessage, logger);
}
return soapMessage;
} | [
"private",
"Document",
"parseSoapFault",
"(",
"Document",
"soapMessage",
",",
"PrintWriter",
"logger",
")",
"throws",
"Exception",
"{",
"String",
"namespace",
"=",
"soapMessage",
".",
"getDocumentElement",
"(",
")",
".",
"getNamespaceURI",
"(",
")",
";",
"if",
"... | A method to parse a SOAP fault. It checks the namespace and invoke the
correct SOAP 1.1 or 1.2 Fault parser.
@param soapMessage
the SOAP fault message to parse
@param logger
the PrintWriter to log all results to
@return the parsed document otherwise
@author Simone Gianfranceschi | [
"A",
"method",
"to",
"parse",
"a",
"SOAP",
"fault",
".",
"It",
"checks",
"the",
"namespace",
"and",
"invoke",
"the",
"correct",
"SOAP",
"1",
".",
"1",
"or",
"1",
".",
"2",
"Fault",
"parser",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/SoapParser.java#L257-L267 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/SoapParser.java | SoapParser.parseSoap11Fault | private void parseSoap11Fault(Document soapMessage, PrintWriter logger)
throws Exception {
Element envelope = soapMessage.getDocumentElement();
Element element = DomUtils.getElementByTagName(envelope, "faultcode");
if (element == null) {
element = DomUtils.getElementByTagNameNS(envelope,
SOAP_11_NAMESPACE, "faultcode");
}
String faultcode = element.getTextContent();
element = DomUtils.getElementByTagName(envelope, "faultstring");
if (element == null) {
element = DomUtils.getElementByTagNameNS(envelope,
SOAP_11_NAMESPACE, "faultstring");
}
String faultstring = element.getTextContent();
String msg = "SOAP Fault received - [code:" + faultcode
+ "][fault string:" + faultstring + "]";
logger.println(msg);
} | java | private void parseSoap11Fault(Document soapMessage, PrintWriter logger)
throws Exception {
Element envelope = soapMessage.getDocumentElement();
Element element = DomUtils.getElementByTagName(envelope, "faultcode");
if (element == null) {
element = DomUtils.getElementByTagNameNS(envelope,
SOAP_11_NAMESPACE, "faultcode");
}
String faultcode = element.getTextContent();
element = DomUtils.getElementByTagName(envelope, "faultstring");
if (element == null) {
element = DomUtils.getElementByTagNameNS(envelope,
SOAP_11_NAMESPACE, "faultstring");
}
String faultstring = element.getTextContent();
String msg = "SOAP Fault received - [code:" + faultcode
+ "][fault string:" + faultstring + "]";
logger.println(msg);
} | [
"private",
"void",
"parseSoap11Fault",
"(",
"Document",
"soapMessage",
",",
"PrintWriter",
"logger",
")",
"throws",
"Exception",
"{",
"Element",
"envelope",
"=",
"soapMessage",
".",
"getDocumentElement",
"(",
")",
";",
"Element",
"element",
"=",
"DomUtils",
".",
... | A method to parse a SOAP 1.1 fault message.
@param soapMessage
the SOAP 1.1 fault message to parse
@param logger
the PrintWriter to log all results to
@return void
@author Simone Gianfranceschi | [
"A",
"method",
"to",
"parse",
"a",
"SOAP",
"1",
".",
"1",
"fault",
"message",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/SoapParser.java#L282-L303 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/SoapParser.java | SoapParser.parseSoap12Fault | private void parseSoap12Fault(Document soapMessage, PrintWriter logger)
throws Exception {
Element envelope = soapMessage.getDocumentElement();
Element code = DomUtils.getElementByTagNameNS(envelope,
SOAP_12_NAMESPACE, "Code");
String value = DomUtils.getElementByTagNameNS(code, SOAP_12_NAMESPACE,
"Value").getTextContent();
String msg = "SOAP Fault received - [code:" + value + "]";
Element subCode = DomUtils.getElementByTagNameNS(code,
SOAP_12_NAMESPACE, "Subcode");
if (subCode != null) {
value = DomUtils.getElementByTagNameNS(subCode, SOAP_12_NAMESPACE,
"Value").getTextContent();
msg += "[subcode:" + value + "]";
}
Element reason = DomUtils.getElementByTagNameNS(envelope,
SOAP_12_NAMESPACE, "Reason");
Element text = DomUtils.getElementByTagNameNS(reason,
SOAP_12_NAMESPACE, "Text");
if (text != null) {
value = text.getTextContent();
msg += "[reason:" + value + "]";
}
logger.println(msg);
} | java | private void parseSoap12Fault(Document soapMessage, PrintWriter logger)
throws Exception {
Element envelope = soapMessage.getDocumentElement();
Element code = DomUtils.getElementByTagNameNS(envelope,
SOAP_12_NAMESPACE, "Code");
String value = DomUtils.getElementByTagNameNS(code, SOAP_12_NAMESPACE,
"Value").getTextContent();
String msg = "SOAP Fault received - [code:" + value + "]";
Element subCode = DomUtils.getElementByTagNameNS(code,
SOAP_12_NAMESPACE, "Subcode");
if (subCode != null) {
value = DomUtils.getElementByTagNameNS(subCode, SOAP_12_NAMESPACE,
"Value").getTextContent();
msg += "[subcode:" + value + "]";
}
Element reason = DomUtils.getElementByTagNameNS(envelope,
SOAP_12_NAMESPACE, "Reason");
Element text = DomUtils.getElementByTagNameNS(reason,
SOAP_12_NAMESPACE, "Text");
if (text != null) {
value = text.getTextContent();
msg += "[reason:" + value + "]";
}
logger.println(msg);
} | [
"private",
"void",
"parseSoap12Fault",
"(",
"Document",
"soapMessage",
",",
"PrintWriter",
"logger",
")",
"throws",
"Exception",
"{",
"Element",
"envelope",
"=",
"soapMessage",
".",
"getDocumentElement",
"(",
")",
";",
"Element",
"code",
"=",
"DomUtils",
".",
"g... | A method to parse a SOAP 1.2 fault message.
@param soapMessage
the SOAP 1.2 fault message to parse
@param logger
the PrintWriter to log all results to
@return void
@author Simone Gianfranceschi | [
"A",
"method",
"to",
"parse",
"a",
"SOAP",
"1",
".",
"2",
"fault",
"message",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/SoapParser.java#L318-L343 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/Generator.java | Generator.createEncodedName | public static String createEncodedName(File source) {
String fileURI = source.toURI().toString();
String userDirURI = new File(System.getProperty("user.dir")).toURI()
.toString();
fileURI = fileURI.replace(userDirURI, "");
String encodedName = fileURI.substring(fileURI.lastIndexOf(':') + 1)
.replace("%20", "-").replace('/', '_');
return encodedName;
} | java | public static String createEncodedName(File source) {
String fileURI = source.toURI().toString();
String userDirURI = new File(System.getProperty("user.dir")).toURI()
.toString();
fileURI = fileURI.replace(userDirURI, "");
String encodedName = fileURI.substring(fileURI.lastIndexOf(':') + 1)
.replace("%20", "-").replace('/', '_');
return encodedName;
} | [
"public",
"static",
"String",
"createEncodedName",
"(",
"File",
"source",
")",
"{",
"String",
"fileURI",
"=",
"source",
".",
"toURI",
"(",
")",
".",
"toString",
"(",
")",
";",
"String",
"userDirURI",
"=",
"new",
"File",
"(",
"System",
".",
"getProperty",
... | Creates a directory name from a file path.
@param source
A File reference.
@return A String representing a legal directory name. | [
"Creates",
"a",
"directory",
"name",
"from",
"a",
"file",
"path",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/Generator.java#L248-L256 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/SoapUtils.java | SoapUtils.getSOAPMessage | public static Document getSOAPMessage(InputStream in) throws Exception {
/*
* ByteArrayOutputStream out = new ByteArrayOutputStream(); int b; while
* ((b = in.read()) != -1) { out.write(b); }
*
* System.out.println("OUT:" + out.toString());
*/
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
// Fortify Mod: Disable entity expansion to foil External Entity Injections
dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document soapMessage = db.newDocument();
// Fortify Mod: prevent external entity injection
TransformerFactory tf = TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer t = tf.newTransformer();
// End Fortify Mod
t.transform(new StreamSource(in), new DOMResult(soapMessage));
return soapMessage;
} | java | public static Document getSOAPMessage(InputStream in) throws Exception {
/*
* ByteArrayOutputStream out = new ByteArrayOutputStream(); int b; while
* ((b = in.read()) != -1) { out.write(b); }
*
* System.out.println("OUT:" + out.toString());
*/
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
// Fortify Mod: Disable entity expansion to foil External Entity Injections
dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document soapMessage = db.newDocument();
// Fortify Mod: prevent external entity injection
TransformerFactory tf = TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer t = tf.newTransformer();
// End Fortify Mod
t.transform(new StreamSource(in), new DOMResult(soapMessage));
return soapMessage;
} | [
"public",
"static",
"Document",
"getSOAPMessage",
"(",
"InputStream",
"in",
")",
"throws",
"Exception",
"{",
"/*\r\n * ByteArrayOutputStream out = new ByteArrayOutputStream(); int b; while\r\n * ((b = in.read()) != -1) { out.write(b); }\r\n * \r\n * System.out.p... | A method to get the SOAP message from the input stream.
@param in
the input stream to be used to get the SOAP message.
@return the SOAP message
@author Simone Gianfranceschi | [
"A",
"method",
"to",
"get",
"the",
"SOAP",
"message",
"from",
"the",
"input",
"stream",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/SoapUtils.java#L55-L75 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/SoapUtils.java | SoapUtils.getSoapBody | public static Document getSoapBody(Document soapMessage) throws Exception {
Element envelope = soapMessage.getDocumentElement();
Element body = DomUtils.getChildElement(DomUtils.getElementByTagName(
envelope, envelope.getPrefix() + ":Body"));
Document content = DomUtils.createDocument(body);
Element documentRoot = content.getDocumentElement();
addNSdeclarations(envelope, documentRoot);
addNSdeclarations(body, documentRoot);
return content;
} | java | public static Document getSoapBody(Document soapMessage) throws Exception {
Element envelope = soapMessage.getDocumentElement();
Element body = DomUtils.getChildElement(DomUtils.getElementByTagName(
envelope, envelope.getPrefix() + ":Body"));
Document content = DomUtils.createDocument(body);
Element documentRoot = content.getDocumentElement();
addNSdeclarations(envelope, documentRoot);
addNSdeclarations(body, documentRoot);
return content;
} | [
"public",
"static",
"Document",
"getSoapBody",
"(",
"Document",
"soapMessage",
")",
"throws",
"Exception",
"{",
"Element",
"envelope",
"=",
"soapMessage",
".",
"getDocumentElement",
"(",
")",
";",
"Element",
"body",
"=",
"DomUtils",
".",
"getChildElement",
"(",
... | A method to extract the content of the SOAP body.
@param soapMessage
the SOAP message.
@return the content of the body of the input SOAP message.
@author Simone Gianfranceschi | [
"A",
"method",
"to",
"extract",
"the",
"content",
"of",
"the",
"SOAP",
"body",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/SoapUtils.java#L87-L97 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/SoapUtils.java | SoapUtils.addNSdeclarations | public static void addNSdeclarations(Element source, Element target)
throws Exception {
NamedNodeMap sourceAttributes = source.getAttributes();
Attr attribute;
String attributeName;
for (int i = 0; i <= sourceAttributes.getLength() - 1; i++) {
attribute = (Attr) sourceAttributes.item(i);
attributeName = attribute.getName();
if (attributeName.startsWith("xmlns")
&& !attributeName.startsWith("xmlns:soap-env")) {
// System.out.println("XMLNS:" +
// attributeName+":"+attribute.getValue());
target.setAttribute(attributeName, attribute.getValue());
}
}
} | java | public static void addNSdeclarations(Element source, Element target)
throws Exception {
NamedNodeMap sourceAttributes = source.getAttributes();
Attr attribute;
String attributeName;
for (int i = 0; i <= sourceAttributes.getLength() - 1; i++) {
attribute = (Attr) sourceAttributes.item(i);
attributeName = attribute.getName();
if (attributeName.startsWith("xmlns")
&& !attributeName.startsWith("xmlns:soap-env")) {
// System.out.println("XMLNS:" +
// attributeName+":"+attribute.getValue());
target.setAttribute(attributeName, attribute.getValue());
}
}
} | [
"public",
"static",
"void",
"addNSdeclarations",
"(",
"Element",
"source",
",",
"Element",
"target",
")",
"throws",
"Exception",
"{",
"NamedNodeMap",
"sourceAttributes",
"=",
"source",
".",
"getAttributes",
"(",
")",
";",
"Attr",
"attribute",
";",
"String",
"att... | A method to copy namespaces declarations.
@param source
the source message containing the namespaces to be copied on
the target message.
@param target
the target message.
@author Simone Gianfranceschi | [
"A",
"method",
"to",
"copy",
"namespaces",
"declarations",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/SoapUtils.java#L110-L125 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/SoapUtils.java | SoapUtils.getSoapMessageAsByte | public static byte[] getSoapMessageAsByte(String version,
List headerBlocks, Element body, String encoding) throws Exception {
Document message = createSoapMessage(version, headerBlocks, body);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TransformerFactory tf = TransformerFactory.newInstance();
// Fortify Mod: prevent external entity injection
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer t = tf.newTransformer();
// End Fortify Mod
t.setOutputProperty(OutputKeys.ENCODING, encoding);
t.transform(new DOMSource(message), new StreamResult(baos));
// System.out.println("SOAP MESSAGE : " + baos.toString());
return baos.toByteArray();
} | java | public static byte[] getSoapMessageAsByte(String version,
List headerBlocks, Element body, String encoding) throws Exception {
Document message = createSoapMessage(version, headerBlocks, body);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TransformerFactory tf = TransformerFactory.newInstance();
// Fortify Mod: prevent external entity injection
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer t = tf.newTransformer();
// End Fortify Mod
t.setOutputProperty(OutputKeys.ENCODING, encoding);
t.transform(new DOMSource(message), new StreamResult(baos));
// System.out.println("SOAP MESSAGE : " + baos.toString());
return baos.toByteArray();
} | [
"public",
"static",
"byte",
"[",
"]",
"getSoapMessageAsByte",
"(",
"String",
"version",
",",
"List",
"headerBlocks",
",",
"Element",
"body",
",",
"String",
"encoding",
")",
"throws",
"Exception",
"{",
"Document",
"message",
"=",
"createSoapMessage",
"(",
"versio... | A method to create a SOAP message and retrieve it as byte.
@param version
the SOAP version to be used (1.1 or 1.2).
@param headerBlocks
the list of Header Blocks to be included in the SOAP Header .
@param body
the XML message to be included in the SOAP BODY element.
@param encoding
the encoding to be used for the message creation.
@return The created SOAP message as byte.
@author Simone Gianfranceschi | [
"A",
"method",
"to",
"create",
"a",
"SOAP",
"message",
"and",
"retrieve",
"it",
"as",
"byte",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/SoapUtils.java#L143-L159 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/SoapUtils.java | SoapUtils.createSoapMessage | public static Document createSoapMessage(String version, List headerBlocks,
Element body) throws Exception {
Document message = null;
NodeList children = body.getChildNodes();
// Loop in order to remove dummy nodes (spaces, CR)
for (int i = 0; i < children.getLength(); i++) {
if (children.item(i).getNodeType() != Node.ELEMENT_NODE && children.item(i).getNodeType() == Node.TEXT_NODE) {
Document bodyDoc = DomUtils.convertToElementNode(body.getTextContent().trim());
if(bodyDoc.getFirstChild().getNodeType() == Node.ELEMENT_NODE){
body = (Element) bodyDoc.getFirstChild();
}
}
if (version.equals(SOAP_V_1_1)) {
message = Soap11MessageBuilder.getSoapMessage(headerBlocks,
body);
} else {
message = Soap12MessageBuilder.getSoapMessage(headerBlocks,
body);
}
break;
}
return message;
} | java | public static Document createSoapMessage(String version, List headerBlocks,
Element body) throws Exception {
Document message = null;
NodeList children = body.getChildNodes();
// Loop in order to remove dummy nodes (spaces, CR)
for (int i = 0; i < children.getLength(); i++) {
if (children.item(i).getNodeType() != Node.ELEMENT_NODE && children.item(i).getNodeType() == Node.TEXT_NODE) {
Document bodyDoc = DomUtils.convertToElementNode(body.getTextContent().trim());
if(bodyDoc.getFirstChild().getNodeType() == Node.ELEMENT_NODE){
body = (Element) bodyDoc.getFirstChild();
}
}
if (version.equals(SOAP_V_1_1)) {
message = Soap11MessageBuilder.getSoapMessage(headerBlocks,
body);
} else {
message = Soap12MessageBuilder.getSoapMessage(headerBlocks,
body);
}
break;
}
return message;
} | [
"public",
"static",
"Document",
"createSoapMessage",
"(",
"String",
"version",
",",
"List",
"headerBlocks",
",",
"Element",
"body",
")",
"throws",
"Exception",
"{",
"Document",
"message",
"=",
"null",
";",
"NodeList",
"children",
"=",
"body",
".",
"getChildNodes... | A method to create a SOAP message. The SOAP message, including the Header
is created and returned as DOM Document.
@param version
the SOAP version to be used (1.1 or 1.2).
@param headerBlocks
the list of Header Blocks to be included in the SOAP Header .
@param body
the XML message to be included in the SOAP BODY element.
@return The created SOAP message as document.
@author Simone Gianfranceschi | [
"A",
"method",
"to",
"create",
"a",
"SOAP",
"message",
".",
"The",
"SOAP",
"message",
"including",
"the",
"Header",
"is",
"created",
"and",
"returned",
"as",
"DOM",
"Document",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/SoapUtils.java#L176-L198 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/StringUtils.java | StringUtils.getFilenameFromString | public static String getFilenameFromString(String filePath) {
String newPath = filePath;
int forwardInd = filePath.lastIndexOf("/");
int backInd = filePath.lastIndexOf("\\");
if (forwardInd > backInd) {
newPath = filePath.substring(forwardInd + 1);
} else {
newPath = filePath.substring(backInd + 1);
}
// still original if no occurance of "/" or "\"
return newPath;
} | java | public static String getFilenameFromString(String filePath) {
String newPath = filePath;
int forwardInd = filePath.lastIndexOf("/");
int backInd = filePath.lastIndexOf("\\");
if (forwardInd > backInd) {
newPath = filePath.substring(forwardInd + 1);
} else {
newPath = filePath.substring(backInd + 1);
}
// still original if no occurance of "/" or "\"
return newPath;
} | [
"public",
"static",
"String",
"getFilenameFromString",
"(",
"String",
"filePath",
")",
"{",
"String",
"newPath",
"=",
"filePath",
";",
"int",
"forwardInd",
"=",
"filePath",
".",
"lastIndexOf",
"(",
"\"/\"",
")",
";",
"int",
"backInd",
"=",
"filePath",
".",
"... | Extracts the filename from a path.
@param filePath
the string to parse
@return the path containing only the filename itself | [
"Extracts",
"the",
"filename",
"from",
"a",
"path",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/StringUtils.java#L43-L57 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/StringUtils.java | StringUtils.replaceAll | public static String replaceAll(String str, String match, String replacement) {
String newStr = str;
int i = newStr.indexOf(match);
while (i >= 0) {
newStr = newStr.substring(0, i) + replacement
+ newStr.substring(i + match.length());
i = newStr.indexOf(match);
}
return newStr;
} | java | public static String replaceAll(String str, String match, String replacement) {
String newStr = str;
int i = newStr.indexOf(match);
while (i >= 0) {
newStr = newStr.substring(0, i) + replacement
+ newStr.substring(i + match.length());
i = newStr.indexOf(match);
}
return newStr;
} | [
"public",
"static",
"String",
"replaceAll",
"(",
"String",
"str",
",",
"String",
"match",
",",
"String",
"replacement",
")",
"{",
"String",
"newStr",
"=",
"str",
";",
"int",
"i",
"=",
"newStr",
".",
"indexOf",
"(",
"match",
")",
";",
"while",
"(",
"i",... | Replaces all occurences of match in str with replacement | [
"Replaces",
"all",
"occurences",
"of",
"match",
"in",
"str",
"with",
"replacement"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/StringUtils.java#L60-L69 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/ZipParser.java | ZipParser.getMediaType | public static String getMediaType(String ext) {
String mediaType = "";
// Find the media type value in the lookup table
for (int i = 0; i < ApplicationMediaTypeMappings.length; i++) {
if (ApplicationMediaTypeMappings[i][0].equals(ext.toLowerCase())) {
mediaType = ApplicationMediaTypeMappings[i][1];
}
}
// Give the media type default of "application/octet-stream"
if (mediaType.equals("")) {
mediaType = "application/octet-stream";
}
return mediaType;
} | java | public static String getMediaType(String ext) {
String mediaType = "";
// Find the media type value in the lookup table
for (int i = 0; i < ApplicationMediaTypeMappings.length; i++) {
if (ApplicationMediaTypeMappings[i][0].equals(ext.toLowerCase())) {
mediaType = ApplicationMediaTypeMappings[i][1];
}
}
// Give the media type default of "application/octet-stream"
if (mediaType.equals("")) {
mediaType = "application/octet-stream";
}
return mediaType;
} | [
"public",
"static",
"String",
"getMediaType",
"(",
"String",
"ext",
")",
"{",
"String",
"mediaType",
"=",
"\"\"",
";",
"// Find the media type value in the lookup table\r",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"ApplicationMediaTypeMappings",
".",
"leng... | Returns the mime media type value for the given extension
@param ext
the filename extension to lookup
@return String the mime type for the given extension | [
"Returns",
"the",
"mime",
"media",
"type",
"value",
"for",
"the",
"given",
"extension"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/ZipParser.java#L71-L87 | train |
opengeospatial/teamengine | teamengine-web/src/main/java/com/occamlab/te/web/MonitorServlet.java | MonitorServlet.createMonitor | static public String createMonitor(String monitorUrl, TECore core) {
return createMonitor(monitorUrl, null, "", core);
} | java | static public String createMonitor(String monitorUrl, TECore core) {
return createMonitor(monitorUrl, null, "", core);
} | [
"static",
"public",
"String",
"createMonitor",
"(",
"String",
"monitorUrl",
",",
"TECore",
"core",
")",
"{",
"return",
"createMonitor",
"(",
"monitorUrl",
",",
"null",
",",
"\"\"",
",",
"core",
")",
";",
"}"
] | Monitor without parser that doesn't trigger a test | [
"Monitor",
"without",
"parser",
"that",
"doesn",
"t",
"trigger",
"a",
"test"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-web/src/main/java/com/occamlab/te/web/MonitorServlet.java#L85-L87 | train |
opengeospatial/teamengine | teamengine-web/src/main/java/com/occamlab/te/web/MonitorServlet.java | MonitorServlet.createMonitor | static public String createMonitor(String monitorUrl,
Node parserInstruction, String modifiesResponse, TECore core) {
MonitorCall mc = monitors.get(monitorUrl);
mc.setCore(core);
if (parserInstruction != null) {
mc.setParserInstruction(DomUtils.getElement(parserInstruction));
mc.setModifiesResponse(Boolean.parseBoolean(modifiesResponse));
}
LOGR.log(Level.CONFIG, "Configured monitor without test:\n {0}", mc);
return "";
} | java | static public String createMonitor(String monitorUrl,
Node parserInstruction, String modifiesResponse, TECore core) {
MonitorCall mc = monitors.get(monitorUrl);
mc.setCore(core);
if (parserInstruction != null) {
mc.setParserInstruction(DomUtils.getElement(parserInstruction));
mc.setModifiesResponse(Boolean.parseBoolean(modifiesResponse));
}
LOGR.log(Level.CONFIG, "Configured monitor without test:\n {0}", mc);
return "";
} | [
"static",
"public",
"String",
"createMonitor",
"(",
"String",
"monitorUrl",
",",
"Node",
"parserInstruction",
",",
"String",
"modifiesResponse",
",",
"TECore",
"core",
")",
"{",
"MonitorCall",
"mc",
"=",
"monitors",
".",
"get",
"(",
"monitorUrl",
")",
";",
"mc... | Monitor that doesn't trigger a test | [
"Monitor",
"that",
"doesn",
"t",
"trigger",
"a",
"test"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-web/src/main/java/com/occamlab/te/web/MonitorServlet.java#L90-L100 | train |
opengeospatial/teamengine | teamengine-web/src/main/java/com/occamlab/te/web/MonitorServlet.java | MonitorServlet.createMonitor | static public String createMonitor(XPathContext context, String url,
String localName, String namespaceURI, NodeInfo params,
String callId, TECore core) throws Exception {
return createMonitor(context, url, localName, namespaceURI, params,
null, "", callId, core);
} | java | static public String createMonitor(XPathContext context, String url,
String localName, String namespaceURI, NodeInfo params,
String callId, TECore core) throws Exception {
return createMonitor(context, url, localName, namespaceURI, params,
null, "", callId, core);
} | [
"static",
"public",
"String",
"createMonitor",
"(",
"XPathContext",
"context",
",",
"String",
"url",
",",
"String",
"localName",
",",
"String",
"namespaceURI",
",",
"NodeInfo",
"params",
",",
"String",
"callId",
",",
"TECore",
"core",
")",
"throws",
"Exception",... | Monitor without parser that triggers a test | [
"Monitor",
"without",
"parser",
"that",
"triggers",
"a",
"test"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-web/src/main/java/com/occamlab/te/web/MonitorServlet.java#L103-L108 | train |
opengeospatial/teamengine | teamengine-web/src/main/java/com/occamlab/te/web/MonitorServlet.java | MonitorServlet.createMonitor | static public String createMonitor(XPathContext context, String monitorUrl,
String localName, String namespaceURI, NodeInfo params,
NodeInfo parserInstruction, String modifiesResponse, String callId,
TECore core) throws Exception {
MonitorCall mc = monitors.get(monitorUrl);
mc.setContext(context);
mc.setLocalName(localName);
mc.setNamespaceURI(namespaceURI);
mc.setCore(core);
if (params != null) {
Node node = (Node) NodeOverNodeInfo.wrap(params);
if (node.getNodeType() == Node.DOCUMENT_NODE) {
mc.setParams(((Document) node).getDocumentElement());
} else {
mc.setParams((Element) node);
}
}
if (parserInstruction != null) {
Node node = (Node) NodeOverNodeInfo.wrap(parserInstruction);
if (node.getNodeType() == Node.DOCUMENT_NODE) {
mc.setParserInstruction(((Document) node).getDocumentElement());
} else {
mc.setParserInstruction((Element) node);
}
mc.setModifiesResponse(Boolean.parseBoolean(modifiesResponse));
}
mc.setCallId(callId);
LOGR.log(Level.CONFIG, "Configured monitor with test:\n {0}", mc);
return "";
} | java | static public String createMonitor(XPathContext context, String monitorUrl,
String localName, String namespaceURI, NodeInfo params,
NodeInfo parserInstruction, String modifiesResponse, String callId,
TECore core) throws Exception {
MonitorCall mc = monitors.get(monitorUrl);
mc.setContext(context);
mc.setLocalName(localName);
mc.setNamespaceURI(namespaceURI);
mc.setCore(core);
if (params != null) {
Node node = (Node) NodeOverNodeInfo.wrap(params);
if (node.getNodeType() == Node.DOCUMENT_NODE) {
mc.setParams(((Document) node).getDocumentElement());
} else {
mc.setParams((Element) node);
}
}
if (parserInstruction != null) {
Node node = (Node) NodeOverNodeInfo.wrap(parserInstruction);
if (node.getNodeType() == Node.DOCUMENT_NODE) {
mc.setParserInstruction(((Document) node).getDocumentElement());
} else {
mc.setParserInstruction((Element) node);
}
mc.setModifiesResponse(Boolean.parseBoolean(modifiesResponse));
}
mc.setCallId(callId);
LOGR.log(Level.CONFIG, "Configured monitor with test:\n {0}", mc);
return "";
} | [
"static",
"public",
"String",
"createMonitor",
"(",
"XPathContext",
"context",
",",
"String",
"monitorUrl",
",",
"String",
"localName",
",",
"String",
"namespaceURI",
",",
"NodeInfo",
"params",
",",
"NodeInfo",
"parserInstruction",
",",
"String",
"modifiesResponse",
... | Monitor that triggers a test | [
"Monitor",
"that",
"triggers",
"a",
"test"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-web/src/main/java/com/occamlab/te/web/MonitorServlet.java#L111-L140 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/html/EarlToHtmlTransformation.java | EarlToHtmlTransformation.earlHtmlReport | public void earlHtmlReport( String outputDir ) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
String resourceDir = cl.getResource( "com/occamlab/te/earl/lib" ).getPath();
String earlXsl = cl.getResource( "com/occamlab/te/earl_html_report.xsl" ).toString();
File htmlOutput = new File( outputDir, "result" );
htmlOutput.mkdir();
File earlResult = findEarlResultFile( outputDir );
LOGR.log( FINE, "Try to transform earl result file '" + earlResult + "' to directory " + htmlOutput );
try {
if ( earlResult != null && earlResult.exists() ) {
Transformer transformer = TransformerFactory.newInstance().newTransformer( new StreamSource( earlXsl ) );
transformer.setParameter( "outputDir", htmlOutput );
File indexHtml = new File( htmlOutput, "index.html" );
indexHtml.createNewFile();
// Fortify Mod: Make sure the FileOutputStream is closed when we are done with it.
// transformer.transform( new StreamSource( earlResult ),
// new StreamResult( new FileOutputStream( indexHtml ) ) );
FileOutputStream fo = new FileOutputStream( indexHtml );
transformer.transform( new StreamSource( earlResult ), new StreamResult( fo ) );
fo.close();
FileUtils.copyDirectory( new File( resourceDir ), htmlOutput );
}
} catch ( Exception e ) {
LOGR.log( SEVERE, "Transformation of EARL to HTML failed.", e );
}
} | java | public void earlHtmlReport( String outputDir ) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
String resourceDir = cl.getResource( "com/occamlab/te/earl/lib" ).getPath();
String earlXsl = cl.getResource( "com/occamlab/te/earl_html_report.xsl" ).toString();
File htmlOutput = new File( outputDir, "result" );
htmlOutput.mkdir();
File earlResult = findEarlResultFile( outputDir );
LOGR.log( FINE, "Try to transform earl result file '" + earlResult + "' to directory " + htmlOutput );
try {
if ( earlResult != null && earlResult.exists() ) {
Transformer transformer = TransformerFactory.newInstance().newTransformer( new StreamSource( earlXsl ) );
transformer.setParameter( "outputDir", htmlOutput );
File indexHtml = new File( htmlOutput, "index.html" );
indexHtml.createNewFile();
// Fortify Mod: Make sure the FileOutputStream is closed when we are done with it.
// transformer.transform( new StreamSource( earlResult ),
// new StreamResult( new FileOutputStream( indexHtml ) ) );
FileOutputStream fo = new FileOutputStream( indexHtml );
transformer.transform( new StreamSource( earlResult ), new StreamResult( fo ) );
fo.close();
FileUtils.copyDirectory( new File( resourceDir ), htmlOutput );
}
} catch ( Exception e ) {
LOGR.log( SEVERE, "Transformation of EARL to HTML failed.", e );
}
} | [
"public",
"void",
"earlHtmlReport",
"(",
"String",
"outputDir",
")",
"{",
"ClassLoader",
"cl",
"=",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getContextClassLoader",
"(",
")",
";",
"String",
"resourceDir",
"=",
"cl",
".",
"getResource",
"(",
"\"com/occam... | Transform EARL result into HTML report using XSLT.
@param outputDir | [
"Transform",
"EARL",
"result",
"into",
"HTML",
"report",
"using",
"XSLT",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/html/EarlToHtmlTransformation.java#L29-L57 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/SetupOptions.java | SetupOptions.recordingInfo | public static boolean recordingInfo(String testName) throws ParserConfigurationException, SAXException, IOException {
TECore.rootTestName.clear();
String path = getBaseConfigDirectory() + "/config.xml";
if (new File(path).exists()) {
// Fortify Mod: prevent external entity injection
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder();
//DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(path);
NodeList nodeListForStandardTag = doc.getElementsByTagName("standard");
if (null!=nodeListForStandardTag && nodeListForStandardTag.getLength() > 0) {
for (int i = 0; i < nodeListForStandardTag.getLength(); i++) {
Element elementStandard = (Element) nodeListForStandardTag.item(i);
if (testName.equals(elementStandard.getElementsByTagName("local-name").item(0).getTextContent())) {
if (null!=elementStandard.getElementsByTagName("record").item(0)) {
System.setProperty("Record", "True");
NodeList rootTestNameArray=elementStandard.getElementsByTagName("test-name");
if (null!=rootTestNameArray && rootTestNameArray.getLength() > 0) {
for (int counter = 0; counter < rootTestNameArray.getLength(); counter++) {
Element rootTestName = (Element) rootTestNameArray.item(counter);
TECore.rootTestName.add(rootTestName.getTextContent());
}
}
return true;
}
}
}
}
}
System.setProperty("Record", "False");
return false;
} | java | public static boolean recordingInfo(String testName) throws ParserConfigurationException, SAXException, IOException {
TECore.rootTestName.clear();
String path = getBaseConfigDirectory() + "/config.xml";
if (new File(path).exists()) {
// Fortify Mod: prevent external entity injection
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder();
//DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(path);
NodeList nodeListForStandardTag = doc.getElementsByTagName("standard");
if (null!=nodeListForStandardTag && nodeListForStandardTag.getLength() > 0) {
for (int i = 0; i < nodeListForStandardTag.getLength(); i++) {
Element elementStandard = (Element) nodeListForStandardTag.item(i);
if (testName.equals(elementStandard.getElementsByTagName("local-name").item(0).getTextContent())) {
if (null!=elementStandard.getElementsByTagName("record").item(0)) {
System.setProperty("Record", "True");
NodeList rootTestNameArray=elementStandard.getElementsByTagName("test-name");
if (null!=rootTestNameArray && rootTestNameArray.getLength() > 0) {
for (int counter = 0; counter < rootTestNameArray.getLength(); counter++) {
Element rootTestName = (Element) rootTestNameArray.item(counter);
TECore.rootTestName.add(rootTestName.getTextContent());
}
}
return true;
}
}
}
}
}
System.setProperty("Record", "False");
return false;
} | [
"public",
"static",
"boolean",
"recordingInfo",
"(",
"String",
"testName",
")",
"throws",
"ParserConfigurationException",
",",
"SAXException",
",",
"IOException",
"{",
"TECore",
".",
"rootTestName",
".",
"clear",
"(",
")",
";",
"String",
"path",
"=",
"getBaseConfi... | Determine the test recording is on or off.
@param testName
@return
@throws javax.xml.parsers.ParserConfigurationException
@throws org.xml.sax.SAXException
@throws java.io.IOException | [
"Determine",
"the",
"test",
"recording",
"is",
"on",
"or",
"off",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/SetupOptions.java#L105-L138 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/IOUtils.java | IOUtils.DocumentToInputStream | public static InputStream DocumentToInputStream(Document edoc)
throws IOException {
// Create the input and output for use in the transformation
final org.w3c.dom.Document doc = edoc;
final PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream();
pis.connect(pos);
(new Thread(new Runnable() {
public void run() {
// Use the Transformer.transform() method to save the Document
// to a StreamResult
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
// Fortify Mod: prevent external entity injection
tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty("encoding", "UTF-8");
transformer.setOutputProperty("indent", "yes");
transformer.transform(new DOMSource(doc), new StreamResult(
pos));
} catch (Exception e) {
throw new RuntimeException(
"Error converting Document to InputStream. "
+ e.getMessage());
} finally {
try {
pos.close();
} catch (IOException e) {
}
}
}
}, "IOUtils.DocumentToInputStream(Document edoc)")).start();
return pis;
} | java | public static InputStream DocumentToInputStream(Document edoc)
throws IOException {
// Create the input and output for use in the transformation
final org.w3c.dom.Document doc = edoc;
final PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream();
pis.connect(pos);
(new Thread(new Runnable() {
public void run() {
// Use the Transformer.transform() method to save the Document
// to a StreamResult
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
// Fortify Mod: prevent external entity injection
tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty("encoding", "UTF-8");
transformer.setOutputProperty("indent", "yes");
transformer.transform(new DOMSource(doc), new StreamResult(
pos));
} catch (Exception e) {
throw new RuntimeException(
"Error converting Document to InputStream. "
+ e.getMessage());
} finally {
try {
pos.close();
} catch (IOException e) {
}
}
}
}, "IOUtils.DocumentToInputStream(Document edoc)")).start();
return pis;
} | [
"public",
"static",
"InputStream",
"DocumentToInputStream",
"(",
"Document",
"edoc",
")",
"throws",
"IOException",
"{",
"// Create the input and output for use in the transformation\r",
"final",
"org",
".",
"w3c",
".",
"dom",
".",
"Document",
"doc",
"=",
"edoc",
";",
... | Converts an org.w3c.dom.Document element to an java.io.InputStream.
@param edoc
the org.w3c.dom.Document to be converted
@return InputStream the InputStream value of the passed doument | [
"Converts",
"an",
"org",
".",
"w3c",
".",
"dom",
".",
"Document",
"element",
"to",
"an",
"java",
".",
"io",
".",
"InputStream",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/IOUtils.java#L51-L89 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/IOUtils.java | IOUtils.inputStreamToString | public static String inputStreamToString(InputStream in) {
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(in,
"UTF-8"), 1024);
String line;
while ((line = br.readLine()) != null) {
buffer.append(line);
}
} catch (IOException iox) {
LOGR.warning(iox.getMessage());
}
return buffer.toString();
} | java | public static String inputStreamToString(InputStream in) {
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(in,
"UTF-8"), 1024);
String line;
while ((line = br.readLine()) != null) {
buffer.append(line);
}
} catch (IOException iox) {
LOGR.warning(iox.getMessage());
}
return buffer.toString();
} | [
"public",
"static",
"String",
"inputStreamToString",
"(",
"InputStream",
"in",
")",
"{",
"StringBuffer",
"buffer",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"try",
"{",
"BufferedReader",
"br",
"=",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
... | Reads the content of an input stream into a String value using the UTF-8
charset.
@param in
The InputStream from which the content is read.
@return A String representing the content of the input stream; an empty
string is returned if an error occurs. | [
"Reads",
"the",
"content",
"of",
"an",
"input",
"stream",
"into",
"a",
"String",
"value",
"using",
"the",
"UTF",
"-",
"8",
"charset",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/IOUtils.java#L100-L113 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/IOUtils.java | IOUtils.writeObjectToFile | public static boolean writeObjectToFile(Object obj, File f) {
try {
FileOutputStream fout = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(obj);
oos.close();
} catch (Exception e) {
System.out.println("Error writing Object to file: "
+ e.getMessage());
return false;
}
return true;
} | java | public static boolean writeObjectToFile(Object obj, File f) {
try {
FileOutputStream fout = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(obj);
oos.close();
} catch (Exception e) {
System.out.println("Error writing Object to file: "
+ e.getMessage());
return false;
}
return true;
} | [
"public",
"static",
"boolean",
"writeObjectToFile",
"(",
"Object",
"obj",
",",
"File",
"f",
")",
"{",
"try",
"{",
"FileOutputStream",
"fout",
"=",
"new",
"FileOutputStream",
"(",
"f",
")",
";",
"ObjectOutputStream",
"oos",
"=",
"new",
"ObjectOutputStream",
"("... | Writes a generic object to a file | [
"Writes",
"a",
"generic",
"object",
"to",
"a",
"file"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/IOUtils.java#L137-L149 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/IOUtils.java | IOUtils.readObjectFromFile | public static Object readObjectFromFile(File f) {
Object obj = null;
try {
FileInputStream fin = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fin);
obj = ois.readObject();
ois.close();
} catch (Exception e) {
System.out.println("Error reading Object from file: "
+ e.getMessage());
return null;
}
return obj;
} | java | public static Object readObjectFromFile(File f) {
Object obj = null;
try {
FileInputStream fin = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fin);
obj = ois.readObject();
ois.close();
} catch (Exception e) {
System.out.println("Error reading Object from file: "
+ e.getMessage());
return null;
}
return obj;
} | [
"public",
"static",
"Object",
"readObjectFromFile",
"(",
"File",
"f",
")",
"{",
"Object",
"obj",
"=",
"null",
";",
"try",
"{",
"FileInputStream",
"fin",
"=",
"new",
"FileInputStream",
"(",
"f",
")",
";",
"ObjectInputStream",
"ois",
"=",
"new",
"ObjectInputSt... | Reads in a file that contains only an object | [
"Reads",
"in",
"a",
"file",
"that",
"contains",
"only",
"an",
"object"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/IOUtils.java#L170-L183 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/Engine.java | Engine.preload | public void preload(Index index, String sourcesName) throws Exception {
for (String key : index.getTestKeys()) {
TestEntry te = index.getTest(key);
loadExecutable(te, sourcesName);
}
for (String key : index.getFunctionKeys()) {
List<FunctionEntry> functions = index.getFunctions(key);
for (FunctionEntry fe : functions) {
if (!fe.isJava()) {
loadExecutable(fe, sourcesName);
}
}
}
} | java | public void preload(Index index, String sourcesName) throws Exception {
for (String key : index.getTestKeys()) {
TestEntry te = index.getTest(key);
loadExecutable(te, sourcesName);
}
for (String key : index.getFunctionKeys()) {
List<FunctionEntry> functions = index.getFunctions(key);
for (FunctionEntry fe : functions) {
if (!fe.isJava()) {
loadExecutable(fe, sourcesName);
}
}
}
} | [
"public",
"void",
"preload",
"(",
"Index",
"index",
",",
"String",
"sourcesName",
")",
"throws",
"Exception",
"{",
"for",
"(",
"String",
"key",
":",
"index",
".",
"getTestKeys",
"(",
")",
")",
"{",
"TestEntry",
"te",
"=",
"index",
".",
"getTest",
"(",
... | Loads all of the XSL executables. This is a time consuming operation.
@param index
@param sourcesName
A stylesheet reference.
@throws Exception
If the stylesheet fail to compile. | [
"Loads",
"all",
"of",
"the",
"XSL",
"executables",
".",
"This",
"is",
"a",
"time",
"consuming",
"operation",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/Engine.java#L136-L149 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/DocumentationHelper.java | DocumentationHelper.prettyprint | private void prettyprint(String xmlLogsFile, FileOutputStream htmlReportFile)
throws Exception {
TransformerFactory tFactory = TransformerFactory.newInstance();
// Fortify Mod: prevent external entity injection
tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Fortify Mod: prevent external entity injection
factory.setExpandEntityReferences(false);
factory.setNamespaceAware(true);
factory.setXIncludeAware(true);
DocumentBuilder parser = factory.newDocumentBuilder();
Document document = parser.parse(xmlLogsFile);
Transformer transformer = tFactory.newTransformer(new StreamSource(
xsltFileHandler));
transformer.transform(new DOMSource(document), new StreamResult(
htmlReportFile));
} | java | private void prettyprint(String xmlLogsFile, FileOutputStream htmlReportFile)
throws Exception {
TransformerFactory tFactory = TransformerFactory.newInstance();
// Fortify Mod: prevent external entity injection
tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Fortify Mod: prevent external entity injection
factory.setExpandEntityReferences(false);
factory.setNamespaceAware(true);
factory.setXIncludeAware(true);
DocumentBuilder parser = factory.newDocumentBuilder();
Document document = parser.parse(xmlLogsFile);
Transformer transformer = tFactory.newTransformer(new StreamSource(
xsltFileHandler));
transformer.transform(new DOMSource(document), new StreamResult(
htmlReportFile));
} | [
"private",
"void",
"prettyprint",
"(",
"String",
"xmlLogsFile",
",",
"FileOutputStream",
"htmlReportFile",
")",
"throws",
"Exception",
"{",
"TransformerFactory",
"tFactory",
"=",
"TransformerFactory",
".",
"newInstance",
"(",
")",
";",
"// Fortify Mod: prevent external en... | Apply xslt stylesheet to xml logs file and crate an HTML report file.
@param xmlLogsFile
@param htmlReportFile | [
"Apply",
"xslt",
"stylesheet",
"to",
"xml",
"logs",
"file",
"and",
"crate",
"an",
"HTML",
"report",
"file",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/DocumentationHelper.java#L92-L108 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/DocumentationHelper.java | DocumentationHelper.generateDocumentation | public void generateDocumentation(String sourcecodePath, String suiteName,
FileOutputStream htmlFileOutput) throws Exception {
TransformerFactory tFactory = TransformerFactory.newInstance();
// Fortify Mod: prevent external entity injection
tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Fortify Mod: prevent external entity injection
factory.setExpandEntityReferences(false);
factory.setNamespaceAware(true);
factory.setXIncludeAware(true);
DocumentBuilder parser = factory.newDocumentBuilder();
Document document = parser.parse(sourcecodePath);
Transformer transformer = tFactory.newTransformer(new StreamSource(
xsltSystemId));
transformer.transform(new DOMSource(document), new StreamResult(
htmlFileOutput));
} | java | public void generateDocumentation(String sourcecodePath, String suiteName,
FileOutputStream htmlFileOutput) throws Exception {
TransformerFactory tFactory = TransformerFactory.newInstance();
// Fortify Mod: prevent external entity injection
tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Fortify Mod: prevent external entity injection
factory.setExpandEntityReferences(false);
factory.setNamespaceAware(true);
factory.setXIncludeAware(true);
DocumentBuilder parser = factory.newDocumentBuilder();
Document document = parser.parse(sourcecodePath);
Transformer transformer = tFactory.newTransformer(new StreamSource(
xsltSystemId));
transformer.transform(new DOMSource(document), new StreamResult(
htmlFileOutput));
} | [
"public",
"void",
"generateDocumentation",
"(",
"String",
"sourcecodePath",
",",
"String",
"suiteName",
",",
"FileOutputStream",
"htmlFileOutput",
")",
"throws",
"Exception",
"{",
"TransformerFactory",
"tFactory",
"=",
"TransformerFactory",
".",
"newInstance",
"(",
")",... | Generate pseudocode documentation for CTL test scripts. Apply the
stylesheet to documentate the sources of tests.
@param sourcecodePath
main file of test source
@param suiteName
name of the suite to be documented (TBD)
@param htmlFileOutput
path of generated file
@throws Exception | [
"Generate",
"pseudocode",
"documentation",
"for",
"CTL",
"test",
"scripts",
".",
"Apply",
"the",
"stylesheet",
"to",
"documentate",
"the",
"sources",
"of",
"tests",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/DocumentationHelper.java#L122-L139 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/Misc.java | Misc.deleteDirContents | public static void deleteDirContents(File dir) {
if (!dir.isDirectory() || !dir.exists()) {
throw new IllegalArgumentException(dir.getAbsolutePath()
+ " is not a directory or does not exist.");
}
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
File f = new File(dir, children[i]);
if (f.isDirectory()) {
deleteDirContents(f);
}
f.delete();
}
} | java | public static void deleteDirContents(File dir) {
if (!dir.isDirectory() || !dir.exists()) {
throw new IllegalArgumentException(dir.getAbsolutePath()
+ " is not a directory or does not exist.");
}
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
File f = new File(dir, children[i]);
if (f.isDirectory()) {
deleteDirContents(f);
}
f.delete();
}
} | [
"public",
"static",
"void",
"deleteDirContents",
"(",
"File",
"dir",
")",
"{",
"if",
"(",
"!",
"dir",
".",
"isDirectory",
"(",
")",
"||",
"!",
"dir",
".",
"exists",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"dir",
".",
"getAb... | Deletes the contents of a directory, including subdirectories.
@param dir
The directory to be emptied. | [
"Deletes",
"the",
"contents",
"of",
"a",
"directory",
"including",
"subdirectories",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/Misc.java#L48-L61 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/Misc.java | Misc.deleteSubDirs | public static void deleteSubDirs(File dir) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
File f = new File(dir, children[i]);
if (f.isDirectory()) {
deleteDir(f);
}
}
} | java | public static void deleteSubDirs(File dir) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
File f = new File(dir, children[i]);
if (f.isDirectory()) {
deleteDir(f);
}
}
} | [
"public",
"static",
"void",
"deleteSubDirs",
"(",
"File",
"dir",
")",
"{",
"String",
"[",
"]",
"children",
"=",
"dir",
".",
"list",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"children",
".",
"length",
";",
"i",
"++",
")",
... | Deletes just the sub directories for a certain directory | [
"Deletes",
"just",
"the",
"sub",
"directories",
"for",
"a",
"certain",
"directory"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/Misc.java#L64-L72 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/Misc.java | Misc.getResourceAsFile | public static File getResourceAsFile(String resource) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
return new File(URLDecoder.decode(cl.getResource(resource)
.getFile(), "UTF-8"));
} catch (UnsupportedEncodingException uee) {
return null;
}
} | java | public static File getResourceAsFile(String resource) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
return new File(URLDecoder.decode(cl.getResource(resource)
.getFile(), "UTF-8"));
} catch (UnsupportedEncodingException uee) {
return null;
}
} | [
"public",
"static",
"File",
"getResourceAsFile",
"(",
"String",
"resource",
")",
"{",
"ClassLoader",
"cl",
"=",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getContextClassLoader",
"(",
")",
";",
"try",
"{",
"return",
"new",
"File",
"(",
"URLDecoder",
"."... | Loads a file into memory from the classpath | [
"Loads",
"a",
"file",
"into",
"memory",
"from",
"the",
"classpath"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/Misc.java#L75-L83 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/Misc.java | Misc.getResourceAsDoc | Document getResourceAsDoc(String resource) throws Exception {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
InputStream is = cl.getResourceAsStream(resource);
if (is != null) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
// Fortify Mod: prevent external entity injection
dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder();
// Fortify Mod: prevent external entity injection
TransformerFactory tf = TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer t = tf.newTransformer();
//Transformer t = TransformerFactory.newInstance().newTransformer();
// End Fortify Mod
Document doc = db.newDocument();
t.transform(new StreamSource(is), new DOMResult(doc));
// Fortify Mod: Close the InputStream and release its resources
is.close();
return doc;
} else {
return null;
}
} | java | Document getResourceAsDoc(String resource) throws Exception {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
InputStream is = cl.getResourceAsStream(resource);
if (is != null) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
// Fortify Mod: prevent external entity injection
dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder();
// Fortify Mod: prevent external entity injection
TransformerFactory tf = TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer t = tf.newTransformer();
//Transformer t = TransformerFactory.newInstance().newTransformer();
// End Fortify Mod
Document doc = db.newDocument();
t.transform(new StreamSource(is), new DOMResult(doc));
// Fortify Mod: Close the InputStream and release its resources
is.close();
return doc;
} else {
return null;
}
} | [
"Document",
"getResourceAsDoc",
"(",
"String",
"resource",
")",
"throws",
"Exception",
"{",
"ClassLoader",
"cl",
"=",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getContextClassLoader",
"(",
")",
";",
"InputStream",
"is",
"=",
"cl",
".",
"getResourceAsStream... | Loads a DOM Document from the classpath | [
"Loads",
"a",
"DOM",
"Document",
"from",
"the",
"classpath"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/Misc.java#L86-L109 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/Misc.java | Misc.getResourceURL | public static String getResourceURL(String resource) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
return cl.getResource(resource).toString();
} | java | public static String getResourceURL(String resource) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
return cl.getResource(resource).toString();
} | [
"public",
"static",
"String",
"getResourceURL",
"(",
"String",
"resource",
")",
"{",
"ClassLoader",
"cl",
"=",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getContextClassLoader",
"(",
")",
";",
"return",
"cl",
".",
"getResource",
"(",
"resource",
")",
".... | Returns the URL for file on the classpath as a String | [
"Returns",
"the",
"URL",
"for",
"file",
"on",
"the",
"classpath",
"as",
"a",
"String"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/Misc.java#L112-L115 | train |
opengeospatial/teamengine | teamengine-realm/src/main/java/com/occamlab/te/realm/PBKDF2Realm.java | PBKDF2Realm.authenticate | @Override
public Principal authenticate(String username, String credentials) {
GenericPrincipal principal = (GenericPrincipal) getPrincipal(username);
if (null != principal) {
try {
if (!PasswordStorage.verifyPassword(credentials, principal.getPassword())) {
principal = null;
}
} catch (CannotPerformOperationException | InvalidHashException e) {
LOGR.log(Level.WARNING, e.getMessage());
principal = null;
}
}
return principal;
} | java | @Override
public Principal authenticate(String username, String credentials) {
GenericPrincipal principal = (GenericPrincipal) getPrincipal(username);
if (null != principal) {
try {
if (!PasswordStorage.verifyPassword(credentials, principal.getPassword())) {
principal = null;
}
} catch (CannotPerformOperationException | InvalidHashException e) {
LOGR.log(Level.WARNING, e.getMessage());
principal = null;
}
}
return principal;
} | [
"@",
"Override",
"public",
"Principal",
"authenticate",
"(",
"String",
"username",
",",
"String",
"credentials",
")",
"{",
"GenericPrincipal",
"principal",
"=",
"(",
"GenericPrincipal",
")",
"getPrincipal",
"(",
"username",
")",
";",
"if",
"(",
"null",
"!=",
"... | Return the Principal associated with the specified username and
credentials, if one exists in the user data store; otherwise return null. | [
"Return",
"the",
"Principal",
"associated",
"with",
"the",
"specified",
"username",
"and",
"credentials",
"if",
"one",
"exists",
"in",
"the",
"user",
"data",
"store",
";",
"otherwise",
"return",
"null",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-realm/src/main/java/com/occamlab/te/realm/PBKDF2Realm.java#L75-L89 | train |
opengeospatial/teamengine | teamengine-realm/src/main/java/com/occamlab/te/realm/PBKDF2Realm.java | PBKDF2Realm.createGenericPrincipal | @SuppressWarnings({ "rawtypes", "unchecked" })
GenericPrincipal createGenericPrincipal(String username, String password, List<String> roles) {
Class klass = null;
try {
klass = Class.forName("org.apache.catalina.realm.GenericPrincipal");
} catch (ClassNotFoundException ex) {
LOGR.log(Level.SEVERE, ex.getMessage());
// Fortify Mod: If klass is not populated, then there is no point in continuing
return null;
}
Constructor[] ctors = klass.getConstructors();
Class firstParamType = ctors[0].getParameterTypes()[0];
Class[] paramTypes = new Class[] { Realm.class, String.class, String.class, List.class };
Object[] ctorArgs = new Object[] { this, username, password, roles };
GenericPrincipal principal = null;
try {
if (Realm.class.isAssignableFrom(firstParamType)) {
// Tomcat 6
Constructor ctor = klass.getConstructor(paramTypes);
principal = (GenericPrincipal) ctor.newInstance(ctorArgs);
} else {
// Realm parameter removed in Tomcat 7
Constructor ctor = klass.getConstructor(Arrays.copyOfRange(paramTypes, 1, paramTypes.length));
principal = (GenericPrincipal) ctor.newInstance(Arrays.copyOfRange(ctorArgs, 1, ctorArgs.length));
}
} catch (Exception ex) {
LOGR.log(Level.WARNING, ex.getMessage());
}
return principal;
} | java | @SuppressWarnings({ "rawtypes", "unchecked" })
GenericPrincipal createGenericPrincipal(String username, String password, List<String> roles) {
Class klass = null;
try {
klass = Class.forName("org.apache.catalina.realm.GenericPrincipal");
} catch (ClassNotFoundException ex) {
LOGR.log(Level.SEVERE, ex.getMessage());
// Fortify Mod: If klass is not populated, then there is no point in continuing
return null;
}
Constructor[] ctors = klass.getConstructors();
Class firstParamType = ctors[0].getParameterTypes()[0];
Class[] paramTypes = new Class[] { Realm.class, String.class, String.class, List.class };
Object[] ctorArgs = new Object[] { this, username, password, roles };
GenericPrincipal principal = null;
try {
if (Realm.class.isAssignableFrom(firstParamType)) {
// Tomcat 6
Constructor ctor = klass.getConstructor(paramTypes);
principal = (GenericPrincipal) ctor.newInstance(ctorArgs);
} else {
// Realm parameter removed in Tomcat 7
Constructor ctor = klass.getConstructor(Arrays.copyOfRange(paramTypes, 1, paramTypes.length));
principal = (GenericPrincipal) ctor.newInstance(Arrays.copyOfRange(ctorArgs, 1, ctorArgs.length));
}
} catch (Exception ex) {
LOGR.log(Level.WARNING, ex.getMessage());
}
return principal;
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"rawtypes\"",
",",
"\"unchecked\"",
"}",
")",
"GenericPrincipal",
"createGenericPrincipal",
"(",
"String",
"username",
",",
"String",
"password",
",",
"List",
"<",
"String",
">",
"roles",
")",
"{",
"Class",
"klass",
"=",
"n... | Creates a new GenericPrincipal representing the specified user.
@param username
The username for this user.
@param password
The authentication credentials for this user.
@param roles
The set of roles (specified using String values) associated
with this user.
@return A GenericPrincipal for use by this Realm implementation. | [
"Creates",
"a",
"new",
"GenericPrincipal",
"representing",
"the",
"specified",
"user",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-realm/src/main/java/com/occamlab/te/realm/PBKDF2Realm.java#L196-L225 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/form/ImageHandler.java | ImageHandler.saveImages | public void saveImages( Element form )
throws IOException {
List<Element> images = DomUtils.getElementsByTagName( form, "img" );
int imageCount = 1;
for ( Element image : images ) {
if ( image.hasAttribute( "src" ) ) {
String src = image.getAttribute( "src" );
String imageFormat = parseImageFormat( src );
String testName = System.getProperty( "TestName" );
String imgName = parseImageName( testName );
URL url = new URL( src );
BufferedImage img = ImageIO.read( url );
File file = createImageFile( imageCount, imageFormat, imgName );
if ( !file.exists() ) {
file.getParentFile().mkdirs();
}
ImageIO.write( img, imageFormat, file );
imageCount++;
}
}
} | java | public void saveImages( Element form )
throws IOException {
List<Element> images = DomUtils.getElementsByTagName( form, "img" );
int imageCount = 1;
for ( Element image : images ) {
if ( image.hasAttribute( "src" ) ) {
String src = image.getAttribute( "src" );
String imageFormat = parseImageFormat( src );
String testName = System.getProperty( "TestName" );
String imgName = parseImageName( testName );
URL url = new URL( src );
BufferedImage img = ImageIO.read( url );
File file = createImageFile( imageCount, imageFormat, imgName );
if ( !file.exists() ) {
file.getParentFile().mkdirs();
}
ImageIO.write( img, imageFormat, file );
imageCount++;
}
}
} | [
"public",
"void",
"saveImages",
"(",
"Element",
"form",
")",
"throws",
"IOException",
"{",
"List",
"<",
"Element",
">",
"images",
"=",
"DomUtils",
".",
"getElementsByTagName",
"(",
"form",
",",
"\"img\"",
")",
";",
"int",
"imageCount",
"=",
"1",
";",
"for"... | Save images into session if the ets is interactive and it contains the images.
@param form
the form element with the images, never <code>null</code>
@throws IOException
if the images could not be read/write | [
"Save",
"images",
"into",
"session",
"if",
"the",
"ets",
"is",
"interactive",
"and",
"it",
"contains",
"the",
"images",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/form/ImageHandler.java#L46-L66 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/HTTPParser.java | HTTPParser.select_parser | static Node select_parser(int partnum, String mime, Element instruction) {
if (null == instruction)
return null;
NodeList instructions = instruction.getElementsByTagNameNS(PARSERS_NS,
"parse");
Node parserNode = null;
instructionsLoop: for (int i = 0; i < instructions.getLength(); i++) {
Element parse = (Element) instructions.item(i);
if (partnum != 0) {
String part_i = parse.getAttribute("part");
if (part_i.length() > 0) {
int n = Integer.parseInt(part_i);
if (n != partnum) {
continue;
}
}
}
if (mime != null) {
String mime_i = parse.getAttribute("mime");
if (mime_i.length() > 0) {
String[] mime_parts = mime_i.split(";\\s*");
if (!mime.startsWith(mime_parts[0])) {
continue;
}
boolean ok = true;
for (int j = 1; j < mime_parts.length; j++) {
if (mime.indexOf(mime_parts[j]) < 0) {
ok = false;
break;
}
}
if (!ok) {
continue;
}
}
}
NodeList children = parse.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
if (children.item(j).getNodeType() == Node.ELEMENT_NODE) {
parserNode = children.item(j);
break instructionsLoop;
}
}
}
return parserNode;
} | java | static Node select_parser(int partnum, String mime, Element instruction) {
if (null == instruction)
return null;
NodeList instructions = instruction.getElementsByTagNameNS(PARSERS_NS,
"parse");
Node parserNode = null;
instructionsLoop: for (int i = 0; i < instructions.getLength(); i++) {
Element parse = (Element) instructions.item(i);
if (partnum != 0) {
String part_i = parse.getAttribute("part");
if (part_i.length() > 0) {
int n = Integer.parseInt(part_i);
if (n != partnum) {
continue;
}
}
}
if (mime != null) {
String mime_i = parse.getAttribute("mime");
if (mime_i.length() > 0) {
String[] mime_parts = mime_i.split(";\\s*");
if (!mime.startsWith(mime_parts[0])) {
continue;
}
boolean ok = true;
for (int j = 1; j < mime_parts.length; j++) {
if (mime.indexOf(mime_parts[j]) < 0) {
ok = false;
break;
}
}
if (!ok) {
continue;
}
}
}
NodeList children = parse.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
if (children.item(j).getNodeType() == Node.ELEMENT_NODE) {
parserNode = children.item(j);
break instructionsLoop;
}
}
}
return parserNode;
} | [
"static",
"Node",
"select_parser",
"(",
"int",
"partnum",
",",
"String",
"mime",
",",
"Element",
"instruction",
")",
"{",
"if",
"(",
"null",
"==",
"instruction",
")",
"return",
"null",
";",
"NodeList",
"instructions",
"=",
"instruction",
".",
"getElementsByTag... | Selects a parser for a message part based on the part number and MIME
format type, if supplied in instructions.
@param partnum
An integer indicating the message part number.
@param mime
A MIME media type.
@param instruction
An Element representing parser instructions.
@return A Node containing parser info, or {@code null} if no matching
parser is found. | [
"Selects",
"a",
"parser",
"for",
"a",
"message",
"part",
"based",
"on",
"the",
"part",
"number",
"and",
"MIME",
"format",
"type",
"if",
"supplied",
"in",
"instructions",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/HTTPParser.java#L97-L142 | train |
opengeospatial/teamengine | teamengine-spi/src/main/java/com/occamlab/te/spi/executors/FixtureManager.java | FixtureManager.getFixture | public TestRunFixture getFixture(String runId) {
if (runId.isEmpty() && this.fixtures.size() == 1) {
runId = this.fixtures.keySet().iterator().next();
}
return fixtures.get(runId);
} | java | public TestRunFixture getFixture(String runId) {
if (runId.isEmpty() && this.fixtures.size() == 1) {
runId = this.fixtures.keySet().iterator().next();
}
return fixtures.get(runId);
} | [
"public",
"TestRunFixture",
"getFixture",
"(",
"String",
"runId",
")",
"{",
"if",
"(",
"runId",
".",
"isEmpty",
"(",
")",
"&&",
"this",
".",
"fixtures",
".",
"size",
"(",
")",
"==",
"1",
")",
"{",
"runId",
"=",
"this",
".",
"fixtures",
".",
"keySet",... | Gets the fixture for the specified test run. If runId is an empty String
and only one fixture exists this is returned.
@param runId
The test run identifier (may be an empty String).
@return A TestRunFixture, or {@code null } if a matching one cannot be
found. | [
"Gets",
"the",
"fixture",
"for",
"the",
"specified",
"test",
"run",
".",
"If",
"runId",
"is",
"an",
"empty",
"String",
"and",
"only",
"one",
"fixture",
"exists",
"this",
"is",
"returned",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-spi/src/main/java/com/occamlab/te/spi/executors/FixtureManager.java#L55-L60 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/XmlErrorHandler.java | XmlErrorHandler.printError | void printError(String type, SAXParseException e) {
PrintWriter logger = new PrintWriter(System.out);
logger.print(type);
if (e.getLineNumber() >= 0) {
logger.print(" at line " + e.getLineNumber());
if (e.getColumnNumber() >= 0) {
logger.print(", column " + e.getColumnNumber());
}
if (e.getSystemId() != null) {
logger.print(" of " + e.getSystemId());
}
} else {
if (e.getSystemId() != null) {
logger.print(" in " + e.getSystemId());
}
}
logger.println(":");
logger.println(" " + e.getMessage());
logger.flush();
} | java | void printError(String type, SAXParseException e) {
PrintWriter logger = new PrintWriter(System.out);
logger.print(type);
if (e.getLineNumber() >= 0) {
logger.print(" at line " + e.getLineNumber());
if (e.getColumnNumber() >= 0) {
logger.print(", column " + e.getColumnNumber());
}
if (e.getSystemId() != null) {
logger.print(" of " + e.getSystemId());
}
} else {
if (e.getSystemId() != null) {
logger.print(" in " + e.getSystemId());
}
}
logger.println(":");
logger.println(" " + e.getMessage());
logger.flush();
} | [
"void",
"printError",
"(",
"String",
"type",
",",
"SAXParseException",
"e",
")",
"{",
"PrintWriter",
"logger",
"=",
"new",
"PrintWriter",
"(",
"System",
".",
"out",
")",
";",
"logger",
".",
"print",
"(",
"type",
")",
";",
"if",
"(",
"e",
".",
"getLineN... | Prints the error to STDOUT, used to be consistent with TEAM Engine error
handler. | [
"Prints",
"the",
"error",
"to",
"STDOUT",
"used",
"to",
"be",
"consistent",
"with",
"TEAM",
"Engine",
"error",
"handler",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/XmlErrorHandler.java#L83-L102 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/XmlErrorHandler.java | XmlErrorHandler.toList | public List<String> toList() {
List<String> errorStrings = new ArrayList<String>();
ErrorIterator errIterator = iterator();
while (errIterator.hasNext()) {
ValidationError err = errIterator.next();
errorStrings.add(err.getMessage());
}
return errorStrings;
} | java | public List<String> toList() {
List<String> errorStrings = new ArrayList<String>();
ErrorIterator errIterator = iterator();
while (errIterator.hasNext()) {
ValidationError err = errIterator.next();
errorStrings.add(err.getMessage());
}
return errorStrings;
} | [
"public",
"List",
"<",
"String",
">",
"toList",
"(",
")",
"{",
"List",
"<",
"String",
">",
"errorStrings",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"ErrorIterator",
"errIterator",
"=",
"iterator",
"(",
")",
";",
"while",
"(",
"errIte... | Returns a list of errors as strings.
@return a list of error strings. | [
"Returns",
"a",
"list",
"of",
"errors",
"as",
"strings",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/XmlErrorHandler.java#L160-L169 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/XMLValidatingParser.java | XMLValidatingParser.parse | public Document parse(URLConnection uc, Element instruction,
PrintWriter logger) throws SSLProtocolException {
if (null == uc) {
throw new NullPointerException(
"Unable to parse resource: URLConnection is null.");
}
jlogger.fine("Received URLConnection object for " + uc.getURL());
Document doc = null;
try (InputStream inStream = URLConnectionUtils.getInputStream(uc)) {
doc = parse(inStream, instruction, logger);
} catch (SSLProtocolException sslep){
throw new SSLProtocolException("[SSL ERROR] Failed to connect with the requested URL due to \"Invalid server_name\" found!! :" + uc.getURL() +":" + sslep.getClass() +" : "+ sslep.getMessage());
} catch (Exception e) {
throw new RuntimeException(
String.format("Failed to parse resource from %s", uc.getURL()),
e);
}
return doc;
} | java | public Document parse(URLConnection uc, Element instruction,
PrintWriter logger) throws SSLProtocolException {
if (null == uc) {
throw new NullPointerException(
"Unable to parse resource: URLConnection is null.");
}
jlogger.fine("Received URLConnection object for " + uc.getURL());
Document doc = null;
try (InputStream inStream = URLConnectionUtils.getInputStream(uc)) {
doc = parse(inStream, instruction, logger);
} catch (SSLProtocolException sslep){
throw new SSLProtocolException("[SSL ERROR] Failed to connect with the requested URL due to \"Invalid server_name\" found!! :" + uc.getURL() +":" + sslep.getClass() +" : "+ sslep.getMessage());
} catch (Exception e) {
throw new RuntimeException(
String.format("Failed to parse resource from %s", uc.getURL()),
e);
}
return doc;
} | [
"public",
"Document",
"parse",
"(",
"URLConnection",
"uc",
",",
"Element",
"instruction",
",",
"PrintWriter",
"logger",
")",
"throws",
"SSLProtocolException",
"{",
"if",
"(",
"null",
"==",
"uc",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"Unable to... | Attempts to parse a resource read using the given connection to a URL.
@param uc
A connection for reading from some URL.
@param instruction
An Element node (ctlp:XMLValidatingParser) containing
instructions, usually schema references.
@param logger
A log writer.
@return A Document, or null if the resource could not be parsed.
@throws SSLProtocolException | [
"Attempts",
"to",
"parse",
"a",
"resource",
"read",
"using",
"the",
"given",
"connection",
"to",
"a",
"URL",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/XMLValidatingParser.java#L213-L231 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/XMLValidatingParser.java | XMLValidatingParser.parse | Document parse(Object input, Element parserConfig, PrintWriter logger)
throws Exception {
jlogger.finer("Received XML resource of type "
+ input.getClass().getName());
ArrayList<Object> schemas = new ArrayList<Object>();
ArrayList<Object> dtds = new ArrayList<Object>();
schemas.addAll(this.schemaList);
dtds.addAll(this.dtdList);
loadSchemaLists(parserConfig, schemas, dtds);
Document resultDoc = null;
ErrorHandlerImpl errHandler = new ErrorHandlerImpl("Parsing", logger);
if (input instanceof InputStream) {
DocumentBuilderFactory dbf = nonValidatingDBF;
DocumentBuilder db = dbf.newDocumentBuilder();
db.setErrorHandler(errHandler);
try (InputStream xmlInput = (InputStream) input) {
resultDoc = db.parse(xmlInput);
} catch (Exception e) {
jlogger.log(Level.INFO, "Error parsing InputStream", e);
}
} else if (input instanceof Document) {
resultDoc = (Document) input;
} else {
throw new IllegalArgumentException(
"XML input must be an InputStream or a Document object.");
}
if (null == resultDoc) {
throw new RuntimeException("Failed to parse input: "
+ input.getClass().getName());
}
errHandler.setRole("Validation");
if (null == resultDoc.getDoctype() && dtds.isEmpty()) {
validateAgainstXMLSchemaList(resultDoc, schemas, errHandler);
} else {
validateAgainstDTDList(resultDoc, dtds, errHandler);
}
int error_count = errHandler.getErrorCount();
int warning_count = errHandler.getWarningCount();
if (error_count > 0 || warning_count > 0) {
String msg = "";
if (error_count > 0) {
msg += error_count + " validation error"
+ (error_count == 1 ? "" : "s");
if (warning_count > 0)
msg += " and ";
}
if (warning_count > 0) {
msg += warning_count + " warning"
+ (warning_count == 1 ? "" : "s");
}
msg += " detected.";
logger.println(msg);
}
if (error_count > 0) {
String s = (null != parserConfig) ? parserConfig
.getAttribute("ignoreErrors") : "false";
if (s.length() == 0 || Boolean.parseBoolean(s) == false) {
resultDoc = null;
}
}
if (warning_count > 0) {
String s = (null != parserConfig) ? parserConfig
.getAttribute("ignoreWarnings") : "true";
if (s.length() > 0 && Boolean.parseBoolean(s) == false) {
resultDoc = null;
}
}
return resultDoc;
} | java | Document parse(Object input, Element parserConfig, PrintWriter logger)
throws Exception {
jlogger.finer("Received XML resource of type "
+ input.getClass().getName());
ArrayList<Object> schemas = new ArrayList<Object>();
ArrayList<Object> dtds = new ArrayList<Object>();
schemas.addAll(this.schemaList);
dtds.addAll(this.dtdList);
loadSchemaLists(parserConfig, schemas, dtds);
Document resultDoc = null;
ErrorHandlerImpl errHandler = new ErrorHandlerImpl("Parsing", logger);
if (input instanceof InputStream) {
DocumentBuilderFactory dbf = nonValidatingDBF;
DocumentBuilder db = dbf.newDocumentBuilder();
db.setErrorHandler(errHandler);
try (InputStream xmlInput = (InputStream) input) {
resultDoc = db.parse(xmlInput);
} catch (Exception e) {
jlogger.log(Level.INFO, "Error parsing InputStream", e);
}
} else if (input instanceof Document) {
resultDoc = (Document) input;
} else {
throw new IllegalArgumentException(
"XML input must be an InputStream or a Document object.");
}
if (null == resultDoc) {
throw new RuntimeException("Failed to parse input: "
+ input.getClass().getName());
}
errHandler.setRole("Validation");
if (null == resultDoc.getDoctype() && dtds.isEmpty()) {
validateAgainstXMLSchemaList(resultDoc, schemas, errHandler);
} else {
validateAgainstDTDList(resultDoc, dtds, errHandler);
}
int error_count = errHandler.getErrorCount();
int warning_count = errHandler.getWarningCount();
if (error_count > 0 || warning_count > 0) {
String msg = "";
if (error_count > 0) {
msg += error_count + " validation error"
+ (error_count == 1 ? "" : "s");
if (warning_count > 0)
msg += " and ";
}
if (warning_count > 0) {
msg += warning_count + " warning"
+ (warning_count == 1 ? "" : "s");
}
msg += " detected.";
logger.println(msg);
}
if (error_count > 0) {
String s = (null != parserConfig) ? parserConfig
.getAttribute("ignoreErrors") : "false";
if (s.length() == 0 || Boolean.parseBoolean(s) == false) {
resultDoc = null;
}
}
if (warning_count > 0) {
String s = (null != parserConfig) ? parserConfig
.getAttribute("ignoreWarnings") : "true";
if (s.length() > 0 && Boolean.parseBoolean(s) == false) {
resultDoc = null;
}
}
return resultDoc;
} | [
"Document",
"parse",
"(",
"Object",
"input",
",",
"Element",
"parserConfig",
",",
"PrintWriter",
"logger",
")",
"throws",
"Exception",
"{",
"jlogger",
".",
"finer",
"(",
"\"Received XML resource of type \"",
"+",
"input",
".",
"getClass",
"(",
")",
".",
"getName... | Parses and validates an XML resource using the given schema references.
@param input
The XML input to parse and validate. It must be either an
InputStream or a Document object.
@param parserConfig
An Element
({http://www.occamlab.com/te/parsers}XMLValidatingParser)
containing configuration info. If it is {@code null} or empty
validation will be performed by using location hints in the
input document.
@param logger
The PrintWriter to log all results to
@return {@code null} If any non-ignorable errors or warnings occurred;
otherwise the resulting Document. | [
"Parses",
"and",
"validates",
"an",
"XML",
"resource",
"using",
"the",
"given",
"schema",
"references",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/XMLValidatingParser.java#L251-L322 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/XMLValidatingParser.java | XMLValidatingParser.checkXMLRules | public boolean checkXMLRules(Document doc, Document instruction)
throws Exception {
if (doc == null || doc.getDocumentElement() == null)
return false;
Element e = instruction.getDocumentElement();
PrintWriter logger = new PrintWriter(System.out);
Document parsedDoc = parse(doc, e, logger);
return (parsedDoc != null);
} | java | public boolean checkXMLRules(Document doc, Document instruction)
throws Exception {
if (doc == null || doc.getDocumentElement() == null)
return false;
Element e = instruction.getDocumentElement();
PrintWriter logger = new PrintWriter(System.out);
Document parsedDoc = parse(doc, e, logger);
return (parsedDoc != null);
} | [
"public",
"boolean",
"checkXMLRules",
"(",
"Document",
"doc",
",",
"Document",
"instruction",
")",
"throws",
"Exception",
"{",
"if",
"(",
"doc",
"==",
"null",
"||",
"doc",
".",
"getDocumentElement",
"(",
")",
"==",
"null",
")",
"return",
"false",
";",
"Ele... | A method to validate a pool of schemas outside of the request element.
@param Document
doc The file document to validate
@param Document
instruction The xml encapsulated schema information (file
locations)
@return false if there were errors, true if none. | [
"A",
"method",
"to",
"validate",
"a",
"pool",
"of",
"schemas",
"outside",
"of",
"the",
"request",
"element",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/XMLValidatingParser.java#L335-L344 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/XMLValidatingParser.java | XMLValidatingParser.validate | public NodeList validate(Document doc, Document instruction)
throws Exception {
return schemaValidation(doc, instruction).toNodeList();
} | java | public NodeList validate(Document doc, Document instruction)
throws Exception {
return schemaValidation(doc, instruction).toNodeList();
} | [
"public",
"NodeList",
"validate",
"(",
"Document",
"doc",
",",
"Document",
"instruction",
")",
"throws",
"Exception",
"{",
"return",
"schemaValidation",
"(",
"doc",
",",
"instruction",
")",
".",
"toNodeList",
"(",
")",
";",
"}"
] | Validates the given document against the schema references supplied in
the accompanying instruction document.
@param doc
The document to be validated.
@param instruction
A document containing schema references; may be null, in which
case embedded schema references will be used instead.
@return A list of Element nodes ({@code <error>}) containing error
messages.
@throws Exception
If any error occurs. | [
"Validates",
"the",
"given",
"document",
"against",
"the",
"schema",
"references",
"supplied",
"in",
"the",
"accompanying",
"instruction",
"document",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/XMLValidatingParser.java#L360-L363 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/XMLValidatingParser.java | XMLValidatingParser.validateAgainstXMLSchemaList | void validateAgainstXMLSchemaList(Document doc, ArrayList<Object> xsdList,
ErrorHandler errHandler) throws SAXException, IOException {
jlogger.finer("Validating XML resource from " + doc.getDocumentURI());
Schema schema = SF.newSchema();
if (null != xsdList && !xsdList.isEmpty()) {
Source[] schemaSources = new Source[xsdList.size()];
for (int i = 0; i < xsdList.size(); i++) {
Object ref = xsdList.get(i);
if (ref instanceof File) {
schemaSources[i] = new StreamSource((File) ref);
} else if (ref instanceof URL) {
schemaSources[i] = new StreamSource(ref.toString());
} else if (ref instanceof char[]) {
schemaSources[i] = new StreamSource(new CharArrayReader(
(char[]) ref));
} else {
throw new IllegalArgumentException(
"Unknown schema reference: " + ref.toString());
}
}
schema = SF.newSchema(schemaSources);
} | java | void validateAgainstXMLSchemaList(Document doc, ArrayList<Object> xsdList,
ErrorHandler errHandler) throws SAXException, IOException {
jlogger.finer("Validating XML resource from " + doc.getDocumentURI());
Schema schema = SF.newSchema();
if (null != xsdList && !xsdList.isEmpty()) {
Source[] schemaSources = new Source[xsdList.size()];
for (int i = 0; i < xsdList.size(); i++) {
Object ref = xsdList.get(i);
if (ref instanceof File) {
schemaSources[i] = new StreamSource((File) ref);
} else if (ref instanceof URL) {
schemaSources[i] = new StreamSource(ref.toString());
} else if (ref instanceof char[]) {
schemaSources[i] = new StreamSource(new CharArrayReader(
(char[]) ref));
} else {
throw new IllegalArgumentException(
"Unknown schema reference: " + ref.toString());
}
}
schema = SF.newSchema(schemaSources);
} | [
"void",
"validateAgainstXMLSchemaList",
"(",
"Document",
"doc",
",",
"ArrayList",
"<",
"Object",
">",
"xsdList",
",",
"ErrorHandler",
"errHandler",
")",
"throws",
"SAXException",
",",
"IOException",
"{",
"jlogger",
".",
"finer",
"(",
"\"Validating XML resource from \"... | Validates an XML resource against a list of XML Schemas. Validation
errors are reported to the given handler.
@param doc
The input Document node.
@param xsdList
A list of XML schema references. If the list is {@code null}
or empty, validation will be performed by using location hints
found in the input document.
@param errHandler
An ErrorHandler that collects validation errors.
@throws SAXException
If a schema cannot be read for some reason.
@throws IOException
If an I/O error occurs. | [
"Validates",
"an",
"XML",
"resource",
"against",
"a",
"list",
"of",
"XML",
"Schemas",
".",
"Validation",
"errors",
"are",
"reported",
"to",
"the",
"given",
"handler",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/XMLValidatingParser.java#L406-L427 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/DomUtils.java | DomUtils.addDomAttr | public static Node addDomAttr(Document doc, String tagName,
String tagNamespaceURI, String attrName, String attrValue) {
// Create a Document to work on
Document newDoc = null;
try {
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
newDoc = db.newDocument();
} catch (Exception e) {
e.printStackTrace();
// Fortify Mod: If we got here there is no point going any further
return null;
}
Transformer identity = null;
try {
TransformerFactory TF = TransformerFactory.newInstance();
// Fortify Mod: disable external entity injection
TF.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
identity = TF.newTransformer();
// End Fortify Mod
identity.transform(new DOMSource(doc), new DOMResult(newDoc));
} catch (Exception ex) {
System.out.println("ERROR: " + ex.getMessage());
}
// Get all named nodes in the doucment
NodeList namedTags = newDoc.getElementsByTagNameNS(tagNamespaceURI,
tagName);
for (int i = 0; i < namedTags.getLength(); i++) {
// Add the attribute to each one
Element element = (Element) namedTags.item(i);
element.setAttribute(attrName, attrValue);
}
// displayNode(newDoc);
return (Node) newDoc;
} | java | public static Node addDomAttr(Document doc, String tagName,
String tagNamespaceURI, String attrName, String attrValue) {
// Create a Document to work on
Document newDoc = null;
try {
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
newDoc = db.newDocument();
} catch (Exception e) {
e.printStackTrace();
// Fortify Mod: If we got here there is no point going any further
return null;
}
Transformer identity = null;
try {
TransformerFactory TF = TransformerFactory.newInstance();
// Fortify Mod: disable external entity injection
TF.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
identity = TF.newTransformer();
// End Fortify Mod
identity.transform(new DOMSource(doc), new DOMResult(newDoc));
} catch (Exception ex) {
System.out.println("ERROR: " + ex.getMessage());
}
// Get all named nodes in the doucment
NodeList namedTags = newDoc.getElementsByTagNameNS(tagNamespaceURI,
tagName);
for (int i = 0; i < namedTags.getLength(); i++) {
// Add the attribute to each one
Element element = (Element) namedTags.item(i);
element.setAttribute(attrName, attrValue);
}
// displayNode(newDoc);
return (Node) newDoc;
} | [
"public",
"static",
"Node",
"addDomAttr",
"(",
"Document",
"doc",
",",
"String",
"tagName",
",",
"String",
"tagNamespaceURI",
",",
"String",
"attrName",
",",
"String",
"attrValue",
")",
"{",
"// Create a Document to work on\r",
"Document",
"newDoc",
"=",
"null",
"... | Adds the attribute to each node in the Document with the given name.
@param doc
the Document to add attributes to
@param tagName
the local name of the nodes to add the attribute to
@param tagNamespaceURI
the namespace uri of the nodes to add the attribute to
@param attrName
the name of the attribute to add
@param attrValue
the value of the attribute to add
@return the original Document with the update attribute nodes | [
"Adds",
"the",
"attribute",
"to",
"each",
"node",
"in",
"the",
"Document",
"with",
"the",
"given",
"name",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/DomUtils.java#L67-L108 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/DomUtils.java | DomUtils.checkCommentNodes | public static boolean checkCommentNodes(Node node, String str) {
// Get nodes of node and go through them
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
NodeList childChildren = child.getChildNodes();
if (childChildren.getLength() > 0) {
// Recurse for all children
boolean okDownThere = checkCommentNodes(child, str);
if (okDownThere == true) {
return true;
}
}
// Investigate comments
if (child.getNodeType() == Node.COMMENT_NODE) {
// If we got a comment that contains the string we are happy
Comment comment = (Comment) child;
if (comment.getNodeValue().contains(str)) {
return true;
}
}
}
return false;
} | java | public static boolean checkCommentNodes(Node node, String str) {
// Get nodes of node and go through them
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
NodeList childChildren = child.getChildNodes();
if (childChildren.getLength() > 0) {
// Recurse for all children
boolean okDownThere = checkCommentNodes(child, str);
if (okDownThere == true) {
return true;
}
}
// Investigate comments
if (child.getNodeType() == Node.COMMENT_NODE) {
// If we got a comment that contains the string we are happy
Comment comment = (Comment) child;
if (comment.getNodeValue().contains(str)) {
return true;
}
}
}
return false;
} | [
"public",
"static",
"boolean",
"checkCommentNodes",
"(",
"Node",
"node",
",",
"String",
"str",
")",
"{",
"// Get nodes of node and go through them\r",
"NodeList",
"children",
"=",
"node",
".",
"getChildNodes",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
"... | Determines if there is a comment Node that contains the given string.
@param node
the Node to look in
@param str
the string value to match in the comment nodes
CTL declaration, if we ever want to use it <!--Sample Usage:
ctl:checkCommentNodes($xml.resp, 'complexContent')-->
<ctl:function name="ctl:checkCommentNodes"> <ctl:param
name="node"/> <ctl:param name="string"/>
<ctl:description>Checks a Node for comments that contain the
given string.</ctl:description> <ctl:java
class="com.occamlab.te.util.DomUtils"
method="checkCommentNodes"/> </ctl:function>
@return the original Document with the update attribute nodes | [
"Determines",
"if",
"there",
"is",
"a",
"comment",
"Node",
"that",
"contains",
"the",
"given",
"string",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/DomUtils.java#L129-L153 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/DomUtils.java | DomUtils.serializeNoNS | public static String serializeNoNS(Node node) {
StringBuffer buf = new StringBuffer();
buf.append("<");
buf.append(node.getLocalName());
for (Entry<QName, String> entry : getAttributes(node).entrySet()) {
QName name = entry.getKey();
if (name.getNamespaceURI() != null) {
buf.append(" ");
buf.append(name.getLocalPart());
buf.append("=\"");
buf.append(entry.getValue());
buf.append("\"");
}
}
boolean tagOpen = true;
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node n = children.item(i);
short type = node.getNodeType();
if (type == Node.TEXT_NODE) {
if (tagOpen) {
buf.append(">\n");
tagOpen = false;
}
buf.append(node.getTextContent());
} else if (type == Node.ELEMENT_NODE) {
if (tagOpen) {
buf.append(">\n");
tagOpen = false;
}
buf.append(serializeNoNS(n));
buf.append("\n");
}
}
if (tagOpen) {
buf.append("/>\n");
} else {
buf.append("</");
buf.append(node.getLocalName());
buf.append(">\n");
}
return buf.toString();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// try {
// TransformerFactory factory = TransformerFactory.newInstance();
// File f = Misc.getResourceAsFile("com/occamlab/te/drop-ns.xsl");
// Transformer transformer = factory.newTransformer(new
// StreamSource(f));
//
// DOMSource src = new DOMSource(node);
// StreamResult dest = new StreamResult(baos);
// transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
// "yes");
// transformer.transform(src, dest);
// } catch (Exception e) {
// System.out.println("Error serializing node. "+e.getMessage());
// }
//
// return baos.toString();
} | java | public static String serializeNoNS(Node node) {
StringBuffer buf = new StringBuffer();
buf.append("<");
buf.append(node.getLocalName());
for (Entry<QName, String> entry : getAttributes(node).entrySet()) {
QName name = entry.getKey();
if (name.getNamespaceURI() != null) {
buf.append(" ");
buf.append(name.getLocalPart());
buf.append("=\"");
buf.append(entry.getValue());
buf.append("\"");
}
}
boolean tagOpen = true;
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node n = children.item(i);
short type = node.getNodeType();
if (type == Node.TEXT_NODE) {
if (tagOpen) {
buf.append(">\n");
tagOpen = false;
}
buf.append(node.getTextContent());
} else if (type == Node.ELEMENT_NODE) {
if (tagOpen) {
buf.append(">\n");
tagOpen = false;
}
buf.append(serializeNoNS(n));
buf.append("\n");
}
}
if (tagOpen) {
buf.append("/>\n");
} else {
buf.append("</");
buf.append(node.getLocalName());
buf.append(">\n");
}
return buf.toString();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// try {
// TransformerFactory factory = TransformerFactory.newInstance();
// File f = Misc.getResourceAsFile("com/occamlab/te/drop-ns.xsl");
// Transformer transformer = factory.newTransformer(new
// StreamSource(f));
//
// DOMSource src = new DOMSource(node);
// StreamResult dest = new StreamResult(baos);
// transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
// "yes");
// transformer.transform(src, dest);
// } catch (Exception e) {
// System.out.println("Error serializing node. "+e.getMessage());
// }
//
// return baos.toString();
} | [
"public",
"static",
"String",
"serializeNoNS",
"(",
"Node",
"node",
")",
"{",
"StringBuffer",
"buf",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"buf",
".",
"append",
"(",
"\"<\"",
")",
";",
"buf",
".",
"append",
"(",
"node",
".",
"getLocalName",
"(",
"... | Serializes a Node to a String | [
"Serializes",
"a",
"Node",
"to",
"a",
"String"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/DomUtils.java#L189-L248 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/DomUtils.java | DomUtils.displayNode | static public void displayNode(Node node) {
try {
TransformerFactory TF = TransformerFactory.newInstance();
// Fortify Mod: disable external entity injection
TF.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer identity = TF.newTransformer();
// End Fortify Mod
identity.transform(new DOMSource(node),
new StreamResult(System.out));
} catch (Exception ex) {
System.out.println("ERROR: " + ex.getMessage());
}
} | java | static public void displayNode(Node node) {
try {
TransformerFactory TF = TransformerFactory.newInstance();
// Fortify Mod: disable external entity injection
TF.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer identity = TF.newTransformer();
// End Fortify Mod
identity.transform(new DOMSource(node),
new StreamResult(System.out));
} catch (Exception ex) {
System.out.println("ERROR: " + ex.getMessage());
}
} | [
"static",
"public",
"void",
"displayNode",
"(",
"Node",
"node",
")",
"{",
"try",
"{",
"TransformerFactory",
"TF",
"=",
"TransformerFactory",
".",
"newInstance",
"(",
")",
";",
"// Fortify Mod: disable external entity injection\r",
"TF",
".",
"setFeature",
"(",
"XMLC... | HELPER METHOD TO PRINT A DOM TO STDOUT | [
"HELPER",
"METHOD",
"TO",
"PRINT",
"A",
"DOM",
"TO",
"STDOUT"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/DomUtils.java#L251-L263 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/DomUtils.java | DomUtils.convertToElementNode | public static Document convertToElementNode(String xmlString) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
// Fortify Mod: Disable entity expansion to foil External Entity Injections
dbf.setExpandEntityReferences(false);
Document doc = dbf.newDocumentBuilder().newDocument();
if (xmlString != null) {
// Fortify Mod: disable external entity injection
TransformerFactory tf = TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer t = tf.newTransformer();
// End Fortify Mod
t.transform(new StreamSource(new StringReader(xmlString)), new DOMResult(doc));
}
return doc;
} | java | public static Document convertToElementNode(String xmlString) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
// Fortify Mod: Disable entity expansion to foil External Entity Injections
dbf.setExpandEntityReferences(false);
Document doc = dbf.newDocumentBuilder().newDocument();
if (xmlString != null) {
// Fortify Mod: disable external entity injection
TransformerFactory tf = TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer t = tf.newTransformer();
// End Fortify Mod
t.transform(new StreamSource(new StringReader(xmlString)), new DOMResult(doc));
}
return doc;
} | [
"public",
"static",
"Document",
"convertToElementNode",
"(",
"String",
"xmlString",
")",
"throws",
"Exception",
"{",
"DocumentBuilderFactory",
"dbf",
"=",
"DocumentBuilderFactory",
".",
"newInstance",
"(",
")",
";",
"dbf",
".",
"setNamespaceAware",
"(",
"true",
")",... | Convert text node to element.
@param xmlString
@return Return the document object.
@throws Exception | [
"Convert",
"text",
"node",
"to",
"element",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/DomUtils.java#L416-L431 | train |
opengeospatial/teamengine | teamengine-web/src/main/java/com/occamlab/te/web/ConfigFileCreator.java | ConfigFileCreator.create | public void create(File tebase) throws TEException {
try {
create(tebase.toString() + File.separator);
} catch (Exception e) {
throw e;
}
} | java | public void create(File tebase) throws TEException {
try {
create(tebase.toString() + File.separator);
} catch (Exception e) {
throw e;
}
} | [
"public",
"void",
"create",
"(",
"File",
"tebase",
")",
"throws",
"TEException",
"{",
"try",
"{",
"create",
"(",
"tebase",
".",
"toString",
"(",
")",
"+",
"File",
".",
"separator",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"e"... | Creates the main config file.
@param tebase | [
"Creates",
"the",
"main",
"config",
"file",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-web/src/main/java/com/occamlab/te/web/ConfigFileCreator.java#L93-L99 | train |
opengeospatial/teamengine | teamengine-web/src/main/java/com/occamlab/te/web/ConfigFileCreator.java | ConfigFileCreator.getConfigFiles | private List<File> getConfigFiles(File dir) {
String[] extensions = { "xml" };
List<File> configFiles = new ArrayList<File>();
Collection<File> files = FileUtils.listFiles(dir, extensions, true);
for (Iterator<File> iterator = files.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
if (file.getName().equals("config.xml")) {
configFiles.add(file);
}
}
return configFiles;
} | java | private List<File> getConfigFiles(File dir) {
String[] extensions = { "xml" };
List<File> configFiles = new ArrayList<File>();
Collection<File> files = FileUtils.listFiles(dir, extensions, true);
for (Iterator<File> iterator = files.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
if (file.getName().equals("config.xml")) {
configFiles.add(file);
}
}
return configFiles;
} | [
"private",
"List",
"<",
"File",
">",
"getConfigFiles",
"(",
"File",
"dir",
")",
"{",
"String",
"[",
"]",
"extensions",
"=",
"{",
"\"xml\"",
"}",
";",
"List",
"<",
"File",
">",
"configFiles",
"=",
"new",
"ArrayList",
"<",
"File",
">",
"(",
")",
";",
... | Returns the all config file found under a directory
@param dir
@return A list of files found. Length = 0 if not found files. | [
"Returns",
"the",
"all",
"config",
"file",
"found",
"under",
"a",
"directory"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-web/src/main/java/com/occamlab/te/web/ConfigFileCreator.java#L245-L258 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/SchematronValidatingParser.java | SchematronValidatingParser.checkSchematronRules | public boolean checkSchematronRules(Document doc, String schemaFile,
String phase) throws Exception {
boolean isValid = false;
if (doc == null || doc.getDocumentElement() == null)
return isValid;
try {
ClassLoader loader = this.getClass().getClassLoader();
URL url = loader.getResource(schemaFile);
this.schemaFile = new File(
URLDecoder.decode(url.getFile(), "UTF-8"));
} catch (Exception e) {
assert false : "Entity body not found. " + e.toString();
}
this.phase = phase;
Document returnDoc = parse(doc, null, null);
if (returnDoc != null) {
isValid = true;
}
return isValid;
} | java | public boolean checkSchematronRules(Document doc, String schemaFile,
String phase) throws Exception {
boolean isValid = false;
if (doc == null || doc.getDocumentElement() == null)
return isValid;
try {
ClassLoader loader = this.getClass().getClassLoader();
URL url = loader.getResource(schemaFile);
this.schemaFile = new File(
URLDecoder.decode(url.getFile(), "UTF-8"));
} catch (Exception e) {
assert false : "Entity body not found. " + e.toString();
}
this.phase = phase;
Document returnDoc = parse(doc, null, null);
if (returnDoc != null) {
isValid = true;
}
return isValid;
} | [
"public",
"boolean",
"checkSchematronRules",
"(",
"Document",
"doc",
",",
"String",
"schemaFile",
",",
"String",
"phase",
")",
"throws",
"Exception",
"{",
"boolean",
"isValid",
"=",
"false",
";",
"if",
"(",
"doc",
"==",
"null",
"||",
"doc",
".",
"getDocument... | Checks the given schematron phase for the XML file and returns the
validation status.
@param doc
The XML file to validate (Document)
@param schemaFile
The string path to the schematron file to use
@param phase
The string phase name (contained in schematron file)
@return Whether there were validation errors or not (boolean) | [
"Checks",
"the",
"given",
"schematron",
"phase",
"for",
"the",
"XML",
"file",
"and",
"returns",
"the",
"validation",
"status",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/SchematronValidatingParser.java#L162-L183 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/SchematronValidatingParser.java | SchematronValidatingParser.executeSchematronDriver | public boolean executeSchematronDriver(InputSource inputDoc,
File schemaFile, String phase) {
boolean isValid = false;
ValidationDriver driver = createSchematronDriver(phase);
assert null != driver : "Unable to create Schematron ValidationDriver";
InputSource is = null;
// Fortify Mod: move fis out so it can be closed on exit
FileInputStream fis = null;
try {
// FileInputStream fis = new FileInputStream(schemaFile);
fis = new FileInputStream(schemaFile);
is = new InputSource(fis);
} catch (Exception e) {
e.printStackTrace();
}
try {
if (driver.loadSchema(is)) {
isValid = driver.validate(inputDoc);
fis.close(); // Fortify addition
} else {
assert false : ("Failed to load Schematron schema: "
+ schemaFile + "\nIs the schema valid? Is the phase defined?");
}
} catch (SAXException e) {
assert false : e.toString();
} catch (IOException e) {
assert false : e.toString();
}
return isValid;
} | java | public boolean executeSchematronDriver(InputSource inputDoc,
File schemaFile, String phase) {
boolean isValid = false;
ValidationDriver driver = createSchematronDriver(phase);
assert null != driver : "Unable to create Schematron ValidationDriver";
InputSource is = null;
// Fortify Mod: move fis out so it can be closed on exit
FileInputStream fis = null;
try {
// FileInputStream fis = new FileInputStream(schemaFile);
fis = new FileInputStream(schemaFile);
is = new InputSource(fis);
} catch (Exception e) {
e.printStackTrace();
}
try {
if (driver.loadSchema(is)) {
isValid = driver.validate(inputDoc);
fis.close(); // Fortify addition
} else {
assert false : ("Failed to load Schematron schema: "
+ schemaFile + "\nIs the schema valid? Is the phase defined?");
}
} catch (SAXException e) {
assert false : e.toString();
} catch (IOException e) {
assert false : e.toString();
}
return isValid;
} | [
"public",
"boolean",
"executeSchematronDriver",
"(",
"InputSource",
"inputDoc",
",",
"File",
"schemaFile",
",",
"String",
"phase",
")",
"{",
"boolean",
"isValid",
"=",
"false",
";",
"ValidationDriver",
"driver",
"=",
"createSchematronDriver",
"(",
"phase",
")",
";... | Runs the schematron file against the input source. | [
"Runs",
"the",
"schematron",
"file",
"against",
"the",
"input",
"source",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/SchematronValidatingParser.java#L217-L247 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/SchematronValidatingParser.java | SchematronValidatingParser.parse | Document parse(Document doc, Element instruction, PrintWriter logger)
throws Exception {
this.outputLogger = logger;
if (instruction != null) {
getFileType(instruction);
if (type.equals("url")) {
URL schemaURL = new URL(this.schemaLocation);
this.schemaFile = new File(schemaURL.toURI());
} else if (type.equals("file")) {
this.schemaFile = new File(this.schemaLocation);
} else if (type.equals("resource")) {
URL url = this.getClass().getResource(this.schemaLocation);
this.schemaFile = new File(URLDecoder.decode(url.getFile(),
"UTF-8"));
}
}
boolean isValid = false;
if (doc != null) {
InputSource xmlInputSource = null;
try {
InputStream inputStream = DocumentToInputStream(doc);
xmlInputSource = new InputSource(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
isValid = executeSchematronDriver(xmlInputSource, this.schemaFile,
this.phase);
}
if (!isValid) {
return null;
} else {
return doc;
}
} | java | Document parse(Document doc, Element instruction, PrintWriter logger)
throws Exception {
this.outputLogger = logger;
if (instruction != null) {
getFileType(instruction);
if (type.equals("url")) {
URL schemaURL = new URL(this.schemaLocation);
this.schemaFile = new File(schemaURL.toURI());
} else if (type.equals("file")) {
this.schemaFile = new File(this.schemaLocation);
} else if (type.equals("resource")) {
URL url = this.getClass().getResource(this.schemaLocation);
this.schemaFile = new File(URLDecoder.decode(url.getFile(),
"UTF-8"));
}
}
boolean isValid = false;
if (doc != null) {
InputSource xmlInputSource = null;
try {
InputStream inputStream = DocumentToInputStream(doc);
xmlInputSource = new InputSource(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
isValid = executeSchematronDriver(xmlInputSource, this.schemaFile,
this.phase);
}
if (!isValid) {
return null;
} else {
return doc;
}
} | [
"Document",
"parse",
"(",
"Document",
"doc",
",",
"Element",
"instruction",
",",
"PrintWriter",
"logger",
")",
"throws",
"Exception",
"{",
"this",
".",
"outputLogger",
"=",
"logger",
";",
"if",
"(",
"instruction",
"!=",
"null",
")",
"{",
"getFileType",
"(",
... | Checks the given Document against a Schematron schema. A schema reference
is conveyed by a DOM Element node as indicated below.
<pre>
{@code
<tep:schemas xmlns:tep="http://www.occamlab.com/te/parsers">
<tep:schema type="resource" phase="#ALL">/class/path/schema1.sch</tep:schema>
</tep:schemas>
}
</pre>
@param doc
The document to be validated.
@param instruction
An Element containing schema information.
@param logger
A Writer used for logging error messages.
@return The valid document, or {@code null} if any errors were detected.
@throws Exception | [
"Checks",
"the",
"given",
"Document",
"against",
"a",
"Schematron",
"schema",
".",
"A",
"schema",
"reference",
"is",
"conveyed",
"by",
"a",
"DOM",
"Element",
"node",
"as",
"indicated",
"below",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/SchematronValidatingParser.java#L348-L381 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/SchematronValidatingParser.java | SchematronValidatingParser.createDriver | ValidationDriver createDriver(PropertyMap configProps) {
SchemaReaderLoader loader = new SchemaReaderLoader();
SchemaReader schReader = loader.createSchemaReader(SCHEMATRON_NS_URI);
ValidationDriver validator = new ValidationDriver(configProps,
schReader);
return validator;
} | java | ValidationDriver createDriver(PropertyMap configProps) {
SchemaReaderLoader loader = new SchemaReaderLoader();
SchemaReader schReader = loader.createSchemaReader(SCHEMATRON_NS_URI);
ValidationDriver validator = new ValidationDriver(configProps,
schReader);
return validator;
} | [
"ValidationDriver",
"createDriver",
"(",
"PropertyMap",
"configProps",
")",
"{",
"SchemaReaderLoader",
"loader",
"=",
"new",
"SchemaReaderLoader",
"(",
")",
";",
"SchemaReader",
"schReader",
"=",
"loader",
".",
"createSchemaReader",
"(",
"SCHEMATRON_NS_URI",
")",
";",... | Creates and initializes a ValidationDriver to perform Schematron
validation. A schema must be loaded before an instance can be validated.
@param configProps
A PropertyMap containing properties to configure schema
construction and validation behavior; it typically includes
{@code SchematronProperty} and {@code ValidationProperty}
items.
@return A ValidationDriver that is ready to load a Schematron schema. | [
"Creates",
"and",
"initializes",
"a",
"ValidationDriver",
"to",
"perform",
"Schematron",
"validation",
".",
"A",
"schema",
"must",
"be",
"loaded",
"before",
"an",
"instance",
"can",
"be",
"validated",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/SchematronValidatingParser.java#L451-L457 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/ImageParser.java | ImageParser.getImageWidth | public static int getImageWidth(String imageLoc) {
// Get the image as an InputStream
InputStream is = null;
try {
URI imageUri = new URI(imageLoc);
URL imageUrl = imageUri.toURL();
is = imageUrl.openStream();
} catch (Exception e) {
jlogger.log(Level.SEVERE, "getImageWidth", e);
return -1;
}
// Determine the image width
try {
// Create an image input stream on the image
ImageInputStream iis = ImageIO.createImageInputStream(is);
// Find all image readers that recognize the image format
Iterator iter = ImageIO.getImageReaders(iis);
// No readers found
if (!iter.hasNext()) {
return -1;
}
// Use the first reader
ImageReader reader = (ImageReader) iter.next();
reader.setInput(iis, true);
int width = reader.getWidth(0);
iis.close();
return width;
} catch (IOException e) {
jlogger.log(Level.SEVERE, "getImageWidth", e);
// The image could not be read
}
return -1;
} | java | public static int getImageWidth(String imageLoc) {
// Get the image as an InputStream
InputStream is = null;
try {
URI imageUri = new URI(imageLoc);
URL imageUrl = imageUri.toURL();
is = imageUrl.openStream();
} catch (Exception e) {
jlogger.log(Level.SEVERE, "getImageWidth", e);
return -1;
}
// Determine the image width
try {
// Create an image input stream on the image
ImageInputStream iis = ImageIO.createImageInputStream(is);
// Find all image readers that recognize the image format
Iterator iter = ImageIO.getImageReaders(iis);
// No readers found
if (!iter.hasNext()) {
return -1;
}
// Use the first reader
ImageReader reader = (ImageReader) iter.next();
reader.setInput(iis, true);
int width = reader.getWidth(0);
iis.close();
return width;
} catch (IOException e) {
jlogger.log(Level.SEVERE, "getImageWidth", e);
// The image could not be read
}
return -1;
} | [
"public",
"static",
"int",
"getImageWidth",
"(",
"String",
"imageLoc",
")",
"{",
"// Get the image as an InputStream",
"InputStream",
"is",
"=",
"null",
";",
"try",
"{",
"URI",
"imageUri",
"=",
"new",
"URI",
"(",
"imageLoc",
")",
";",
"URL",
"imageUrl",
"=",
... | Determines the width of the first image in an image file in pixels.
@param imageLoc
the string location of the image (uri syntax expected)
@return int the image width in pixels, or -1 if unable.
@author Paul Daisey added 2011-05-13 to support WMTS ETS | [
"Determines",
"the",
"width",
"of",
"the",
"first",
"image",
"in",
"an",
"image",
"file",
"in",
"pixels",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/ImageParser.java#L393-L431 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/LogUtils.java | LogUtils.createLog | public static PrintWriter createLog(File logDir, String callpath)
throws Exception {
if (logDir != null) {
File dir = new File(logDir, callpath);
String path=logDir.toString() + "/" + callpath.split("/")[0];
System.setProperty("PATH", path);
dir.mkdir();
File f = new File(dir, "log.xml");
f.delete();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(f), "UTF-8"));
return new PrintWriter(writer);
}
return null;
} | java | public static PrintWriter createLog(File logDir, String callpath)
throws Exception {
if (logDir != null) {
File dir = new File(logDir, callpath);
String path=logDir.toString() + "/" + callpath.split("/")[0];
System.setProperty("PATH", path);
dir.mkdir();
File f = new File(dir, "log.xml");
f.delete();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(f), "UTF-8"));
return new PrintWriter(writer);
}
return null;
} | [
"public",
"static",
"PrintWriter",
"createLog",
"(",
"File",
"logDir",
",",
"String",
"callpath",
")",
"throws",
"Exception",
"{",
"if",
"(",
"logDir",
"!=",
"null",
")",
"{",
"File",
"dir",
"=",
"new",
"File",
"(",
"logDir",
",",
"callpath",
")",
";",
... | Creates a Writer used to write test results to the log.xml file.
@param logDir
The directory containing the test session results.
@param callpath
A test session identifier.
@return A PrintWriter object, or {@code null} if one could not be
created.
@throws Exception | [
"Creates",
"a",
"Writer",
"used",
"to",
"write",
"test",
"results",
"to",
"the",
"log",
".",
"xml",
"file",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/LogUtils.java#L70-L84 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/LogUtils.java | LogUtils.readLog | public static Document readLog(File logDir, String callpath)
throws Exception {
File dir = new File(logDir, callpath);
File f = new File(dir, "log.xml");
if (f.exists()) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
// Fortify Mod: Disable entity expansion to foil External Entity Injections
dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
TransformerFactory tf = TransformerFactory.newInstance();
// Fortify Mod: prevent external entity injection
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer t = tf.newTransformer();
t.setErrorListener(new com.occamlab.te.NullErrorListener());
try {
t.transform(new StreamSource(f), new DOMResult(doc));
} catch (Exception e) {
// The log may not have been closed properly.
// Try again with a closing </log> tag
RandomAccessFile raf = new RandomAccessFile(f, "r");
int l = new Long(raf.length()).intValue();
byte[] buf = new byte[l + 8];
raf.read(buf);
raf.close();
buf[l] = '\n';
buf[l + 1] = '<';
buf[l + 2] = '/';
buf[l + 3] = 'l';
buf[l + 4] = 'o';
buf[l + 5] = 'g';
buf[l + 6] = '>';
buf[l + 7] = '\n';
doc = db.newDocument();
tf.newTransformer().transform(
new StreamSource(new ByteArrayInputStream(buf)),
new DOMResult(doc));
}
return doc;
} else {
return null;
}
} | java | public static Document readLog(File logDir, String callpath)
throws Exception {
File dir = new File(logDir, callpath);
File f = new File(dir, "log.xml");
if (f.exists()) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
// Fortify Mod: Disable entity expansion to foil External Entity Injections
dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
TransformerFactory tf = TransformerFactory.newInstance();
// Fortify Mod: prevent external entity injection
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer t = tf.newTransformer();
t.setErrorListener(new com.occamlab.te.NullErrorListener());
try {
t.transform(new StreamSource(f), new DOMResult(doc));
} catch (Exception e) {
// The log may not have been closed properly.
// Try again with a closing </log> tag
RandomAccessFile raf = new RandomAccessFile(f, "r");
int l = new Long(raf.length()).intValue();
byte[] buf = new byte[l + 8];
raf.read(buf);
raf.close();
buf[l] = '\n';
buf[l + 1] = '<';
buf[l + 2] = '/';
buf[l + 3] = 'l';
buf[l + 4] = 'o';
buf[l + 5] = 'g';
buf[l + 6] = '>';
buf[l + 7] = '\n';
doc = db.newDocument();
tf.newTransformer().transform(
new StreamSource(new ByteArrayInputStream(buf)),
new DOMResult(doc));
}
return doc;
} else {
return null;
}
} | [
"public",
"static",
"Document",
"readLog",
"(",
"File",
"logDir",
",",
"String",
"callpath",
")",
"throws",
"Exception",
"{",
"File",
"dir",
"=",
"new",
"File",
"(",
"logDir",
",",
"callpath",
")",
";",
"File",
"f",
"=",
"new",
"File",
"(",
"dir",
",",... | Reads a log from disk | [
"Reads",
"a",
"log",
"from",
"disk"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/LogUtils.java#L87-L130 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/LogUtils.java | LogUtils.getContextFromLog | public static XdmNode getContextFromLog(
net.sf.saxon.s9api.DocumentBuilder builder, Document log)
throws Exception {
Element starttest = (Element) log.getElementsByTagName("starttest")
.item(0);
NodeList nl = starttest.getElementsByTagName("context");
if (nl == null || nl.getLength() == 0) {
return null;
} else {
Element context = (Element) nl.item(0);
Element value = (Element) context.getElementsByTagName("value")
.item(0);
nl = value.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n.getNodeType() == Node.ATTRIBUTE_NODE) {
String s = DomUtils.serializeNode(value);
XdmNode xn = builder.build(new StreamSource(
new CharArrayReader(s.toCharArray())));
return (XdmNode) xn.axisIterator(Axis.ATTRIBUTE).next();
} else if (n.getNodeType() == Node.ELEMENT_NODE) {
Document doc = DomUtils.createDocument(n);
return builder.build(new DOMSource(doc));
}
}
}
return null;
} | java | public static XdmNode getContextFromLog(
net.sf.saxon.s9api.DocumentBuilder builder, Document log)
throws Exception {
Element starttest = (Element) log.getElementsByTagName("starttest")
.item(0);
NodeList nl = starttest.getElementsByTagName("context");
if (nl == null || nl.getLength() == 0) {
return null;
} else {
Element context = (Element) nl.item(0);
Element value = (Element) context.getElementsByTagName("value")
.item(0);
nl = value.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n.getNodeType() == Node.ATTRIBUTE_NODE) {
String s = DomUtils.serializeNode(value);
XdmNode xn = builder.build(new StreamSource(
new CharArrayReader(s.toCharArray())));
return (XdmNode) xn.axisIterator(Axis.ATTRIBUTE).next();
} else if (n.getNodeType() == Node.ELEMENT_NODE) {
Document doc = DomUtils.createDocument(n);
return builder.build(new DOMSource(doc));
}
}
}
return null;
} | [
"public",
"static",
"XdmNode",
"getContextFromLog",
"(",
"net",
".",
"sf",
".",
"saxon",
".",
"s9api",
".",
"DocumentBuilder",
"builder",
",",
"Document",
"log",
")",
"throws",
"Exception",
"{",
"Element",
"starttest",
"=",
"(",
"Element",
")",
"log",
".",
... | Returns the context node for a test from its log document | [
"Returns",
"the",
"context",
"node",
"for",
"a",
"test",
"from",
"its",
"log",
"document"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/LogUtils.java#L181-L208 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.