id
int32
0
165k
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
26,200
apache/incubator-gobblin
gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/source/extractor/extract/kafka/KafkaExtractor.java
KafkaExtractor.moveToNextPartition
private void moveToNextPartition() { if (this.currentPartitionIdx == INITIAL_PARTITION_IDX) { LOG.info("Pulling topic " + this.topicName); this.currentPartitionIdx = 0; } else { updateStatisticsForCurrentPartition(); this.currentPartitionIdx++; this.currentPartitionRecordCount = 0; this.currentPartitionTotalSize = 0; this.currentPartitionDecodeRecordTime = 0; this.currentPartitionFetchMessageBufferTime = 0; this.currentPartitionReadRecordTime = 0; this.currentPartitionLastSuccessfulRecord = null; } this.messageIterator = null; if (this.currentPartitionIdx < this.partitions.size()) { LOG.info(String.format("Pulling partition %s from offset %d to %d, range=%d", this.getCurrentPartition(), this.nextWatermark.get(this.currentPartitionIdx), this.highWatermark.get(this.currentPartitionIdx), this.highWatermark.get(this.currentPartitionIdx) - this.nextWatermark.get(this.currentPartitionIdx))); switchMetricContextToCurrentPartition(); } if (!allPartitionsFinished()) { this.startFetchEpochTime.put(this.getCurrentPartition(), System.currentTimeMillis()); } }
java
private void moveToNextPartition() { if (this.currentPartitionIdx == INITIAL_PARTITION_IDX) { LOG.info("Pulling topic " + this.topicName); this.currentPartitionIdx = 0; } else { updateStatisticsForCurrentPartition(); this.currentPartitionIdx++; this.currentPartitionRecordCount = 0; this.currentPartitionTotalSize = 0; this.currentPartitionDecodeRecordTime = 0; this.currentPartitionFetchMessageBufferTime = 0; this.currentPartitionReadRecordTime = 0; this.currentPartitionLastSuccessfulRecord = null; } this.messageIterator = null; if (this.currentPartitionIdx < this.partitions.size()) { LOG.info(String.format("Pulling partition %s from offset %d to %d, range=%d", this.getCurrentPartition(), this.nextWatermark.get(this.currentPartitionIdx), this.highWatermark.get(this.currentPartitionIdx), this.highWatermark.get(this.currentPartitionIdx) - this.nextWatermark.get(this.currentPartitionIdx))); switchMetricContextToCurrentPartition(); } if (!allPartitionsFinished()) { this.startFetchEpochTime.put(this.getCurrentPartition(), System.currentTimeMillis()); } }
[ "private", "void", "moveToNextPartition", "(", ")", "{", "if", "(", "this", ".", "currentPartitionIdx", "==", "INITIAL_PARTITION_IDX", ")", "{", "LOG", ".", "info", "(", "\"Pulling topic \"", "+", "this", ".", "topicName", ")", ";", "this", ".", "currentPartitionIdx", "=", "0", ";", "}", "else", "{", "updateStatisticsForCurrentPartition", "(", ")", ";", "this", ".", "currentPartitionIdx", "++", ";", "this", ".", "currentPartitionRecordCount", "=", "0", ";", "this", ".", "currentPartitionTotalSize", "=", "0", ";", "this", ".", "currentPartitionDecodeRecordTime", "=", "0", ";", "this", ".", "currentPartitionFetchMessageBufferTime", "=", "0", ";", "this", ".", "currentPartitionReadRecordTime", "=", "0", ";", "this", ".", "currentPartitionLastSuccessfulRecord", "=", "null", ";", "}", "this", ".", "messageIterator", "=", "null", ";", "if", "(", "this", ".", "currentPartitionIdx", "<", "this", ".", "partitions", ".", "size", "(", ")", ")", "{", "LOG", ".", "info", "(", "String", ".", "format", "(", "\"Pulling partition %s from offset %d to %d, range=%d\"", ",", "this", ".", "getCurrentPartition", "(", ")", ",", "this", ".", "nextWatermark", ".", "get", "(", "this", ".", "currentPartitionIdx", ")", ",", "this", ".", "highWatermark", ".", "get", "(", "this", ".", "currentPartitionIdx", ")", ",", "this", ".", "highWatermark", ".", "get", "(", "this", ".", "currentPartitionIdx", ")", "-", "this", ".", "nextWatermark", ".", "get", "(", "this", ".", "currentPartitionIdx", ")", ")", ")", ";", "switchMetricContextToCurrentPartition", "(", ")", ";", "}", "if", "(", "!", "allPartitionsFinished", "(", ")", ")", "{", "this", ".", "startFetchEpochTime", ".", "put", "(", "this", ".", "getCurrentPartition", "(", ")", ",", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "}", "}" ]
Record the avg time per record for the current partition, then increment this.currentPartitionIdx, and switch metric context to the new partition.
[ "Record", "the", "avg", "time", "per", "record", "for", "the", "current", "partition", "then", "increment", "this", ".", "currentPartitionIdx", "and", "switch", "metric", "context", "to", "the", "new", "partition", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/source/extractor/extract/kafka/KafkaExtractor.java#L289-L315
26,201
apache/incubator-gobblin
gobblin-modules/gobblin-http/src/main/java/org/apache/gobblin/writer/AsyncHttpWriter.java
AsyncHttpWriter.onSuccess
protected void onSuccess(AsyncRequest<D, RQ> asyncRequest, ResponseStatus status) { final WriteResponse response = WriteResponse.EMPTY; for (final AsyncRequest.Thunk thunk: asyncRequest.getThunks()) { WriteCallback callback = (WriteCallback) thunk.callback; callback.onSuccess(new WriteResponse() { @Override public Object getRawResponse() { return response.getRawResponse(); } @Override public String getStringResponse() { return response.getStringResponse(); } @Override public long bytesWritten() { return thunk.sizeInBytes; } }); } }
java
protected void onSuccess(AsyncRequest<D, RQ> asyncRequest, ResponseStatus status) { final WriteResponse response = WriteResponse.EMPTY; for (final AsyncRequest.Thunk thunk: asyncRequest.getThunks()) { WriteCallback callback = (WriteCallback) thunk.callback; callback.onSuccess(new WriteResponse() { @Override public Object getRawResponse() { return response.getRawResponse(); } @Override public String getStringResponse() { return response.getStringResponse(); } @Override public long bytesWritten() { return thunk.sizeInBytes; } }); } }
[ "protected", "void", "onSuccess", "(", "AsyncRequest", "<", "D", ",", "RQ", ">", "asyncRequest", ",", "ResponseStatus", "status", ")", "{", "final", "WriteResponse", "response", "=", "WriteResponse", ".", "EMPTY", ";", "for", "(", "final", "AsyncRequest", ".", "Thunk", "thunk", ":", "asyncRequest", ".", "getThunks", "(", ")", ")", "{", "WriteCallback", "callback", "=", "(", "WriteCallback", ")", "thunk", ".", "callback", ";", "callback", ".", "onSuccess", "(", "new", "WriteResponse", "(", ")", "{", "@", "Override", "public", "Object", "getRawResponse", "(", ")", "{", "return", "response", ".", "getRawResponse", "(", ")", ";", "}", "@", "Override", "public", "String", "getStringResponse", "(", ")", "{", "return", "response", ".", "getStringResponse", "(", ")", ";", "}", "@", "Override", "public", "long", "bytesWritten", "(", ")", "{", "return", "thunk", ".", "sizeInBytes", ";", "}", "}", ")", ";", "}", "}" ]
Callback on sending the asyncRequest successfully
[ "Callback", "on", "sending", "the", "asyncRequest", "successfully" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-http/src/main/java/org/apache/gobblin/writer/AsyncHttpWriter.java#L139-L160
26,202
apache/incubator-gobblin
gobblin-modules/gobblin-http/src/main/java/org/apache/gobblin/writer/AsyncHttpWriter.java
AsyncHttpWriter.onFailure
@Deprecated protected void onFailure(AsyncRequest<D, RQ> asyncRequest, Throwable throwable) { for (AsyncRequest.Thunk thunk: asyncRequest.getThunks()) { thunk.callback.onFailure(throwable); } }
java
@Deprecated protected void onFailure(AsyncRequest<D, RQ> asyncRequest, Throwable throwable) { for (AsyncRequest.Thunk thunk: asyncRequest.getThunks()) { thunk.callback.onFailure(throwable); } }
[ "@", "Deprecated", "protected", "void", "onFailure", "(", "AsyncRequest", "<", "D", ",", "RQ", ">", "asyncRequest", ",", "Throwable", "throwable", ")", "{", "for", "(", "AsyncRequest", ".", "Thunk", "thunk", ":", "asyncRequest", ".", "getThunks", "(", ")", ")", "{", "thunk", ".", "callback", ".", "onFailure", "(", "throwable", ")", ";", "}", "}" ]
Callback on failing to send the asyncRequest @deprecated Use {@link #onFailure(AsyncRequest, DispatchException)}
[ "Callback", "on", "failing", "to", "send", "the", "asyncRequest" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-http/src/main/java/org/apache/gobblin/writer/AsyncHttpWriter.java#L167-L172
26,203
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/task/TaskIFaceWrapper.java
TaskIFaceWrapper.cancel
@Override public synchronized boolean cancel() { if (this.taskFuture != null && this.taskFuture.cancel(true)) { this.taskStateTracker.onTaskRunCompletion(this); return true; } else { return false; } }
java
@Override public synchronized boolean cancel() { if (this.taskFuture != null && this.taskFuture.cancel(true)) { this.taskStateTracker.onTaskRunCompletion(this); return true; } else { return false; } }
[ "@", "Override", "public", "synchronized", "boolean", "cancel", "(", ")", "{", "if", "(", "this", ".", "taskFuture", "!=", "null", "&&", "this", ".", "taskFuture", ".", "cancel", "(", "true", ")", ")", "{", "this", ".", "taskStateTracker", ".", "onTaskRunCompletion", "(", "this", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
return true if the task is successfully cancelled. This method is a copy of the method in parent class. We need this copy so TaskIFaceWrapper variables are not shared between this class and its parent class @return
[ "return", "true", "if", "the", "task", "is", "successfully", "cancelled", ".", "This", "method", "is", "a", "copy", "of", "the", "method", "in", "parent", "class", ".", "We", "need", "this", "copy", "so", "TaskIFaceWrapper", "variables", "are", "not", "shared", "between", "this", "class", "and", "its", "parent", "class" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/task/TaskIFaceWrapper.java#L180-L188
26,204
apache/incubator-gobblin
gobblin-core-base/src/main/java/org/apache/gobblin/converter/filter/AvroProjectionConverter.java
AvroProjectionConverter.convertSchema
@Override public Schema convertSchema(Schema inputSchema, WorkUnitState workUnit) throws SchemaConversionException { if (this.fieldRemover.isPresent()) { return this.fieldRemover.get().removeFields(inputSchema); } return inputSchema; }
java
@Override public Schema convertSchema(Schema inputSchema, WorkUnitState workUnit) throws SchemaConversionException { if (this.fieldRemover.isPresent()) { return this.fieldRemover.get().removeFields(inputSchema); } return inputSchema; }
[ "@", "Override", "public", "Schema", "convertSchema", "(", "Schema", "inputSchema", ",", "WorkUnitState", "workUnit", ")", "throws", "SchemaConversionException", "{", "if", "(", "this", ".", "fieldRemover", ".", "isPresent", "(", ")", ")", "{", "return", "this", ".", "fieldRemover", ".", "get", "(", ")", ".", "removeFields", "(", "inputSchema", ")", ";", "}", "return", "inputSchema", ";", "}" ]
Remove the specified fields from inputSchema.
[ "Remove", "the", "specified", "fields", "from", "inputSchema", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core-base/src/main/java/org/apache/gobblin/converter/filter/AvroProjectionConverter.java#L70-L76
26,205
apache/incubator-gobblin
gobblin-core-base/src/main/java/org/apache/gobblin/converter/filter/AvroProjectionConverter.java
AvroProjectionConverter.convertRecordImpl
@Override public Iterable<GenericRecord> convertRecordImpl(Schema outputSchema, GenericRecord inputRecord, WorkUnitState workUnit) throws DataConversionException { try { return new SingleRecordIterable<>(AvroUtils.convertRecordSchema(inputRecord, outputSchema)); } catch (IOException e) { throw new DataConversionException(e); } }
java
@Override public Iterable<GenericRecord> convertRecordImpl(Schema outputSchema, GenericRecord inputRecord, WorkUnitState workUnit) throws DataConversionException { try { return new SingleRecordIterable<>(AvroUtils.convertRecordSchema(inputRecord, outputSchema)); } catch (IOException e) { throw new DataConversionException(e); } }
[ "@", "Override", "public", "Iterable", "<", "GenericRecord", ">", "convertRecordImpl", "(", "Schema", "outputSchema", ",", "GenericRecord", "inputRecord", ",", "WorkUnitState", "workUnit", ")", "throws", "DataConversionException", "{", "try", "{", "return", "new", "SingleRecordIterable", "<>", "(", "AvroUtils", ".", "convertRecordSchema", "(", "inputRecord", ",", "outputSchema", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "DataConversionException", "(", "e", ")", ";", "}", "}" ]
Convert the schema of inputRecord to outputSchema.
[ "Convert", "the", "schema", "of", "inputRecord", "to", "outputSchema", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core-base/src/main/java/org/apache/gobblin/converter/filter/AvroProjectionConverter.java#L81-L89
26,206
apache/incubator-gobblin
gobblin-modules/google-ingestion/src/main/java/org/apache/gobblin/ingestion/google/webmaster/GoogleWebmasterDataFetcherImpl.java
GoogleWebmasterDataFetcherImpl.getPages
private Collection<String> getPages(String startDate, String endDate, List<Dimension> dimensions, ApiDimensionFilter countryFilter, Queue<Pair<String, FilterOperator>> toProcess, int rowLimit) { String country = GoogleWebmasterFilter.countryFilterToString(countryFilter); ConcurrentLinkedDeque<String> allPages = new ConcurrentLinkedDeque<>(); int r = 0; while (r <= GET_PAGES_RETRIES) { ++r; log.info(String.format("Get pages at round %d with size %d.", r, toProcess.size())); ConcurrentLinkedDeque<Pair<String, FilterOperator>> nextRound = new ConcurrentLinkedDeque<>(); ExecutorService es = Executors.newFixedThreadPool(10, ExecutorsUtils.newDaemonThreadFactory(Optional.of(log), Optional.of(this.getClass().getSimpleName()))); while (!toProcess.isEmpty()) { submitJob(toProcess.poll(), countryFilter, startDate, endDate, dimensions, es, allPages, nextRound, rowLimit); } //wait for jobs to finish and start next round if necessary. try { es.shutdown(); boolean terminated = es.awaitTermination(5, TimeUnit.MINUTES); if (!terminated) { es.shutdownNow(); log.warn("Timed out while getting all pages for country-{} at round {}. Next round now has size {}.", country, r, nextRound.size()); } } catch (InterruptedException e) { throw new RuntimeException(e); } if (nextRound.isEmpty()) { break; } toProcess = nextRound; coolDown(r, PAGES_GET_COOLDOWN_TIME); } if (r == GET_PAGES_RETRIES + 1) { throw new RuntimeException( String.format("Getting all pages reaches the maximum number of retires %d. Date range: %s ~ %s. Country: %s.", GET_PAGES_RETRIES, startDate, endDate, country)); } return allPages; }
java
private Collection<String> getPages(String startDate, String endDate, List<Dimension> dimensions, ApiDimensionFilter countryFilter, Queue<Pair<String, FilterOperator>> toProcess, int rowLimit) { String country = GoogleWebmasterFilter.countryFilterToString(countryFilter); ConcurrentLinkedDeque<String> allPages = new ConcurrentLinkedDeque<>(); int r = 0; while (r <= GET_PAGES_RETRIES) { ++r; log.info(String.format("Get pages at round %d with size %d.", r, toProcess.size())); ConcurrentLinkedDeque<Pair<String, FilterOperator>> nextRound = new ConcurrentLinkedDeque<>(); ExecutorService es = Executors.newFixedThreadPool(10, ExecutorsUtils.newDaemonThreadFactory(Optional.of(log), Optional.of(this.getClass().getSimpleName()))); while (!toProcess.isEmpty()) { submitJob(toProcess.poll(), countryFilter, startDate, endDate, dimensions, es, allPages, nextRound, rowLimit); } //wait for jobs to finish and start next round if necessary. try { es.shutdown(); boolean terminated = es.awaitTermination(5, TimeUnit.MINUTES); if (!terminated) { es.shutdownNow(); log.warn("Timed out while getting all pages for country-{} at round {}. Next round now has size {}.", country, r, nextRound.size()); } } catch (InterruptedException e) { throw new RuntimeException(e); } if (nextRound.isEmpty()) { break; } toProcess = nextRound; coolDown(r, PAGES_GET_COOLDOWN_TIME); } if (r == GET_PAGES_RETRIES + 1) { throw new RuntimeException( String.format("Getting all pages reaches the maximum number of retires %d. Date range: %s ~ %s. Country: %s.", GET_PAGES_RETRIES, startDate, endDate, country)); } return allPages; }
[ "private", "Collection", "<", "String", ">", "getPages", "(", "String", "startDate", ",", "String", "endDate", ",", "List", "<", "Dimension", ">", "dimensions", ",", "ApiDimensionFilter", "countryFilter", ",", "Queue", "<", "Pair", "<", "String", ",", "FilterOperator", ">", ">", "toProcess", ",", "int", "rowLimit", ")", "{", "String", "country", "=", "GoogleWebmasterFilter", ".", "countryFilterToString", "(", "countryFilter", ")", ";", "ConcurrentLinkedDeque", "<", "String", ">", "allPages", "=", "new", "ConcurrentLinkedDeque", "<>", "(", ")", ";", "int", "r", "=", "0", ";", "while", "(", "r", "<=", "GET_PAGES_RETRIES", ")", "{", "++", "r", ";", "log", ".", "info", "(", "String", ".", "format", "(", "\"Get pages at round %d with size %d.\"", ",", "r", ",", "toProcess", ".", "size", "(", ")", ")", ")", ";", "ConcurrentLinkedDeque", "<", "Pair", "<", "String", ",", "FilterOperator", ">", ">", "nextRound", "=", "new", "ConcurrentLinkedDeque", "<>", "(", ")", ";", "ExecutorService", "es", "=", "Executors", ".", "newFixedThreadPool", "(", "10", ",", "ExecutorsUtils", ".", "newDaemonThreadFactory", "(", "Optional", ".", "of", "(", "log", ")", ",", "Optional", ".", "of", "(", "this", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", ")", ")", ")", ";", "while", "(", "!", "toProcess", ".", "isEmpty", "(", ")", ")", "{", "submitJob", "(", "toProcess", ".", "poll", "(", ")", ",", "countryFilter", ",", "startDate", ",", "endDate", ",", "dimensions", ",", "es", ",", "allPages", ",", "nextRound", ",", "rowLimit", ")", ";", "}", "//wait for jobs to finish and start next round if necessary.", "try", "{", "es", ".", "shutdown", "(", ")", ";", "boolean", "terminated", "=", "es", ".", "awaitTermination", "(", "5", ",", "TimeUnit", ".", "MINUTES", ")", ";", "if", "(", "!", "terminated", ")", "{", "es", ".", "shutdownNow", "(", ")", ";", "log", ".", "warn", "(", "\"Timed out while getting all pages for country-{} at round {}. Next round now has size {}.\"", ",", "country", ",", "r", ",", "nextRound", ".", "size", "(", ")", ")", ";", "}", "}", "catch", "(", "InterruptedException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "if", "(", "nextRound", ".", "isEmpty", "(", ")", ")", "{", "break", ";", "}", "toProcess", "=", "nextRound", ";", "coolDown", "(", "r", ",", "PAGES_GET_COOLDOWN_TIME", ")", ";", "}", "if", "(", "r", "==", "GET_PAGES_RETRIES", "+", "1", ")", "{", "throw", "new", "RuntimeException", "(", "String", ".", "format", "(", "\"Getting all pages reaches the maximum number of retires %d. Date range: %s ~ %s. Country: %s.\"", ",", "GET_PAGES_RETRIES", ",", "startDate", ",", "endDate", ",", "country", ")", ")", ";", "}", "return", "allPages", ";", "}" ]
Get all pages in an async mode.
[ "Get", "all", "pages", "in", "an", "async", "mode", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/google-ingestion/src/main/java/org/apache/gobblin/ingestion/google/webmaster/GoogleWebmasterDataFetcherImpl.java#L216-L257
26,207
apache/incubator-gobblin
gobblin-modules/google-ingestion/src/main/java/org/apache/gobblin/ingestion/google/webmaster/GoogleWebmasterDataFetcherImpl.java
GoogleWebmasterDataFetcherImpl.getUrlPartitions
private ArrayList<String> getUrlPartitions(String prefix) { ArrayList<String> expanded = new ArrayList<>(); //The page prefix is case insensitive, A-Z is not necessary. for (char c = 'a'; c <= 'z'; ++c) { expanded.add(prefix + c); } for (int num = 0; num <= 9; ++num) { expanded.add(prefix + num); } expanded.add(prefix + "-"); expanded.add(prefix + "."); expanded.add(prefix + "_"); //most important expanded.add(prefix + "~"); expanded.add(prefix + "/"); //most important expanded.add(prefix + "%"); //most important expanded.add(prefix + ":"); expanded.add(prefix + "?"); expanded.add(prefix + "#"); expanded.add(prefix + "@"); expanded.add(prefix + "!"); expanded.add(prefix + "$"); expanded.add(prefix + "&"); expanded.add(prefix + "+"); expanded.add(prefix + "*"); expanded.add(prefix + "'"); expanded.add(prefix + "="); return expanded; }
java
private ArrayList<String> getUrlPartitions(String prefix) { ArrayList<String> expanded = new ArrayList<>(); //The page prefix is case insensitive, A-Z is not necessary. for (char c = 'a'; c <= 'z'; ++c) { expanded.add(prefix + c); } for (int num = 0; num <= 9; ++num) { expanded.add(prefix + num); } expanded.add(prefix + "-"); expanded.add(prefix + "."); expanded.add(prefix + "_"); //most important expanded.add(prefix + "~"); expanded.add(prefix + "/"); //most important expanded.add(prefix + "%"); //most important expanded.add(prefix + ":"); expanded.add(prefix + "?"); expanded.add(prefix + "#"); expanded.add(prefix + "@"); expanded.add(prefix + "!"); expanded.add(prefix + "$"); expanded.add(prefix + "&"); expanded.add(prefix + "+"); expanded.add(prefix + "*"); expanded.add(prefix + "'"); expanded.add(prefix + "="); return expanded; }
[ "private", "ArrayList", "<", "String", ">", "getUrlPartitions", "(", "String", "prefix", ")", "{", "ArrayList", "<", "String", ">", "expanded", "=", "new", "ArrayList", "<>", "(", ")", ";", "//The page prefix is case insensitive, A-Z is not necessary.", "for", "(", "char", "c", "=", "'", "'", ";", "c", "<=", "'", "'", ";", "++", "c", ")", "{", "expanded", ".", "add", "(", "prefix", "+", "c", ")", ";", "}", "for", "(", "int", "num", "=", "0", ";", "num", "<=", "9", ";", "++", "num", ")", "{", "expanded", ".", "add", "(", "prefix", "+", "num", ")", ";", "}", "expanded", ".", "add", "(", "prefix", "+", "\"-\"", ")", ";", "expanded", ".", "add", "(", "prefix", "+", "\".\"", ")", ";", "expanded", ".", "add", "(", "prefix", "+", "\"_\"", ")", ";", "//most important", "expanded", ".", "add", "(", "prefix", "+", "\"~\"", ")", ";", "expanded", ".", "add", "(", "prefix", "+", "\"/\"", ")", ";", "//most important", "expanded", ".", "add", "(", "prefix", "+", "\"%\"", ")", ";", "//most important", "expanded", ".", "add", "(", "prefix", "+", "\":\"", ")", ";", "expanded", ".", "add", "(", "prefix", "+", "\"?\"", ")", ";", "expanded", ".", "add", "(", "prefix", "+", "\"#\"", ")", ";", "expanded", ".", "add", "(", "prefix", "+", "\"@\"", ")", ";", "expanded", ".", "add", "(", "prefix", "+", "\"!\"", ")", ";", "expanded", ".", "add", "(", "prefix", "+", "\"$\"", ")", ";", "expanded", ".", "add", "(", "prefix", "+", "\"&\"", ")", ";", "expanded", ".", "add", "(", "prefix", "+", "\"+\"", ")", ";", "expanded", ".", "add", "(", "prefix", "+", "\"*\"", ")", ";", "expanded", ".", "add", "(", "prefix", "+", "\"'\"", ")", ";", "expanded", ".", "add", "(", "prefix", "+", "\"=\"", ")", ";", "return", "expanded", ";", "}" ]
This doesn't cover all cases but more than 99.9% captured. According to the standard (RFC-3986), here are possible characters: unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" reserved = gen-delims / sub-delims gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" Not included: reserved = gen-delims / sub-delims gen-delims = "[" / "]" sub-delims = "(" / ")" / "," / ";"
[ "This", "doesn", "t", "cover", "all", "cases", "but", "more", "than", "99", ".", "9%", "captured", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/google-ingestion/src/main/java/org/apache/gobblin/ingestion/google/webmaster/GoogleWebmasterDataFetcherImpl.java#L323-L351
26,208
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/filesystem/PathAlterationObserver.java
PathAlterationObserver.addListener
public void addListener(final PathAlterationListener listener) { if (listener != null) { this.listeners.put(listener, new ExceptionCatchingPathAlterationListenerDecorator(listener)); } }
java
public void addListener(final PathAlterationListener listener) { if (listener != null) { this.listeners.put(listener, new ExceptionCatchingPathAlterationListenerDecorator(listener)); } }
[ "public", "void", "addListener", "(", "final", "PathAlterationListener", "listener", ")", "{", "if", "(", "listener", "!=", "null", ")", "{", "this", ".", "listeners", ".", "put", "(", "listener", ",", "new", "ExceptionCatchingPathAlterationListenerDecorator", "(", "listener", ")", ")", ";", "}", "}" ]
Add a file system listener. @param listener The file system listener
[ "Add", "a", "file", "system", "listener", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/filesystem/PathAlterationObserver.java#L129-L133
26,209
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/filesystem/PathAlterationObserver.java
PathAlterationObserver.initialize
public void initialize() throws IOException { rootEntry.refresh(rootEntry.getPath()); final FileStatusEntry[] children = doListPathsEntry(rootEntry.getPath(), rootEntry); rootEntry.setChildren(children); }
java
public void initialize() throws IOException { rootEntry.refresh(rootEntry.getPath()); final FileStatusEntry[] children = doListPathsEntry(rootEntry.getPath(), rootEntry); rootEntry.setChildren(children); }
[ "public", "void", "initialize", "(", ")", "throws", "IOException", "{", "rootEntry", ".", "refresh", "(", "rootEntry", ".", "getPath", "(", ")", ")", ";", "final", "FileStatusEntry", "[", "]", "children", "=", "doListPathsEntry", "(", "rootEntry", ".", "getPath", "(", ")", ",", "rootEntry", ")", ";", "rootEntry", ".", "setChildren", "(", "children", ")", ";", "}" ]
Initialize the observer. @throws IOException if an error occurs
[ "Initialize", "the", "observer", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/filesystem/PathAlterationObserver.java#L159-L163
26,210
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/filesystem/PathAlterationObserver.java
PathAlterationObserver.checkAndNotify
public void checkAndNotify() throws IOException { /* fire onStart() */ for (final PathAlterationListener listener : listeners.values()) { listener.onStart(this); } /* fire directory/file events */ final Path rootPath = rootEntry.getPath(); if (fs.exists(rootPath)) { // Current existed. checkAndNotify(rootEntry, rootEntry.getChildren(), listPaths(rootPath)); } else if (rootEntry.isExists()) { // Existed before and not existed now. checkAndNotify(rootEntry, rootEntry.getChildren(), EMPTY_PATH_ARRAY); } else { // Didn't exist and still doesn't } /* fire onStop() */ for (final PathAlterationListener listener : listeners.values()) { listener.onStop(this); } }
java
public void checkAndNotify() throws IOException { /* fire onStart() */ for (final PathAlterationListener listener : listeners.values()) { listener.onStart(this); } /* fire directory/file events */ final Path rootPath = rootEntry.getPath(); if (fs.exists(rootPath)) { // Current existed. checkAndNotify(rootEntry, rootEntry.getChildren(), listPaths(rootPath)); } else if (rootEntry.isExists()) { // Existed before and not existed now. checkAndNotify(rootEntry, rootEntry.getChildren(), EMPTY_PATH_ARRAY); } else { // Didn't exist and still doesn't } /* fire onStop() */ for (final PathAlterationListener listener : listeners.values()) { listener.onStop(this); } }
[ "public", "void", "checkAndNotify", "(", ")", "throws", "IOException", "{", "/* fire onStart() */", "for", "(", "final", "PathAlterationListener", "listener", ":", "listeners", ".", "values", "(", ")", ")", "{", "listener", ".", "onStart", "(", "this", ")", ";", "}", "/* fire directory/file events */", "final", "Path", "rootPath", "=", "rootEntry", ".", "getPath", "(", ")", ";", "if", "(", "fs", ".", "exists", "(", "rootPath", ")", ")", "{", "// Current existed.", "checkAndNotify", "(", "rootEntry", ",", "rootEntry", ".", "getChildren", "(", ")", ",", "listPaths", "(", "rootPath", ")", ")", ";", "}", "else", "if", "(", "rootEntry", ".", "isExists", "(", ")", ")", "{", "// Existed before and not existed now.", "checkAndNotify", "(", "rootEntry", ",", "rootEntry", ".", "getChildren", "(", ")", ",", "EMPTY_PATH_ARRAY", ")", ";", "}", "else", "{", "// Didn't exist and still doesn't", "}", "/* fire onStop() */", "for", "(", "final", "PathAlterationListener", "listener", ":", "listeners", ".", "values", "(", ")", ")", "{", "listener", ".", "onStop", "(", "this", ")", ";", "}", "}" ]
Check whether the file and its chlidren have been created, modified or deleted.
[ "Check", "whether", "the", "file", "and", "its", "chlidren", "have", "been", "created", "modified", "or", "deleted", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/filesystem/PathAlterationObserver.java#L168-L192
26,211
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/filesystem/PathAlterationObserver.java
PathAlterationObserver.checkAndNotify
private void checkAndNotify(final FileStatusEntry parent, final FileStatusEntry[] previous, final Path[] currentPaths) throws IOException { int c = 0; final FileStatusEntry[] current = currentPaths.length > 0 ? new FileStatusEntry[currentPaths.length] : FileStatusEntry.EMPTY_ENTRIES; for (final FileStatusEntry previousEntry : previous) { while (c < currentPaths.length && comparator.compare(previousEntry.getPath(), currentPaths[c]) > 0) { current[c] = createPathEntry(parent, currentPaths[c]); doCreate(current[c]); c++; } if (c < currentPaths.length && comparator.compare(previousEntry.getPath(), currentPaths[c]) == 0) { doMatch(previousEntry, currentPaths[c]); checkAndNotify(previousEntry, previousEntry.getChildren(), listPaths(currentPaths[c])); current[c] = previousEntry; c++; } else { checkAndNotify(previousEntry, previousEntry.getChildren(), EMPTY_PATH_ARRAY); doDelete(previousEntry); } } for (; c < currentPaths.length; c++) { current[c] = createPathEntry(parent, currentPaths[c]); doCreate(current[c]); } parent.setChildren(current); }
java
private void checkAndNotify(final FileStatusEntry parent, final FileStatusEntry[] previous, final Path[] currentPaths) throws IOException { int c = 0; final FileStatusEntry[] current = currentPaths.length > 0 ? new FileStatusEntry[currentPaths.length] : FileStatusEntry.EMPTY_ENTRIES; for (final FileStatusEntry previousEntry : previous) { while (c < currentPaths.length && comparator.compare(previousEntry.getPath(), currentPaths[c]) > 0) { current[c] = createPathEntry(parent, currentPaths[c]); doCreate(current[c]); c++; } if (c < currentPaths.length && comparator.compare(previousEntry.getPath(), currentPaths[c]) == 0) { doMatch(previousEntry, currentPaths[c]); checkAndNotify(previousEntry, previousEntry.getChildren(), listPaths(currentPaths[c])); current[c] = previousEntry; c++; } else { checkAndNotify(previousEntry, previousEntry.getChildren(), EMPTY_PATH_ARRAY); doDelete(previousEntry); } } for (; c < currentPaths.length; c++) { current[c] = createPathEntry(parent, currentPaths[c]); doCreate(current[c]); } parent.setChildren(current); }
[ "private", "void", "checkAndNotify", "(", "final", "FileStatusEntry", "parent", ",", "final", "FileStatusEntry", "[", "]", "previous", ",", "final", "Path", "[", "]", "currentPaths", ")", "throws", "IOException", "{", "int", "c", "=", "0", ";", "final", "FileStatusEntry", "[", "]", "current", "=", "currentPaths", ".", "length", ">", "0", "?", "new", "FileStatusEntry", "[", "currentPaths", ".", "length", "]", ":", "FileStatusEntry", ".", "EMPTY_ENTRIES", ";", "for", "(", "final", "FileStatusEntry", "previousEntry", ":", "previous", ")", "{", "while", "(", "c", "<", "currentPaths", ".", "length", "&&", "comparator", ".", "compare", "(", "previousEntry", ".", "getPath", "(", ")", ",", "currentPaths", "[", "c", "]", ")", ">", "0", ")", "{", "current", "[", "c", "]", "=", "createPathEntry", "(", "parent", ",", "currentPaths", "[", "c", "]", ")", ";", "doCreate", "(", "current", "[", "c", "]", ")", ";", "c", "++", ";", "}", "if", "(", "c", "<", "currentPaths", ".", "length", "&&", "comparator", ".", "compare", "(", "previousEntry", ".", "getPath", "(", ")", ",", "currentPaths", "[", "c", "]", ")", "==", "0", ")", "{", "doMatch", "(", "previousEntry", ",", "currentPaths", "[", "c", "]", ")", ";", "checkAndNotify", "(", "previousEntry", ",", "previousEntry", ".", "getChildren", "(", ")", ",", "listPaths", "(", "currentPaths", "[", "c", "]", ")", ")", ";", "current", "[", "c", "]", "=", "previousEntry", ";", "c", "++", ";", "}", "else", "{", "checkAndNotify", "(", "previousEntry", ",", "previousEntry", ".", "getChildren", "(", ")", ",", "EMPTY_PATH_ARRAY", ")", ";", "doDelete", "(", "previousEntry", ")", ";", "}", "}", "for", "(", ";", "c", "<", "currentPaths", ".", "length", ";", "c", "++", ")", "{", "current", "[", "c", "]", "=", "createPathEntry", "(", "parent", ",", "currentPaths", "[", "c", "]", ")", ";", "doCreate", "(", "current", "[", "c", "]", ")", ";", "}", "parent", ".", "setChildren", "(", "current", ")", ";", "}" ]
Compare two file lists for files which have been created, modified or deleted. @param parent The parent entry @param previous The original list of paths @param currentPaths The current list of paths
[ "Compare", "two", "file", "lists", "for", "files", "which", "have", "been", "created", "modified", "or", "deleted", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/filesystem/PathAlterationObserver.java#L201-L229
26,212
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/filesystem/PathAlterationObserver.java
PathAlterationObserver.createPathEntry
private FileStatusEntry createPathEntry(final FileStatusEntry parent, final Path childPath) throws IOException { final FileStatusEntry entry = parent.newChildInstance(childPath); entry.refresh(childPath); final FileStatusEntry[] children = doListPathsEntry(childPath, entry); entry.setChildren(children); return entry; }
java
private FileStatusEntry createPathEntry(final FileStatusEntry parent, final Path childPath) throws IOException { final FileStatusEntry entry = parent.newChildInstance(childPath); entry.refresh(childPath); final FileStatusEntry[] children = doListPathsEntry(childPath, entry); entry.setChildren(children); return entry; }
[ "private", "FileStatusEntry", "createPathEntry", "(", "final", "FileStatusEntry", "parent", ",", "final", "Path", "childPath", ")", "throws", "IOException", "{", "final", "FileStatusEntry", "entry", "=", "parent", ".", "newChildInstance", "(", "childPath", ")", ";", "entry", ".", "refresh", "(", "childPath", ")", ";", "final", "FileStatusEntry", "[", "]", "children", "=", "doListPathsEntry", "(", "childPath", ",", "entry", ")", ";", "entry", ".", "setChildren", "(", "children", ")", ";", "return", "entry", ";", "}" ]
Create a new FileStatusEntry for the specified file. @param parent The parent file entry @param childPath The file to create an entry for @return A new file entry
[ "Create", "a", "new", "FileStatusEntry", "for", "the", "specified", "file", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/filesystem/PathAlterationObserver.java#L238-L245
26,213
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/filesystem/PathAlterationObserver.java
PathAlterationObserver.doListPathsEntry
private FileStatusEntry[] doListPathsEntry(Path path, FileStatusEntry entry) throws IOException { final Path[] paths = listPaths(path); final FileStatusEntry[] children = paths.length > 0 ? new FileStatusEntry[paths.length] : FileStatusEntry.EMPTY_ENTRIES; for (int i = 0; i < paths.length; i++) { children[i] = createPathEntry(entry, paths[i]); } return children; }
java
private FileStatusEntry[] doListPathsEntry(Path path, FileStatusEntry entry) throws IOException { final Path[] paths = listPaths(path); final FileStatusEntry[] children = paths.length > 0 ? new FileStatusEntry[paths.length] : FileStatusEntry.EMPTY_ENTRIES; for (int i = 0; i < paths.length; i++) { children[i] = createPathEntry(entry, paths[i]); } return children; }
[ "private", "FileStatusEntry", "[", "]", "doListPathsEntry", "(", "Path", "path", ",", "FileStatusEntry", "entry", ")", "throws", "IOException", "{", "final", "Path", "[", "]", "paths", "=", "listPaths", "(", "path", ")", ";", "final", "FileStatusEntry", "[", "]", "children", "=", "paths", ".", "length", ">", "0", "?", "new", "FileStatusEntry", "[", "paths", ".", "length", "]", ":", "FileStatusEntry", ".", "EMPTY_ENTRIES", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "paths", ".", "length", ";", "i", "++", ")", "{", "children", "[", "i", "]", "=", "createPathEntry", "(", "entry", ",", "paths", "[", "i", "]", ")", ";", "}", "return", "children", ";", "}" ]
List the path in the format of FileStatusEntry array @param path The path to list files for @param entry the parent entry @return The child files
[ "List", "the", "path", "in", "the", "format", "of", "FileStatusEntry", "array" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/filesystem/PathAlterationObserver.java#L253-L263
26,214
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/filesystem/PathAlterationObserver.java
PathAlterationObserver.listPaths
private Path[] listPaths(final Path path) throws IOException { Path[] children = null; ArrayList<Path> tmpChildrenPath = new ArrayList<>(); if (fs.isDirectory(path)) { // Get children's path list. FileStatus[] chiledrenFileStatus = pathFilter == null ? fs.listStatus(path) : fs.listStatus(path, pathFilter); for (FileStatus childFileStatus : chiledrenFileStatus) { tmpChildrenPath.add(childFileStatus.getPath()); } children = tmpChildrenPath.toArray(new Path[tmpChildrenPath.size()]); } if (children == null) { children = EMPTY_PATH_ARRAY; } if (comparator != null && children.length > 1) { Arrays.sort(children, comparator); } return children; }
java
private Path[] listPaths(final Path path) throws IOException { Path[] children = null; ArrayList<Path> tmpChildrenPath = new ArrayList<>(); if (fs.isDirectory(path)) { // Get children's path list. FileStatus[] chiledrenFileStatus = pathFilter == null ? fs.listStatus(path) : fs.listStatus(path, pathFilter); for (FileStatus childFileStatus : chiledrenFileStatus) { tmpChildrenPath.add(childFileStatus.getPath()); } children = tmpChildrenPath.toArray(new Path[tmpChildrenPath.size()]); } if (children == null) { children = EMPTY_PATH_ARRAY; } if (comparator != null && children.length > 1) { Arrays.sort(children, comparator); } return children; }
[ "private", "Path", "[", "]", "listPaths", "(", "final", "Path", "path", ")", "throws", "IOException", "{", "Path", "[", "]", "children", "=", "null", ";", "ArrayList", "<", "Path", ">", "tmpChildrenPath", "=", "new", "ArrayList", "<>", "(", ")", ";", "if", "(", "fs", ".", "isDirectory", "(", "path", ")", ")", "{", "// Get children's path list.", "FileStatus", "[", "]", "chiledrenFileStatus", "=", "pathFilter", "==", "null", "?", "fs", ".", "listStatus", "(", "path", ")", ":", "fs", ".", "listStatus", "(", "path", ",", "pathFilter", ")", ";", "for", "(", "FileStatus", "childFileStatus", ":", "chiledrenFileStatus", ")", "{", "tmpChildrenPath", ".", "add", "(", "childFileStatus", ".", "getPath", "(", ")", ")", ";", "}", "children", "=", "tmpChildrenPath", ".", "toArray", "(", "new", "Path", "[", "tmpChildrenPath", ".", "size", "(", ")", "]", ")", ";", "}", "if", "(", "children", "==", "null", ")", "{", "children", "=", "EMPTY_PATH_ARRAY", ";", "}", "if", "(", "comparator", "!=", "null", "&&", "children", ".", "length", ">", "1", ")", "{", "Arrays", ".", "sort", "(", "children", ",", "comparator", ")", ";", "}", "return", "children", ";", "}" ]
List the contents of a directory denoted by Path @param path The path(File Object in general file system) to list the contents of @return the directory contents or a zero length array if the empty or the file is not a directory
[ "List", "the", "contents", "of", "a", "directory", "denoted", "by", "Path" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/filesystem/PathAlterationObserver.java#L326-L345
26,215
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/service/monitoring/FlowStatusGenerator.java
FlowStatusGenerator.getFlowStatus
public FlowStatus getFlowStatus(String flowName, String flowGroup, long flowExecutionId) { FlowStatus flowStatus = null; Iterator<JobStatus> jobStatusIterator = jobStatusRetriever.getJobStatusesForFlowExecution(flowName, flowGroup, flowExecutionId); if (jobStatusIterator.hasNext()) { flowStatus = new FlowStatus(flowName, flowGroup, flowExecutionId, jobStatusIterator); } return flowStatus; }
java
public FlowStatus getFlowStatus(String flowName, String flowGroup, long flowExecutionId) { FlowStatus flowStatus = null; Iterator<JobStatus> jobStatusIterator = jobStatusRetriever.getJobStatusesForFlowExecution(flowName, flowGroup, flowExecutionId); if (jobStatusIterator.hasNext()) { flowStatus = new FlowStatus(flowName, flowGroup, flowExecutionId, jobStatusIterator); } return flowStatus; }
[ "public", "FlowStatus", "getFlowStatus", "(", "String", "flowName", ",", "String", "flowGroup", ",", "long", "flowExecutionId", ")", "{", "FlowStatus", "flowStatus", "=", "null", ";", "Iterator", "<", "JobStatus", ">", "jobStatusIterator", "=", "jobStatusRetriever", ".", "getJobStatusesForFlowExecution", "(", "flowName", ",", "flowGroup", ",", "flowExecutionId", ")", ";", "if", "(", "jobStatusIterator", ".", "hasNext", "(", ")", ")", "{", "flowStatus", "=", "new", "FlowStatus", "(", "flowName", ",", "flowGroup", ",", "flowExecutionId", ",", "jobStatusIterator", ")", ";", "}", "return", "flowStatus", ";", "}" ]
Get the flow status for a specific execution. @param flowName @param flowGroup @param flowExecutionId @return the flow status, null is returned if the flow status does not exist
[ "Get", "the", "flow", "status", "for", "a", "specific", "execution", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/service/monitoring/FlowStatusGenerator.java#L68-L78
26,216
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/service/monitoring/FlowStatusGenerator.java
FlowStatusGenerator.isFlowRunning
public boolean isFlowRunning(String flowName, String flowGroup) { List<FlowStatus> flowStatusList = getLatestFlowStatus(flowName, flowGroup, 1); if (flowStatusList == null || flowStatusList.isEmpty()) { return false; } else { FlowStatus flowStatus = flowStatusList.get(0); Iterator<JobStatus> jobStatusIterator = flowStatus.getJobStatusIterator(); while (jobStatusIterator.hasNext()) { JobStatus jobStatus = jobStatusIterator.next(); if (isJobRunning(jobStatus)) { return true; } } return false; } }
java
public boolean isFlowRunning(String flowName, String flowGroup) { List<FlowStatus> flowStatusList = getLatestFlowStatus(flowName, flowGroup, 1); if (flowStatusList == null || flowStatusList.isEmpty()) { return false; } else { FlowStatus flowStatus = flowStatusList.get(0); Iterator<JobStatus> jobStatusIterator = flowStatus.getJobStatusIterator(); while (jobStatusIterator.hasNext()) { JobStatus jobStatus = jobStatusIterator.next(); if (isJobRunning(jobStatus)) { return true; } } return false; } }
[ "public", "boolean", "isFlowRunning", "(", "String", "flowName", ",", "String", "flowGroup", ")", "{", "List", "<", "FlowStatus", ">", "flowStatusList", "=", "getLatestFlowStatus", "(", "flowName", ",", "flowGroup", ",", "1", ")", ";", "if", "(", "flowStatusList", "==", "null", "||", "flowStatusList", ".", "isEmpty", "(", ")", ")", "{", "return", "false", ";", "}", "else", "{", "FlowStatus", "flowStatus", "=", "flowStatusList", ".", "get", "(", "0", ")", ";", "Iterator", "<", "JobStatus", ">", "jobStatusIterator", "=", "flowStatus", ".", "getJobStatusIterator", "(", ")", ";", "while", "(", "jobStatusIterator", ".", "hasNext", "(", ")", ")", "{", "JobStatus", "jobStatus", "=", "jobStatusIterator", ".", "next", "(", ")", ";", "if", "(", "isJobRunning", "(", "jobStatus", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", "}" ]
Return true if another instance of a flow is running. A flow is determined to be in the RUNNING state, if any of the jobs in the flow are in the RUNNING state. @param flowName @param flowGroup @return true, if any jobs of the flow are RUNNING.
[ "Return", "true", "if", "another", "instance", "of", "a", "flow", "is", "running", ".", "A", "flow", "is", "determined", "to", "be", "in", "the", "RUNNING", "state", "if", "any", "of", "the", "jobs", "in", "the", "flow", "are", "in", "the", "RUNNING", "state", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/service/monitoring/FlowStatusGenerator.java#L87-L103
26,217
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/broker/DefaultBrokerCache.java
DefaultBrokerCache.getScopedFromCache
@SuppressWarnings(value = "unchecked") <T, K extends SharedResourceKey> SharedResourceFactoryResponse<T> getScopedFromCache( final SharedResourceFactory<T, K, S> factory, @Nonnull final K key, @Nonnull final ScopeWrapper<S> scope, final SharedResourcesBrokerImpl<S> broker) throws ExecutionException { RawJobBrokerKey fullKey = new RawJobBrokerKey(scope, factory.getName(), key); Object obj = this.sharedResourceCache.get(fullKey, new Callable<Object>() { @Override public Object call() throws Exception { return factory.createResource(broker.getScopedView(scope.getType()), broker.getConfigView(scope.getType(), key, factory.getName())); } }); return (SharedResourceFactoryResponse<T>)obj; }
java
@SuppressWarnings(value = "unchecked") <T, K extends SharedResourceKey> SharedResourceFactoryResponse<T> getScopedFromCache( final SharedResourceFactory<T, K, S> factory, @Nonnull final K key, @Nonnull final ScopeWrapper<S> scope, final SharedResourcesBrokerImpl<S> broker) throws ExecutionException { RawJobBrokerKey fullKey = new RawJobBrokerKey(scope, factory.getName(), key); Object obj = this.sharedResourceCache.get(fullKey, new Callable<Object>() { @Override public Object call() throws Exception { return factory.createResource(broker.getScopedView(scope.getType()), broker.getConfigView(scope.getType(), key, factory.getName())); } }); return (SharedResourceFactoryResponse<T>)obj; }
[ "@", "SuppressWarnings", "(", "value", "=", "\"unchecked\"", ")", "<", "T", ",", "K", "extends", "SharedResourceKey", ">", "SharedResourceFactoryResponse", "<", "T", ">", "getScopedFromCache", "(", "final", "SharedResourceFactory", "<", "T", ",", "K", ",", "S", ">", "factory", ",", "@", "Nonnull", "final", "K", "key", ",", "@", "Nonnull", "final", "ScopeWrapper", "<", "S", ">", "scope", ",", "final", "SharedResourcesBrokerImpl", "<", "S", ">", "broker", ")", "throws", "ExecutionException", "{", "RawJobBrokerKey", "fullKey", "=", "new", "RawJobBrokerKey", "(", "scope", ",", "factory", ".", "getName", "(", ")", ",", "key", ")", ";", "Object", "obj", "=", "this", ".", "sharedResourceCache", ".", "get", "(", "fullKey", ",", "new", "Callable", "<", "Object", ">", "(", ")", "{", "@", "Override", "public", "Object", "call", "(", ")", "throws", "Exception", "{", "return", "factory", ".", "createResource", "(", "broker", ".", "getScopedView", "(", "scope", ".", "getType", "(", ")", ")", ",", "broker", ".", "getConfigView", "(", "scope", ".", "getType", "(", ")", ",", "key", ",", "factory", ".", "getName", "(", ")", ")", ")", ";", "}", "}", ")", ";", "return", "(", "SharedResourceFactoryResponse", "<", "T", ">", ")", "obj", ";", "}" ]
Get a scoped object from the cache.
[ "Get", "a", "scoped", "object", "from", "the", "cache", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/broker/DefaultBrokerCache.java#L108-L123
26,218
apache/incubator-gobblin
gobblin-salesforce/src/main/java/org/apache/gobblin/salesforce/SalesforceExtractor.java
SalesforceExtractor.getSoftDeletedRecords
private Iterator<JsonElement> getSoftDeletedRecords(String schema, String entity, WorkUnit workUnit, List<Predicate> predicateList) throws DataRecordException { return this.getRecordSet(schema, entity, workUnit, predicateList); }
java
private Iterator<JsonElement> getSoftDeletedRecords(String schema, String entity, WorkUnit workUnit, List<Predicate> predicateList) throws DataRecordException { return this.getRecordSet(schema, entity, workUnit, predicateList); }
[ "private", "Iterator", "<", "JsonElement", ">", "getSoftDeletedRecords", "(", "String", "schema", ",", "String", "entity", ",", "WorkUnit", "workUnit", ",", "List", "<", "Predicate", ">", "predicateList", ")", "throws", "DataRecordException", "{", "return", "this", ".", "getRecordSet", "(", "schema", ",", "entity", ",", "workUnit", ",", "predicateList", ")", ";", "}" ]
Get soft deleted records using Rest Api @return iterator with deleted records
[ "Get", "soft", "deleted", "records", "using", "Rest", "Api" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-salesforce/src/main/java/org/apache/gobblin/salesforce/SalesforceExtractor.java#L638-L641
26,219
apache/incubator-gobblin
gobblin-salesforce/src/main/java/org/apache/gobblin/salesforce/SalesforceExtractor.java
SalesforceExtractor.bulkApiLogin
public boolean bulkApiLogin() throws Exception { log.info("Authenticating salesforce bulk api"); boolean success = false; String hostName = this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_HOST_NAME); String apiVersion = this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_VERSION); if (Strings.isNullOrEmpty(apiVersion)) { // queryAll was introduced in version 39.0, so need to use a higher version when using queryAll with the bulk api apiVersion = this.bulkApiUseQueryAll ? "42.0" : "29.0"; } String soapAuthEndPoint = hostName + SALESFORCE_SOAP_SERVICE + "/" + apiVersion; try { ConnectorConfig partnerConfig = new ConnectorConfig(); if (super.workUnitState.contains(ConfigurationKeys.SOURCE_CONN_USE_PROXY_URL) && !super.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_USE_PROXY_URL).isEmpty()) { partnerConfig.setProxy(super.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_USE_PROXY_URL), super.workUnitState.getPropAsInt(ConfigurationKeys.SOURCE_CONN_USE_PROXY_PORT)); } String accessToken = sfConnector.getAccessToken(); if (accessToken == null) { boolean isConnectSuccess = sfConnector.connect(); if (isConnectSuccess) { accessToken = sfConnector.getAccessToken(); } } if (accessToken != null) { String serviceEndpoint = sfConnector.getInstanceUrl() + SALESFORCE_SOAP_SERVICE + "/" + apiVersion; partnerConfig.setSessionId(accessToken); partnerConfig.setServiceEndpoint(serviceEndpoint); } else { String securityToken = this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_SECURITY_TOKEN); String password = PasswordManager.getInstance(this.workUnitState) .readPassword(this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_PASSWORD)); partnerConfig.setUsername(this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_USERNAME)); partnerConfig.setPassword(password + securityToken); } partnerConfig.setAuthEndpoint(soapAuthEndPoint); new PartnerConnection(partnerConfig); String soapEndpoint = partnerConfig.getServiceEndpoint(); String restEndpoint = soapEndpoint.substring(0, soapEndpoint.indexOf("Soap/")) + "async/" + apiVersion; ConnectorConfig config = new ConnectorConfig(); config.setSessionId(partnerConfig.getSessionId()); config.setRestEndpoint(restEndpoint); config.setCompression(true); config.setTraceFile("traceLogs.txt"); config.setTraceMessage(false); config.setPrettyPrintXml(true); if (super.workUnitState.contains(ConfigurationKeys.SOURCE_CONN_USE_PROXY_URL) && !super.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_USE_PROXY_URL).isEmpty()) { config.setProxy(super.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_USE_PROXY_URL), super.workUnitState.getPropAsInt(ConfigurationKeys.SOURCE_CONN_USE_PROXY_PORT)); } this.bulkConnection = new BulkConnection(config); success = true; } catch (RuntimeException e) { throw new RuntimeException("Failed to connect to salesforce bulk api; error - " + e, e); } return success; }
java
public boolean bulkApiLogin() throws Exception { log.info("Authenticating salesforce bulk api"); boolean success = false; String hostName = this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_HOST_NAME); String apiVersion = this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_VERSION); if (Strings.isNullOrEmpty(apiVersion)) { // queryAll was introduced in version 39.0, so need to use a higher version when using queryAll with the bulk api apiVersion = this.bulkApiUseQueryAll ? "42.0" : "29.0"; } String soapAuthEndPoint = hostName + SALESFORCE_SOAP_SERVICE + "/" + apiVersion; try { ConnectorConfig partnerConfig = new ConnectorConfig(); if (super.workUnitState.contains(ConfigurationKeys.SOURCE_CONN_USE_PROXY_URL) && !super.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_USE_PROXY_URL).isEmpty()) { partnerConfig.setProxy(super.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_USE_PROXY_URL), super.workUnitState.getPropAsInt(ConfigurationKeys.SOURCE_CONN_USE_PROXY_PORT)); } String accessToken = sfConnector.getAccessToken(); if (accessToken == null) { boolean isConnectSuccess = sfConnector.connect(); if (isConnectSuccess) { accessToken = sfConnector.getAccessToken(); } } if (accessToken != null) { String serviceEndpoint = sfConnector.getInstanceUrl() + SALESFORCE_SOAP_SERVICE + "/" + apiVersion; partnerConfig.setSessionId(accessToken); partnerConfig.setServiceEndpoint(serviceEndpoint); } else { String securityToken = this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_SECURITY_TOKEN); String password = PasswordManager.getInstance(this.workUnitState) .readPassword(this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_PASSWORD)); partnerConfig.setUsername(this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_USERNAME)); partnerConfig.setPassword(password + securityToken); } partnerConfig.setAuthEndpoint(soapAuthEndPoint); new PartnerConnection(partnerConfig); String soapEndpoint = partnerConfig.getServiceEndpoint(); String restEndpoint = soapEndpoint.substring(0, soapEndpoint.indexOf("Soap/")) + "async/" + apiVersion; ConnectorConfig config = new ConnectorConfig(); config.setSessionId(partnerConfig.getSessionId()); config.setRestEndpoint(restEndpoint); config.setCompression(true); config.setTraceFile("traceLogs.txt"); config.setTraceMessage(false); config.setPrettyPrintXml(true); if (super.workUnitState.contains(ConfigurationKeys.SOURCE_CONN_USE_PROXY_URL) && !super.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_USE_PROXY_URL).isEmpty()) { config.setProxy(super.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_USE_PROXY_URL), super.workUnitState.getPropAsInt(ConfigurationKeys.SOURCE_CONN_USE_PROXY_PORT)); } this.bulkConnection = new BulkConnection(config); success = true; } catch (RuntimeException e) { throw new RuntimeException("Failed to connect to salesforce bulk api; error - " + e, e); } return success; }
[ "public", "boolean", "bulkApiLogin", "(", ")", "throws", "Exception", "{", "log", ".", "info", "(", "\"Authenticating salesforce bulk api\"", ")", ";", "boolean", "success", "=", "false", ";", "String", "hostName", "=", "this", ".", "workUnitState", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_CONN_HOST_NAME", ")", ";", "String", "apiVersion", "=", "this", ".", "workUnitState", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_CONN_VERSION", ")", ";", "if", "(", "Strings", ".", "isNullOrEmpty", "(", "apiVersion", ")", ")", "{", "// queryAll was introduced in version 39.0, so need to use a higher version when using queryAll with the bulk api", "apiVersion", "=", "this", ".", "bulkApiUseQueryAll", "?", "\"42.0\"", ":", "\"29.0\"", ";", "}", "String", "soapAuthEndPoint", "=", "hostName", "+", "SALESFORCE_SOAP_SERVICE", "+", "\"/\"", "+", "apiVersion", ";", "try", "{", "ConnectorConfig", "partnerConfig", "=", "new", "ConnectorConfig", "(", ")", ";", "if", "(", "super", ".", "workUnitState", ".", "contains", "(", "ConfigurationKeys", ".", "SOURCE_CONN_USE_PROXY_URL", ")", "&&", "!", "super", ".", "workUnitState", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_CONN_USE_PROXY_URL", ")", ".", "isEmpty", "(", ")", ")", "{", "partnerConfig", ".", "setProxy", "(", "super", ".", "workUnitState", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_CONN_USE_PROXY_URL", ")", ",", "super", ".", "workUnitState", ".", "getPropAsInt", "(", "ConfigurationKeys", ".", "SOURCE_CONN_USE_PROXY_PORT", ")", ")", ";", "}", "String", "accessToken", "=", "sfConnector", ".", "getAccessToken", "(", ")", ";", "if", "(", "accessToken", "==", "null", ")", "{", "boolean", "isConnectSuccess", "=", "sfConnector", ".", "connect", "(", ")", ";", "if", "(", "isConnectSuccess", ")", "{", "accessToken", "=", "sfConnector", ".", "getAccessToken", "(", ")", ";", "}", "}", "if", "(", "accessToken", "!=", "null", ")", "{", "String", "serviceEndpoint", "=", "sfConnector", ".", "getInstanceUrl", "(", ")", "+", "SALESFORCE_SOAP_SERVICE", "+", "\"/\"", "+", "apiVersion", ";", "partnerConfig", ".", "setSessionId", "(", "accessToken", ")", ";", "partnerConfig", ".", "setServiceEndpoint", "(", "serviceEndpoint", ")", ";", "}", "else", "{", "String", "securityToken", "=", "this", ".", "workUnitState", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_CONN_SECURITY_TOKEN", ")", ";", "String", "password", "=", "PasswordManager", ".", "getInstance", "(", "this", ".", "workUnitState", ")", ".", "readPassword", "(", "this", ".", "workUnitState", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_CONN_PASSWORD", ")", ")", ";", "partnerConfig", ".", "setUsername", "(", "this", ".", "workUnitState", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_CONN_USERNAME", ")", ")", ";", "partnerConfig", ".", "setPassword", "(", "password", "+", "securityToken", ")", ";", "}", "partnerConfig", ".", "setAuthEndpoint", "(", "soapAuthEndPoint", ")", ";", "new", "PartnerConnection", "(", "partnerConfig", ")", ";", "String", "soapEndpoint", "=", "partnerConfig", ".", "getServiceEndpoint", "(", ")", ";", "String", "restEndpoint", "=", "soapEndpoint", ".", "substring", "(", "0", ",", "soapEndpoint", ".", "indexOf", "(", "\"Soap/\"", ")", ")", "+", "\"async/\"", "+", "apiVersion", ";", "ConnectorConfig", "config", "=", "new", "ConnectorConfig", "(", ")", ";", "config", ".", "setSessionId", "(", "partnerConfig", ".", "getSessionId", "(", ")", ")", ";", "config", ".", "setRestEndpoint", "(", "restEndpoint", ")", ";", "config", ".", "setCompression", "(", "true", ")", ";", "config", ".", "setTraceFile", "(", "\"traceLogs.txt\"", ")", ";", "config", ".", "setTraceMessage", "(", "false", ")", ";", "config", ".", "setPrettyPrintXml", "(", "true", ")", ";", "if", "(", "super", ".", "workUnitState", ".", "contains", "(", "ConfigurationKeys", ".", "SOURCE_CONN_USE_PROXY_URL", ")", "&&", "!", "super", ".", "workUnitState", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_CONN_USE_PROXY_URL", ")", ".", "isEmpty", "(", ")", ")", "{", "config", ".", "setProxy", "(", "super", ".", "workUnitState", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_CONN_USE_PROXY_URL", ")", ",", "super", ".", "workUnitState", ".", "getPropAsInt", "(", "ConfigurationKeys", ".", "SOURCE_CONN_USE_PROXY_PORT", ")", ")", ";", "}", "this", ".", "bulkConnection", "=", "new", "BulkConnection", "(", "config", ")", ";", "success", "=", "true", ";", "}", "catch", "(", "RuntimeException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Failed to connect to salesforce bulk api; error - \"", "+", "e", ",", "e", ")", ";", "}", "return", "success", ";", "}" ]
Login to salesforce @return login status
[ "Login", "to", "salesforce" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-salesforce/src/main/java/org/apache/gobblin/salesforce/SalesforceExtractor.java#L647-L713
26,220
apache/incubator-gobblin
gobblin-salesforce/src/main/java/org/apache/gobblin/salesforce/SalesforceExtractor.java
SalesforceExtractor.getBulkBufferedReader
private BufferedReader getBulkBufferedReader(int index) throws AsyncApiException { return new BufferedReader(new InputStreamReader( this.bulkConnection.getQueryResultStream(this.bulkJob.getId(), this.bulkResultIdList.get(index).getBatchId(), this.bulkResultIdList.get(index).getResultId()), ConfigurationKeys.DEFAULT_CHARSET_ENCODING)); }
java
private BufferedReader getBulkBufferedReader(int index) throws AsyncApiException { return new BufferedReader(new InputStreamReader( this.bulkConnection.getQueryResultStream(this.bulkJob.getId(), this.bulkResultIdList.get(index).getBatchId(), this.bulkResultIdList.get(index).getResultId()), ConfigurationKeys.DEFAULT_CHARSET_ENCODING)); }
[ "private", "BufferedReader", "getBulkBufferedReader", "(", "int", "index", ")", "throws", "AsyncApiException", "{", "return", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "this", ".", "bulkConnection", ".", "getQueryResultStream", "(", "this", ".", "bulkJob", ".", "getId", "(", ")", ",", "this", ".", "bulkResultIdList", ".", "get", "(", "index", ")", ".", "getBatchId", "(", ")", ",", "this", ".", "bulkResultIdList", ".", "get", "(", "index", ")", ".", "getResultId", "(", ")", ")", ",", "ConfigurationKeys", ".", "DEFAULT_CHARSET_ENCODING", ")", ")", ";", "}" ]
Get a buffered reader wrapping the query result stream for the result with the specified index @param index index the {@link #bulkResultIdList} @return a {@link BufferedReader} @throws AsyncApiException
[ "Get", "a", "buffered", "reader", "wrapping", "the", "query", "result", "stream", "for", "the", "result", "with", "the", "specified", "index" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-salesforce/src/main/java/org/apache/gobblin/salesforce/SalesforceExtractor.java#L826-L830
26,221
apache/incubator-gobblin
gobblin-salesforce/src/main/java/org/apache/gobblin/salesforce/SalesforceExtractor.java
SalesforceExtractor.fetchResultBatchWithRetry
private void fetchResultBatchWithRetry(RecordSetList<JsonElement> rs) throws AsyncApiException, DataRecordException, IOException { boolean success = false; int retryCount = 0; int recordCountBeforeFetch = this.bulkRecordCount; do { try { // reinitialize the reader to establish a new connection to handle transient network errors if (retryCount > 0) { reinitializeBufferedReader(); } // on retries there may already be records in rs, so pass the number of records as the initial count fetchResultBatch(rs, this.bulkRecordCount - recordCountBeforeFetch); success = true; } catch (IOException e) { if (retryCount < this.fetchRetryLimit) { log.info("Exception while fetching data, retrying: " + e.getMessage(), e); retryCount++; } else { log.error("Exception while fetching data: " + e.getMessage(), e); throw e; } } } while (!success); }
java
private void fetchResultBatchWithRetry(RecordSetList<JsonElement> rs) throws AsyncApiException, DataRecordException, IOException { boolean success = false; int retryCount = 0; int recordCountBeforeFetch = this.bulkRecordCount; do { try { // reinitialize the reader to establish a new connection to handle transient network errors if (retryCount > 0) { reinitializeBufferedReader(); } // on retries there may already be records in rs, so pass the number of records as the initial count fetchResultBatch(rs, this.bulkRecordCount - recordCountBeforeFetch); success = true; } catch (IOException e) { if (retryCount < this.fetchRetryLimit) { log.info("Exception while fetching data, retrying: " + e.getMessage(), e); retryCount++; } else { log.error("Exception while fetching data: " + e.getMessage(), e); throw e; } } } while (!success); }
[ "private", "void", "fetchResultBatchWithRetry", "(", "RecordSetList", "<", "JsonElement", ">", "rs", ")", "throws", "AsyncApiException", ",", "DataRecordException", ",", "IOException", "{", "boolean", "success", "=", "false", ";", "int", "retryCount", "=", "0", ";", "int", "recordCountBeforeFetch", "=", "this", ".", "bulkRecordCount", ";", "do", "{", "try", "{", "// reinitialize the reader to establish a new connection to handle transient network errors", "if", "(", "retryCount", ">", "0", ")", "{", "reinitializeBufferedReader", "(", ")", ";", "}", "// on retries there may already be records in rs, so pass the number of records as the initial count", "fetchResultBatch", "(", "rs", ",", "this", ".", "bulkRecordCount", "-", "recordCountBeforeFetch", ")", ";", "success", "=", "true", ";", "}", "catch", "(", "IOException", "e", ")", "{", "if", "(", "retryCount", "<", "this", ".", "fetchRetryLimit", ")", "{", "log", ".", "info", "(", "\"Exception while fetching data, retrying: \"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "retryCount", "++", ";", "}", "else", "{", "log", ".", "error", "(", "\"Exception while fetching data: \"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "throw", "e", ";", "}", "}", "}", "while", "(", "!", "success", ")", ";", "}" ]
Fetch a result batch with retry for network errors @param rs the {@link RecordSetList} to fetch into
[ "Fetch", "a", "result", "batch", "with", "retry", "for", "network", "errors" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-salesforce/src/main/java/org/apache/gobblin/salesforce/SalesforceExtractor.java#L911-L937
26,222
apache/incubator-gobblin
gobblin-salesforce/src/main/java/org/apache/gobblin/salesforce/SalesforceExtractor.java
SalesforceExtractor.getBulkData
private RecordSet<JsonElement> getBulkData() throws DataRecordException { log.debug("Processing bulk api batch..."); RecordSetList<JsonElement> rs = new RecordSetList<>(); try { // if Buffer is empty then get stream for the new resultset id if (this.bulkBufferedReader == null || !this.bulkBufferedReader.ready()) { // log the number of records from each result set after it is processed (bulkResultIdCount > 0) if (this.bulkResultIdCount > 0) { log.info("Result set {} had {} records", this.bulkResultIdCount, this.bulkRecordCount - this.prevBulkRecordCount); } // if there is unprocessed resultset id then get result stream for that id if (this.bulkResultIdCount < this.bulkResultIdList.size()) { log.info("Stream resultset for resultId:" + this.bulkResultIdList.get(this.bulkResultIdCount)); this.setNewBulkResultSet(true); if (this.bulkBufferedReader != null) { this.bulkBufferedReader.close(); } this.bulkBufferedReader = getBulkBufferedReader(this.bulkResultIdCount); this.bulkResultIdCount++; this.prevBulkRecordCount = bulkRecordCount; } else { // if result stream processed for all resultset ids then finish the bulk job log.info("Bulk job is finished"); this.setBulkJobFinished(true); return rs; } } // fetch a batch of results with retry for network errors fetchResultBatchWithRetry(rs); } catch (Exception e) { throw new DataRecordException("Failed to get records from salesforce; error - " + e.getMessage(), e); } return rs; }
java
private RecordSet<JsonElement> getBulkData() throws DataRecordException { log.debug("Processing bulk api batch..."); RecordSetList<JsonElement> rs = new RecordSetList<>(); try { // if Buffer is empty then get stream for the new resultset id if (this.bulkBufferedReader == null || !this.bulkBufferedReader.ready()) { // log the number of records from each result set after it is processed (bulkResultIdCount > 0) if (this.bulkResultIdCount > 0) { log.info("Result set {} had {} records", this.bulkResultIdCount, this.bulkRecordCount - this.prevBulkRecordCount); } // if there is unprocessed resultset id then get result stream for that id if (this.bulkResultIdCount < this.bulkResultIdList.size()) { log.info("Stream resultset for resultId:" + this.bulkResultIdList.get(this.bulkResultIdCount)); this.setNewBulkResultSet(true); if (this.bulkBufferedReader != null) { this.bulkBufferedReader.close(); } this.bulkBufferedReader = getBulkBufferedReader(this.bulkResultIdCount); this.bulkResultIdCount++; this.prevBulkRecordCount = bulkRecordCount; } else { // if result stream processed for all resultset ids then finish the bulk job log.info("Bulk job is finished"); this.setBulkJobFinished(true); return rs; } } // fetch a batch of results with retry for network errors fetchResultBatchWithRetry(rs); } catch (Exception e) { throw new DataRecordException("Failed to get records from salesforce; error - " + e.getMessage(), e); } return rs; }
[ "private", "RecordSet", "<", "JsonElement", ">", "getBulkData", "(", ")", "throws", "DataRecordException", "{", "log", ".", "debug", "(", "\"Processing bulk api batch...\"", ")", ";", "RecordSetList", "<", "JsonElement", ">", "rs", "=", "new", "RecordSetList", "<>", "(", ")", ";", "try", "{", "// if Buffer is empty then get stream for the new resultset id", "if", "(", "this", ".", "bulkBufferedReader", "==", "null", "||", "!", "this", ".", "bulkBufferedReader", ".", "ready", "(", ")", ")", "{", "// log the number of records from each result set after it is processed (bulkResultIdCount > 0)", "if", "(", "this", ".", "bulkResultIdCount", ">", "0", ")", "{", "log", ".", "info", "(", "\"Result set {} had {} records\"", ",", "this", ".", "bulkResultIdCount", ",", "this", ".", "bulkRecordCount", "-", "this", ".", "prevBulkRecordCount", ")", ";", "}", "// if there is unprocessed resultset id then get result stream for that id", "if", "(", "this", ".", "bulkResultIdCount", "<", "this", ".", "bulkResultIdList", ".", "size", "(", ")", ")", "{", "log", ".", "info", "(", "\"Stream resultset for resultId:\"", "+", "this", ".", "bulkResultIdList", ".", "get", "(", "this", ".", "bulkResultIdCount", ")", ")", ";", "this", ".", "setNewBulkResultSet", "(", "true", ")", ";", "if", "(", "this", ".", "bulkBufferedReader", "!=", "null", ")", "{", "this", ".", "bulkBufferedReader", ".", "close", "(", ")", ";", "}", "this", ".", "bulkBufferedReader", "=", "getBulkBufferedReader", "(", "this", ".", "bulkResultIdCount", ")", ";", "this", ".", "bulkResultIdCount", "++", ";", "this", ".", "prevBulkRecordCount", "=", "bulkRecordCount", ";", "}", "else", "{", "// if result stream processed for all resultset ids then finish the bulk job", "log", ".", "info", "(", "\"Bulk job is finished\"", ")", ";", "this", ".", "setBulkJobFinished", "(", "true", ")", ";", "return", "rs", ";", "}", "}", "// fetch a batch of results with retry for network errors", "fetchResultBatchWithRetry", "(", "rs", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "DataRecordException", "(", "\"Failed to get records from salesforce; error - \"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "return", "rs", ";", "}" ]
Get data from the bulk api input stream @return record set with each record as a JsonObject
[ "Get", "data", "from", "the", "bulk", "api", "input", "stream" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-salesforce/src/main/java/org/apache/gobblin/salesforce/SalesforceExtractor.java#L943-L985
26,223
apache/incubator-gobblin
gobblin-salesforce/src/main/java/org/apache/gobblin/salesforce/SalesforceExtractor.java
SalesforceExtractor.waitForPkBatches
private BatchInfo waitForPkBatches(BatchInfoList batchInfoList, int retryInterval) throws InterruptedException, AsyncApiException { BatchInfo batchInfo = null; BatchInfo[] batchInfos = batchInfoList.getBatchInfo(); // Wait for all batches other than the first one. The first one is not processed in PK chunking mode for (int i = 1; i < batchInfos.length; i++) { BatchInfo bi = batchInfos[i]; // get refreshed job status bi = this.bulkConnection.getBatchInfo(this.bulkJob.getId(), bi.getId()); while ((bi.getState() != BatchStateEnum.Completed) && (bi.getState() != BatchStateEnum.Failed)) { Thread.sleep(retryInterval * 1000); bi = this.bulkConnection.getBatchInfo(this.bulkJob.getId(), bi.getId()); log.debug("Bulk Api Batch Info:" + bi); log.info("Waiting for bulk resultSetIds"); } batchInfo = bi; // exit if there was a failure if (batchInfo.getState() == BatchStateEnum.Failed) { break; } } return batchInfo; }
java
private BatchInfo waitForPkBatches(BatchInfoList batchInfoList, int retryInterval) throws InterruptedException, AsyncApiException { BatchInfo batchInfo = null; BatchInfo[] batchInfos = batchInfoList.getBatchInfo(); // Wait for all batches other than the first one. The first one is not processed in PK chunking mode for (int i = 1; i < batchInfos.length; i++) { BatchInfo bi = batchInfos[i]; // get refreshed job status bi = this.bulkConnection.getBatchInfo(this.bulkJob.getId(), bi.getId()); while ((bi.getState() != BatchStateEnum.Completed) && (bi.getState() != BatchStateEnum.Failed)) { Thread.sleep(retryInterval * 1000); bi = this.bulkConnection.getBatchInfo(this.bulkJob.getId(), bi.getId()); log.debug("Bulk Api Batch Info:" + bi); log.info("Waiting for bulk resultSetIds"); } batchInfo = bi; // exit if there was a failure if (batchInfo.getState() == BatchStateEnum.Failed) { break; } } return batchInfo; }
[ "private", "BatchInfo", "waitForPkBatches", "(", "BatchInfoList", "batchInfoList", ",", "int", "retryInterval", ")", "throws", "InterruptedException", ",", "AsyncApiException", "{", "BatchInfo", "batchInfo", "=", "null", ";", "BatchInfo", "[", "]", "batchInfos", "=", "batchInfoList", ".", "getBatchInfo", "(", ")", ";", "// Wait for all batches other than the first one. The first one is not processed in PK chunking mode", "for", "(", "int", "i", "=", "1", ";", "i", "<", "batchInfos", ".", "length", ";", "i", "++", ")", "{", "BatchInfo", "bi", "=", "batchInfos", "[", "i", "]", ";", "// get refreshed job status", "bi", "=", "this", ".", "bulkConnection", ".", "getBatchInfo", "(", "this", ".", "bulkJob", ".", "getId", "(", ")", ",", "bi", ".", "getId", "(", ")", ")", ";", "while", "(", "(", "bi", ".", "getState", "(", ")", "!=", "BatchStateEnum", ".", "Completed", ")", "&&", "(", "bi", ".", "getState", "(", ")", "!=", "BatchStateEnum", ".", "Failed", ")", ")", "{", "Thread", ".", "sleep", "(", "retryInterval", "*", "1000", ")", ";", "bi", "=", "this", ".", "bulkConnection", ".", "getBatchInfo", "(", "this", ".", "bulkJob", ".", "getId", "(", ")", ",", "bi", ".", "getId", "(", ")", ")", ";", "log", ".", "debug", "(", "\"Bulk Api Batch Info:\"", "+", "bi", ")", ";", "log", ".", "info", "(", "\"Waiting for bulk resultSetIds\"", ")", ";", "}", "batchInfo", "=", "bi", ";", "// exit if there was a failure", "if", "(", "batchInfo", ".", "getState", "(", ")", "==", "BatchStateEnum", ".", "Failed", ")", "{", "break", ";", "}", "}", "return", "batchInfo", ";", "}" ]
Waits for the PK batches to complete. The wait will stop after all batches are complete or on the first failed batch @param batchInfoList list of batch info @param retryInterval the polling interval @return the last {@link BatchInfo} processed @throws InterruptedException @throws AsyncApiException
[ "Waits", "for", "the", "PK", "batches", "to", "complete", ".", "The", "wait", "will", "stop", "after", "all", "batches", "are", "complete", "or", "on", "the", "first", "failed", "batch" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-salesforce/src/main/java/org/apache/gobblin/salesforce/SalesforceExtractor.java#L1008-L1037
26,224
apache/incubator-gobblin
gobblin-core-base/src/main/java/org/apache/gobblin/compression/CompressionConfigParser.java
CompressionConfigParser.getConfigForBranch
public static Map<String, Object> getConfigForBranch(State taskState, int numBranches, int branch) { String typePropertyName = ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_CODEC_TYPE, numBranches, branch); String compressionType = taskState.getProp(typePropertyName); if (compressionType == null) { return null; } return ImmutableMap.<String, Object>of(COMPRESSION_TYPE_KEY, compressionType); }
java
public static Map<String, Object> getConfigForBranch(State taskState, int numBranches, int branch) { String typePropertyName = ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_CODEC_TYPE, numBranches, branch); String compressionType = taskState.getProp(typePropertyName); if (compressionType == null) { return null; } return ImmutableMap.<String, Object>of(COMPRESSION_TYPE_KEY, compressionType); }
[ "public", "static", "Map", "<", "String", ",", "Object", ">", "getConfigForBranch", "(", "State", "taskState", ",", "int", "numBranches", ",", "int", "branch", ")", "{", "String", "typePropertyName", "=", "ForkOperatorUtils", ".", "getPropertyNameForBranch", "(", "ConfigurationKeys", ".", "WRITER_CODEC_TYPE", ",", "numBranches", ",", "branch", ")", ";", "String", "compressionType", "=", "taskState", ".", "getProp", "(", "typePropertyName", ")", ";", "if", "(", "compressionType", "==", "null", ")", "{", "return", "null", ";", "}", "return", "ImmutableMap", ".", "<", "String", ",", "Object", ">", "of", "(", "COMPRESSION_TYPE_KEY", ",", "compressionType", ")", ";", "}" ]
Retrieve configuration settings for a given branch. @param taskState Task state @param numBranches # of branches in the state @param branch Branch to retrieve @return Map of properties for compression
[ "Retrieve", "configuration", "settings", "for", "a", "given", "branch", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core-base/src/main/java/org/apache/gobblin/compression/CompressionConfigParser.java#L41-L50
26,225
apache/incubator-gobblin
gobblin-core-base/src/main/java/org/apache/gobblin/compression/CompressionConfigParser.java
CompressionConfigParser.getCompressionType
public static String getCompressionType(Map<String, Object> properties) { return (String) properties.get(COMPRESSION_TYPE_KEY); }
java
public static String getCompressionType(Map<String, Object> properties) { return (String) properties.get(COMPRESSION_TYPE_KEY); }
[ "public", "static", "String", "getCompressionType", "(", "Map", "<", "String", ",", "Object", ">", "properties", ")", "{", "return", "(", "String", ")", "properties", ".", "get", "(", "COMPRESSION_TYPE_KEY", ")", ";", "}" ]
Return compression type @param properties Compression config settings @return String representing compression type, null if none exists
[ "Return", "compression", "type" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core-base/src/main/java/org/apache/gobblin/compression/CompressionConfigParser.java#L57-L59
26,226
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/AutoReturnableObject.java
AutoReturnableObject.close
@Override public void close() throws IOException { try { this.pool.returnObject(this.object); } catch (Exception exc) { throw new IOException(exc); } finally { this.returned = true; } }
java
@Override public void close() throws IOException { try { this.pool.returnObject(this.object); } catch (Exception exc) { throw new IOException(exc); } finally { this.returned = true; } }
[ "@", "Override", "public", "void", "close", "(", ")", "throws", "IOException", "{", "try", "{", "this", ".", "pool", ".", "returnObject", "(", "this", ".", "object", ")", ";", "}", "catch", "(", "Exception", "exc", ")", "{", "throw", "new", "IOException", "(", "exc", ")", ";", "}", "finally", "{", "this", ".", "returned", "=", "true", ";", "}", "}" ]
Return the borrowed object to the pool. @throws IOException
[ "Return", "the", "borrowed", "object", "to", "the", "pool", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/AutoReturnableObject.java#L60-L69
26,227
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/converter/filter/AvroFieldsPickConverter.java
AvroFieldsPickConverter.convertSchema
@Override public Schema convertSchema(Schema inputSchema, WorkUnitState workUnit) throws SchemaConversionException { LOG.info("Converting schema " + inputSchema); String fieldsStr = workUnit.getProp(ConfigurationKeys.CONVERTER_AVRO_FIELD_PICK_FIELDS); Preconditions.checkNotNull(fieldsStr, ConfigurationKeys.CONVERTER_AVRO_FIELD_PICK_FIELDS + " is required for converter " + this.getClass().getSimpleName()); LOG.info("Converting schema to selected fields: " + fieldsStr); try { return createSchema(inputSchema, fieldsStr); } catch (Exception e) { throw new SchemaConversionException(e); } }
java
@Override public Schema convertSchema(Schema inputSchema, WorkUnitState workUnit) throws SchemaConversionException { LOG.info("Converting schema " + inputSchema); String fieldsStr = workUnit.getProp(ConfigurationKeys.CONVERTER_AVRO_FIELD_PICK_FIELDS); Preconditions.checkNotNull(fieldsStr, ConfigurationKeys.CONVERTER_AVRO_FIELD_PICK_FIELDS + " is required for converter " + this.getClass().getSimpleName()); LOG.info("Converting schema to selected fields: " + fieldsStr); try { return createSchema(inputSchema, fieldsStr); } catch (Exception e) { throw new SchemaConversionException(e); } }
[ "@", "Override", "public", "Schema", "convertSchema", "(", "Schema", "inputSchema", ",", "WorkUnitState", "workUnit", ")", "throws", "SchemaConversionException", "{", "LOG", ".", "info", "(", "\"Converting schema \"", "+", "inputSchema", ")", ";", "String", "fieldsStr", "=", "workUnit", ".", "getProp", "(", "ConfigurationKeys", ".", "CONVERTER_AVRO_FIELD_PICK_FIELDS", ")", ";", "Preconditions", ".", "checkNotNull", "(", "fieldsStr", ",", "ConfigurationKeys", ".", "CONVERTER_AVRO_FIELD_PICK_FIELDS", "+", "\" is required for converter \"", "+", "this", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", ")", ";", "LOG", ".", "info", "(", "\"Converting schema to selected fields: \"", "+", "fieldsStr", ")", ";", "try", "{", "return", "createSchema", "(", "inputSchema", ",", "fieldsStr", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "SchemaConversionException", "(", "e", ")", ";", "}", "}" ]
Convert the schema to contain only specified field. This will reuse AvroSchemaFieldRemover by listing fields not specified and remove it from the schema 1. Retrieve list of fields from property 2. Traverse schema and get list of fields to be removed 3. While traversing also confirm specified fields from property also exist 4. Convert schema by using AvroSchemaFieldRemover Each Avro Record type increments depth and from input depth is represented by '.'. Avro schema is always expected to start with Record type and first record type is depth 0 and won't be represented by '.'. As it's always expected to start with Record type, it's not necessary to disambiguate. After first record type, if it reaches another record type, the prefix of the field name will be "[Record name].". Example: { "namespace": "example.avro", "type": "record", "name": "user", "fields": [ { "name": "name", "type": "string" }, { "name": "favorite_number", "type": [ "int", "null" ] }, { "type": "record", "name": "address", "fields": [ { "name": "city", "type": "string" } ] } ] } If user wants to only choose name and city, the input parameter should be "name,address.city". Note that it is not user.name as first record is depth zero. {@inheritDoc} @see org.apache.gobblin.converter.AvroToAvroConverterBase#convertSchema(org.apache.avro.Schema, org.apache.gobblin.configuration.WorkUnitState)
[ "Convert", "the", "schema", "to", "contain", "only", "specified", "field", ".", "This", "will", "reuse", "AvroSchemaFieldRemover", "by", "listing", "fields", "not", "specified", "and", "remove", "it", "from", "the", "schema", "1", ".", "Retrieve", "list", "of", "fields", "from", "property", "2", ".", "Traverse", "schema", "and", "get", "list", "of", "fields", "to", "be", "removed", "3", ".", "While", "traversing", "also", "confirm", "specified", "fields", "from", "property", "also", "exist", "4", ".", "Convert", "schema", "by", "using", "AvroSchemaFieldRemover" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/converter/filter/AvroFieldsPickConverter.java#L101-L114
26,228
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/converter/filter/AvroFieldsPickConverter.java
AvroFieldsPickConverter.createSchema
private static Schema createSchema(Schema schema, String fieldsStr) { List<String> fields = SPLITTER_ON_COMMA.splitToList(fieldsStr); TrieNode root = buildTrie(fields); return createSchemaHelper(schema, root); }
java
private static Schema createSchema(Schema schema, String fieldsStr) { List<String> fields = SPLITTER_ON_COMMA.splitToList(fieldsStr); TrieNode root = buildTrie(fields); return createSchemaHelper(schema, root); }
[ "private", "static", "Schema", "createSchema", "(", "Schema", "schema", ",", "String", "fieldsStr", ")", "{", "List", "<", "String", ">", "fields", "=", "SPLITTER_ON_COMMA", ".", "splitToList", "(", "fieldsStr", ")", ";", "TrieNode", "root", "=", "buildTrie", "(", "fields", ")", ";", "return", "createSchemaHelper", "(", "schema", ",", "root", ")", ";", "}" ]
Creates Schema containing only specified fields. Traversing via either fully qualified names or input Schema is quite inefficient as it's hard to align each other. Also, as Schema's fields is immutable, all the fields need to be collected before updating field in Schema. Figuring out all required field in just input Schema and fully qualified names is also not efficient as well. This is where Trie comes into picture. Having fully qualified names in Trie means, it is aligned with input schema and also it can provides all children on specific prefix. This solves two problems mentioned above. 1. Based on fully qualified field name, build a Trie to present dependencies. 2. Traverse the Trie. If it's leaf, add field. If it's not a leaf, recurse with child schema. @param schema @param fieldsStr @return
[ "Creates", "Schema", "containing", "only", "specified", "fields", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/converter/filter/AvroFieldsPickConverter.java#L133-L137
26,229
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/converter/filter/AvroFieldsPickConverter.java
AvroFieldsPickConverter.getActualRecord
private static Schema getActualRecord(Schema inputSchema) { if (Type.RECORD.equals(inputSchema.getType())) { return inputSchema; } Preconditions.checkArgument(Type.UNION.equals(inputSchema.getType()), "Nested schema is only support with either record or union type of null with record"); Preconditions.checkArgument(inputSchema.getTypes().size() <= 2, "For union type in nested record, it should only have NULL and Record type"); for (Schema inner : inputSchema.getTypes()) { if (Type.NULL.equals(inner.getType())) { continue; } Preconditions.checkArgument(Type.RECORD.equals(inner.getType()), "For union type in nested record, it should only have NULL and Record type"); return inner; } throw new IllegalArgumentException(inputSchema + " is not supported."); }
java
private static Schema getActualRecord(Schema inputSchema) { if (Type.RECORD.equals(inputSchema.getType())) { return inputSchema; } Preconditions.checkArgument(Type.UNION.equals(inputSchema.getType()), "Nested schema is only support with either record or union type of null with record"); Preconditions.checkArgument(inputSchema.getTypes().size() <= 2, "For union type in nested record, it should only have NULL and Record type"); for (Schema inner : inputSchema.getTypes()) { if (Type.NULL.equals(inner.getType())) { continue; } Preconditions.checkArgument(Type.RECORD.equals(inner.getType()), "For union type in nested record, it should only have NULL and Record type"); return inner; } throw new IllegalArgumentException(inputSchema + " is not supported."); }
[ "private", "static", "Schema", "getActualRecord", "(", "Schema", "inputSchema", ")", "{", "if", "(", "Type", ".", "RECORD", ".", "equals", "(", "inputSchema", ".", "getType", "(", ")", ")", ")", "{", "return", "inputSchema", ";", "}", "Preconditions", ".", "checkArgument", "(", "Type", ".", "UNION", ".", "equals", "(", "inputSchema", ".", "getType", "(", ")", ")", ",", "\"Nested schema is only support with either record or union type of null with record\"", ")", ";", "Preconditions", ".", "checkArgument", "(", "inputSchema", ".", "getTypes", "(", ")", ".", "size", "(", ")", "<=", "2", ",", "\"For union type in nested record, it should only have NULL and Record type\"", ")", ";", "for", "(", "Schema", "inner", ":", "inputSchema", ".", "getTypes", "(", ")", ")", "{", "if", "(", "Type", ".", "NULL", ".", "equals", "(", "inner", ".", "getType", "(", ")", ")", ")", "{", "continue", ";", "}", "Preconditions", ".", "checkArgument", "(", "Type", ".", "RECORD", ".", "equals", "(", "inner", ".", "getType", "(", ")", ")", ",", "\"For union type in nested record, it should only have NULL and Record type\"", ")", ";", "return", "inner", ";", "}", "throw", "new", "IllegalArgumentException", "(", "inputSchema", "+", "\" is not supported.\"", ")", ";", "}" ]
For the schema that is a UNION type with NULL and Record type, it provides Records type. @param inputSchema @return
[ "For", "the", "schema", "that", "is", "a", "UNION", "type", "with", "NULL", "and", "Record", "type", "it", "provides", "Records", "type", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/converter/filter/AvroFieldsPickConverter.java#L184-L202
26,230
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/CopyEntity.java
CopyEntity.getSerializedWithNewPackage
public static String getSerializedWithNewPackage(String serialized) { serialized = serialized.replace("\"gobblin.data.management.", "\"org.apache.gobblin.data.management."); log.debug("Serialized updated copy entity: " + serialized); return serialized; }
java
public static String getSerializedWithNewPackage(String serialized) { serialized = serialized.replace("\"gobblin.data.management.", "\"org.apache.gobblin.data.management."); log.debug("Serialized updated copy entity: " + serialized); return serialized; }
[ "public", "static", "String", "getSerializedWithNewPackage", "(", "String", "serialized", ")", "{", "serialized", "=", "serialized", ".", "replace", "(", "\"\\\"gobblin.data.management.\"", ",", "\"\\\"org.apache.gobblin.data.management.\"", ")", ";", "log", ".", "debug", "(", "\"Serialized updated copy entity: \"", "+", "serialized", ")", ";", "return", "serialized", ";", "}" ]
Converts package name in serialized string to new name. This is temporary change and should get removed after all the states are switched from old to new package name. @param serialized serialized string possibly having old package names @return
[ "Converts", "package", "name", "in", "serialized", "string", "to", "new", "name", ".", "This", "is", "temporary", "change", "and", "should", "get", "removed", "after", "all", "the", "states", "are", "switched", "from", "old", "to", "new", "package", "name", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/CopyEntity.java#L119-L123
26,231
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/TemplateUtils.java
TemplateUtils.mergeTemplateWithUserCustomizedFile
public static Properties mergeTemplateWithUserCustomizedFile(Properties template, Properties userCustomized) { Properties cleanedTemplate = new Properties(); cleanedTemplate.putAll(template); if (cleanedTemplate.containsKey(ConfigurationKeys.REQUIRED_ATRRIBUTES_LIST)) { cleanedTemplate.remove(ConfigurationKeys.REQUIRED_ATRRIBUTES_LIST); } Properties cleanedUserCustomized = new Properties(); cleanedUserCustomized.putAll(userCustomized); if (cleanedUserCustomized.containsKey(ConfigurationKeys.JOB_TEMPLATE_PATH)) { cleanedUserCustomized.remove(ConfigurationKeys.JOB_TEMPLATE_PATH); } return PropertiesUtils.combineProperties(cleanedTemplate, cleanedUserCustomized); }
java
public static Properties mergeTemplateWithUserCustomizedFile(Properties template, Properties userCustomized) { Properties cleanedTemplate = new Properties(); cleanedTemplate.putAll(template); if (cleanedTemplate.containsKey(ConfigurationKeys.REQUIRED_ATRRIBUTES_LIST)) { cleanedTemplate.remove(ConfigurationKeys.REQUIRED_ATRRIBUTES_LIST); } Properties cleanedUserCustomized = new Properties(); cleanedUserCustomized.putAll(userCustomized); if (cleanedUserCustomized.containsKey(ConfigurationKeys.JOB_TEMPLATE_PATH)) { cleanedUserCustomized.remove(ConfigurationKeys.JOB_TEMPLATE_PATH); } return PropertiesUtils.combineProperties(cleanedTemplate, cleanedUserCustomized); }
[ "public", "static", "Properties", "mergeTemplateWithUserCustomizedFile", "(", "Properties", "template", ",", "Properties", "userCustomized", ")", "{", "Properties", "cleanedTemplate", "=", "new", "Properties", "(", ")", ";", "cleanedTemplate", ".", "putAll", "(", "template", ")", ";", "if", "(", "cleanedTemplate", ".", "containsKey", "(", "ConfigurationKeys", ".", "REQUIRED_ATRRIBUTES_LIST", ")", ")", "{", "cleanedTemplate", ".", "remove", "(", "ConfigurationKeys", ".", "REQUIRED_ATRRIBUTES_LIST", ")", ";", "}", "Properties", "cleanedUserCustomized", "=", "new", "Properties", "(", ")", ";", "cleanedUserCustomized", ".", "putAll", "(", "userCustomized", ")", ";", "if", "(", "cleanedUserCustomized", ".", "containsKey", "(", "ConfigurationKeys", ".", "JOB_TEMPLATE_PATH", ")", ")", "{", "cleanedUserCustomized", ".", "remove", "(", "ConfigurationKeys", ".", "JOB_TEMPLATE_PATH", ")", ";", "}", "return", "PropertiesUtils", ".", "combineProperties", "(", "cleanedTemplate", ",", "cleanedUserCustomized", ")", ";", "}" ]
create a complete property file based on the given template
[ "create", "a", "complete", "property", "file", "based", "on", "the", "given", "template" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/TemplateUtils.java#L28-L43
26,232
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/AbstractJobLauncher.java
AbstractJobLauncher.startCancellationExecutor
protected void startCancellationExecutor() { this.cancellationExecutor.execute(new Runnable() { @Override public void run() { synchronized (AbstractJobLauncher.this.cancellationRequest) { try { while (!AbstractJobLauncher.this.cancellationRequested) { // Wait for a cancellation request to arrive AbstractJobLauncher.this.cancellationRequest.wait(); } LOG.info("Cancellation has been requested for job " + AbstractJobLauncher.this.jobContext.getJobId()); executeCancellation(); LOG.info("Cancellation has been executed for job " + AbstractJobLauncher.this.jobContext.getJobId()); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } synchronized (AbstractJobLauncher.this.cancellationExecution) { AbstractJobLauncher.this.cancellationExecuted = true; AbstractJobLauncher.this.jobContext.getJobState().setState(JobState.RunningState.CANCELLED); // Notify that the cancellation has been executed AbstractJobLauncher.this.cancellationExecution.notifyAll(); } } }); }
java
protected void startCancellationExecutor() { this.cancellationExecutor.execute(new Runnable() { @Override public void run() { synchronized (AbstractJobLauncher.this.cancellationRequest) { try { while (!AbstractJobLauncher.this.cancellationRequested) { // Wait for a cancellation request to arrive AbstractJobLauncher.this.cancellationRequest.wait(); } LOG.info("Cancellation has been requested for job " + AbstractJobLauncher.this.jobContext.getJobId()); executeCancellation(); LOG.info("Cancellation has been executed for job " + AbstractJobLauncher.this.jobContext.getJobId()); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } synchronized (AbstractJobLauncher.this.cancellationExecution) { AbstractJobLauncher.this.cancellationExecuted = true; AbstractJobLauncher.this.jobContext.getJobState().setState(JobState.RunningState.CANCELLED); // Notify that the cancellation has been executed AbstractJobLauncher.this.cancellationExecution.notifyAll(); } } }); }
[ "protected", "void", "startCancellationExecutor", "(", ")", "{", "this", ".", "cancellationExecutor", ".", "execute", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "synchronized", "(", "AbstractJobLauncher", ".", "this", ".", "cancellationRequest", ")", "{", "try", "{", "while", "(", "!", "AbstractJobLauncher", ".", "this", ".", "cancellationRequested", ")", "{", "// Wait for a cancellation request to arrive", "AbstractJobLauncher", ".", "this", ".", "cancellationRequest", ".", "wait", "(", ")", ";", "}", "LOG", ".", "info", "(", "\"Cancellation has been requested for job \"", "+", "AbstractJobLauncher", ".", "this", ".", "jobContext", ".", "getJobId", "(", ")", ")", ";", "executeCancellation", "(", ")", ";", "LOG", ".", "info", "(", "\"Cancellation has been executed for job \"", "+", "AbstractJobLauncher", ".", "this", ".", "jobContext", ".", "getJobId", "(", ")", ")", ";", "}", "catch", "(", "InterruptedException", "ie", ")", "{", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "}", "}", "synchronized", "(", "AbstractJobLauncher", ".", "this", ".", "cancellationExecution", ")", "{", "AbstractJobLauncher", ".", "this", ".", "cancellationExecuted", "=", "true", ";", "AbstractJobLauncher", ".", "this", ".", "jobContext", ".", "getJobState", "(", ")", ".", "setState", "(", "JobState", ".", "RunningState", ".", "CANCELLED", ")", ";", "// Notify that the cancellation has been executed", "AbstractJobLauncher", ".", "this", ".", "cancellationExecution", ".", "notifyAll", "(", ")", ";", "}", "}", "}", ")", ";", "}" ]
Start the scheduled executor for executing job cancellation. <p> The executor, upon started, waits on the condition variable indicating a cancellation is requested, i.e., it waits for a cancellation request to arrive. If a cancellation is requested, the executor is unblocked and calls {@link #executeCancellation()} to execute the cancellation. Upon completion of the cancellation execution, the executor notifies the caller that requested the cancellation on the conditional variable indicating the cancellation has been executed so the caller is unblocked. Upon successful execution of the cancellation, it sets the job state to {@link JobState.RunningState#CANCELLED}. </p>
[ "Start", "the", "scheduled", "executor", "for", "executing", "job", "cancellation", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/AbstractJobLauncher.java#L668-L694
26,233
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/AbstractJobLauncher.java
AbstractJobLauncher.tryLockJob
private boolean tryLockJob(Properties properties) { try { if (Boolean.valueOf(properties.getProperty(ConfigurationKeys.JOB_LOCK_ENABLED_KEY, Boolean.TRUE.toString()))) { this.jobLockOptional = Optional.of(getJobLock(properties, new JobLockEventListener() { @Override public void onLost() { executeCancellation(); } })); } return !this.jobLockOptional.isPresent() || this.jobLockOptional.get().tryLock(); } catch (JobLockException ioe) { LOG.error(String.format("Failed to acquire job lock for job %s: %s", this.jobContext.getJobId(), ioe), ioe); return false; } }
java
private boolean tryLockJob(Properties properties) { try { if (Boolean.valueOf(properties.getProperty(ConfigurationKeys.JOB_LOCK_ENABLED_KEY, Boolean.TRUE.toString()))) { this.jobLockOptional = Optional.of(getJobLock(properties, new JobLockEventListener() { @Override public void onLost() { executeCancellation(); } })); } return !this.jobLockOptional.isPresent() || this.jobLockOptional.get().tryLock(); } catch (JobLockException ioe) { LOG.error(String.format("Failed to acquire job lock for job %s: %s", this.jobContext.getJobId(), ioe), ioe); return false; } }
[ "private", "boolean", "tryLockJob", "(", "Properties", "properties", ")", "{", "try", "{", "if", "(", "Boolean", ".", "valueOf", "(", "properties", ".", "getProperty", "(", "ConfigurationKeys", ".", "JOB_LOCK_ENABLED_KEY", ",", "Boolean", ".", "TRUE", ".", "toString", "(", ")", ")", ")", ")", "{", "this", ".", "jobLockOptional", "=", "Optional", ".", "of", "(", "getJobLock", "(", "properties", ",", "new", "JobLockEventListener", "(", ")", "{", "@", "Override", "public", "void", "onLost", "(", ")", "{", "executeCancellation", "(", ")", ";", "}", "}", ")", ")", ";", "}", "return", "!", "this", ".", "jobLockOptional", ".", "isPresent", "(", ")", "||", "this", ".", "jobLockOptional", ".", "get", "(", ")", ".", "tryLock", "(", ")", ";", "}", "catch", "(", "JobLockException", "ioe", ")", "{", "LOG", ".", "error", "(", "String", ".", "format", "(", "\"Failed to acquire job lock for job %s: %s\"", ",", "this", ".", "jobContext", ".", "getJobId", "(", ")", ",", "ioe", ")", ",", "ioe", ")", ";", "return", "false", ";", "}", "}" ]
Try acquiring the job lock and return whether the lock is successfully locked. @param properties the job properties
[ "Try", "acquiring", "the", "job", "lock", "and", "return", "whether", "the", "lock", "is", "successfully", "locked", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/AbstractJobLauncher.java#L741-L756
26,234
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/AbstractJobLauncher.java
AbstractJobLauncher.unlockJob
private void unlockJob() { if (this.jobLockOptional.isPresent()) { try { // Unlock so the next run of the same job can proceed this.jobLockOptional.get().unlock(); } catch (JobLockException ioe) { LOG.error(String.format("Failed to unlock for job %s: %s", this.jobContext.getJobId(), ioe), ioe); } finally { try { this.jobLockOptional.get().close(); } catch (IOException e) { LOG.error(String.format("Failed to close job lock for job %s: %s", this.jobContext.getJobId(), e), e); } finally { this.jobLockOptional = Optional.absent(); } } } }
java
private void unlockJob() { if (this.jobLockOptional.isPresent()) { try { // Unlock so the next run of the same job can proceed this.jobLockOptional.get().unlock(); } catch (JobLockException ioe) { LOG.error(String.format("Failed to unlock for job %s: %s", this.jobContext.getJobId(), ioe), ioe); } finally { try { this.jobLockOptional.get().close(); } catch (IOException e) { LOG.error(String.format("Failed to close job lock for job %s: %s", this.jobContext.getJobId(), e), e); } finally { this.jobLockOptional = Optional.absent(); } } } }
[ "private", "void", "unlockJob", "(", ")", "{", "if", "(", "this", ".", "jobLockOptional", ".", "isPresent", "(", ")", ")", "{", "try", "{", "// Unlock so the next run of the same job can proceed", "this", ".", "jobLockOptional", ".", "get", "(", ")", ".", "unlock", "(", ")", ";", "}", "catch", "(", "JobLockException", "ioe", ")", "{", "LOG", ".", "error", "(", "String", ".", "format", "(", "\"Failed to unlock for job %s: %s\"", ",", "this", ".", "jobContext", ".", "getJobId", "(", ")", ",", "ioe", ")", ",", "ioe", ")", ";", "}", "finally", "{", "try", "{", "this", ".", "jobLockOptional", ".", "get", "(", ")", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "LOG", ".", "error", "(", "String", ".", "format", "(", "\"Failed to close job lock for job %s: %s\"", ",", "this", ".", "jobContext", ".", "getJobId", "(", ")", ",", "e", ")", ",", "e", ")", ";", "}", "finally", "{", "this", ".", "jobLockOptional", "=", "Optional", ".", "absent", "(", ")", ";", "}", "}", "}", "}" ]
Unlock a completed or failed job.
[ "Unlock", "a", "completed", "or", "failed", "job", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/AbstractJobLauncher.java#L761-L778
26,235
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/AbstractJobLauncher.java
AbstractJobLauncher.cleanLeftoverStagingData
private void cleanLeftoverStagingData(WorkUnitStream workUnits, JobState jobState) throws JobException { if (jobState.getPropAsBoolean(ConfigurationKeys.CLEANUP_STAGING_DATA_BY_INITIALIZER, false)) { //Clean up will be done by initializer. return; } try { if (!canCleanStagingData(jobState)) { LOG.error("Job " + jobState.getJobName() + " has unfinished commit sequences. Will not clean up staging data."); return; } } catch (IOException e) { throw new JobException("Failed to check unfinished commit sequences", e); } try { if (this.jobContext.shouldCleanupStagingDataPerTask()) { if (workUnits.isSafeToMaterialize()) { Closer closer = Closer.create(); Map<String, ParallelRunner> parallelRunners = Maps.newHashMap(); try { for (WorkUnit workUnit : JobLauncherUtils.flattenWorkUnits(workUnits.getMaterializedWorkUnitCollection())) { JobLauncherUtils.cleanTaskStagingData(new WorkUnitState(workUnit, jobState), LOG, closer, parallelRunners); } } catch (Throwable t) { throw closer.rethrow(t); } finally { closer.close(); } } else { throw new RuntimeException("Work unit streams do not support cleaning staging data per task."); } } else { if (jobState.getPropAsBoolean(ConfigurationKeys.CLEANUP_OLD_JOBS_DATA, ConfigurationKeys.DEFAULT_CLEANUP_OLD_JOBS_DATA)) { JobLauncherUtils.cleanUpOldJobData(jobState, LOG, jobContext.getStagingDirProvided(), jobContext.getOutputDirProvided()); } JobLauncherUtils.cleanJobStagingData(jobState, LOG); } } catch (Throwable t) { // Catch Throwable instead of just IOException to make sure failure of this won't affect the current run LOG.error("Failed to clean leftover staging data", t); } }
java
private void cleanLeftoverStagingData(WorkUnitStream workUnits, JobState jobState) throws JobException { if (jobState.getPropAsBoolean(ConfigurationKeys.CLEANUP_STAGING_DATA_BY_INITIALIZER, false)) { //Clean up will be done by initializer. return; } try { if (!canCleanStagingData(jobState)) { LOG.error("Job " + jobState.getJobName() + " has unfinished commit sequences. Will not clean up staging data."); return; } } catch (IOException e) { throw new JobException("Failed to check unfinished commit sequences", e); } try { if (this.jobContext.shouldCleanupStagingDataPerTask()) { if (workUnits.isSafeToMaterialize()) { Closer closer = Closer.create(); Map<String, ParallelRunner> parallelRunners = Maps.newHashMap(); try { for (WorkUnit workUnit : JobLauncherUtils.flattenWorkUnits(workUnits.getMaterializedWorkUnitCollection())) { JobLauncherUtils.cleanTaskStagingData(new WorkUnitState(workUnit, jobState), LOG, closer, parallelRunners); } } catch (Throwable t) { throw closer.rethrow(t); } finally { closer.close(); } } else { throw new RuntimeException("Work unit streams do not support cleaning staging data per task."); } } else { if (jobState.getPropAsBoolean(ConfigurationKeys.CLEANUP_OLD_JOBS_DATA, ConfigurationKeys.DEFAULT_CLEANUP_OLD_JOBS_DATA)) { JobLauncherUtils.cleanUpOldJobData(jobState, LOG, jobContext.getStagingDirProvided(), jobContext.getOutputDirProvided()); } JobLauncherUtils.cleanJobStagingData(jobState, LOG); } } catch (Throwable t) { // Catch Throwable instead of just IOException to make sure failure of this won't affect the current run LOG.error("Failed to clean leftover staging data", t); } }
[ "private", "void", "cleanLeftoverStagingData", "(", "WorkUnitStream", "workUnits", ",", "JobState", "jobState", ")", "throws", "JobException", "{", "if", "(", "jobState", ".", "getPropAsBoolean", "(", "ConfigurationKeys", ".", "CLEANUP_STAGING_DATA_BY_INITIALIZER", ",", "false", ")", ")", "{", "//Clean up will be done by initializer.", "return", ";", "}", "try", "{", "if", "(", "!", "canCleanStagingData", "(", "jobState", ")", ")", "{", "LOG", ".", "error", "(", "\"Job \"", "+", "jobState", ".", "getJobName", "(", ")", "+", "\" has unfinished commit sequences. Will not clean up staging data.\"", ")", ";", "return", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "JobException", "(", "\"Failed to check unfinished commit sequences\"", ",", "e", ")", ";", "}", "try", "{", "if", "(", "this", ".", "jobContext", ".", "shouldCleanupStagingDataPerTask", "(", ")", ")", "{", "if", "(", "workUnits", ".", "isSafeToMaterialize", "(", ")", ")", "{", "Closer", "closer", "=", "Closer", ".", "create", "(", ")", ";", "Map", "<", "String", ",", "ParallelRunner", ">", "parallelRunners", "=", "Maps", ".", "newHashMap", "(", ")", ";", "try", "{", "for", "(", "WorkUnit", "workUnit", ":", "JobLauncherUtils", ".", "flattenWorkUnits", "(", "workUnits", ".", "getMaterializedWorkUnitCollection", "(", ")", ")", ")", "{", "JobLauncherUtils", ".", "cleanTaskStagingData", "(", "new", "WorkUnitState", "(", "workUnit", ",", "jobState", ")", ",", "LOG", ",", "closer", ",", "parallelRunners", ")", ";", "}", "}", "catch", "(", "Throwable", "t", ")", "{", "throw", "closer", ".", "rethrow", "(", "t", ")", ";", "}", "finally", "{", "closer", ".", "close", "(", ")", ";", "}", "}", "else", "{", "throw", "new", "RuntimeException", "(", "\"Work unit streams do not support cleaning staging data per task.\"", ")", ";", "}", "}", "else", "{", "if", "(", "jobState", ".", "getPropAsBoolean", "(", "ConfigurationKeys", ".", "CLEANUP_OLD_JOBS_DATA", ",", "ConfigurationKeys", ".", "DEFAULT_CLEANUP_OLD_JOBS_DATA", ")", ")", "{", "JobLauncherUtils", ".", "cleanUpOldJobData", "(", "jobState", ",", "LOG", ",", "jobContext", ".", "getStagingDirProvided", "(", ")", ",", "jobContext", ".", "getOutputDirProvided", "(", ")", ")", ";", "}", "JobLauncherUtils", ".", "cleanJobStagingData", "(", "jobState", ",", "LOG", ")", ";", "}", "}", "catch", "(", "Throwable", "t", ")", "{", "// Catch Throwable instead of just IOException to make sure failure of this won't affect the current run", "LOG", ".", "error", "(", "\"Failed to clean leftover staging data\"", ",", "t", ")", ";", "}", "}" ]
Cleanup the left-over staging data possibly from the previous run of the job that may have failed and not cleaned up its staging data. Property {@link ConfigurationKeys#CLEANUP_STAGING_DATA_PER_TASK} controls whether to cleanup staging data per task, or to cleanup entire job's staging data at once. Staging data will not be cleaned if the job has unfinished {@link CommitSequence}s.
[ "Cleanup", "the", "left", "-", "over", "staging", "data", "possibly", "from", "the", "previous", "run", "of", "the", "job", "that", "may", "have", "failed", "and", "not", "cleaned", "up", "its", "staging", "data", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/AbstractJobLauncher.java#L832-L875
26,236
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/AbstractJobLauncher.java
AbstractJobLauncher.cleanupStagingData
private void cleanupStagingData(JobState jobState) throws JobException { if (jobState.getPropAsBoolean(ConfigurationKeys.CLEANUP_STAGING_DATA_BY_INITIALIZER, false)) { //Clean up will be done by initializer. return; } try { if (!canCleanStagingData(jobState)) { LOG.error("Job " + jobState.getJobName() + " has unfinished commit sequences. Will not clean up staging data."); return; } } catch (IOException e) { throw new JobException("Failed to check unfinished commit sequences", e); } if (this.jobContext.shouldCleanupStagingDataPerTask()) { cleanupStagingDataPerTask(jobState); } else { cleanupStagingDataForEntireJob(jobState); } }
java
private void cleanupStagingData(JobState jobState) throws JobException { if (jobState.getPropAsBoolean(ConfigurationKeys.CLEANUP_STAGING_DATA_BY_INITIALIZER, false)) { //Clean up will be done by initializer. return; } try { if (!canCleanStagingData(jobState)) { LOG.error("Job " + jobState.getJobName() + " has unfinished commit sequences. Will not clean up staging data."); return; } } catch (IOException e) { throw new JobException("Failed to check unfinished commit sequences", e); } if (this.jobContext.shouldCleanupStagingDataPerTask()) { cleanupStagingDataPerTask(jobState); } else { cleanupStagingDataForEntireJob(jobState); } }
[ "private", "void", "cleanupStagingData", "(", "JobState", "jobState", ")", "throws", "JobException", "{", "if", "(", "jobState", ".", "getPropAsBoolean", "(", "ConfigurationKeys", ".", "CLEANUP_STAGING_DATA_BY_INITIALIZER", ",", "false", ")", ")", "{", "//Clean up will be done by initializer.", "return", ";", "}", "try", "{", "if", "(", "!", "canCleanStagingData", "(", "jobState", ")", ")", "{", "LOG", ".", "error", "(", "\"Job \"", "+", "jobState", ".", "getJobName", "(", ")", "+", "\" has unfinished commit sequences. Will not clean up staging data.\"", ")", ";", "return", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "JobException", "(", "\"Failed to check unfinished commit sequences\"", ",", "e", ")", ";", "}", "if", "(", "this", ".", "jobContext", ".", "shouldCleanupStagingDataPerTask", "(", ")", ")", "{", "cleanupStagingDataPerTask", "(", "jobState", ")", ";", "}", "else", "{", "cleanupStagingDataForEntireJob", "(", "jobState", ")", ";", "}", "}" ]
Cleanup the job's task staging data. This is not doing anything in case job succeeds and data is successfully committed because the staging data has already been moved to the job output directory. But in case the job fails and data is not committed, we want the staging data to be cleaned up. Property {@link ConfigurationKeys#CLEANUP_STAGING_DATA_PER_TASK} controls whether to cleanup staging data per task, or to cleanup entire job's staging data at once. Staging data will not be cleaned if the job has unfinished {@link CommitSequence}s.
[ "Cleanup", "the", "job", "s", "task", "staging", "data", ".", "This", "is", "not", "doing", "anything", "in", "case", "job", "succeeds", "and", "data", "is", "successfully", "committed", "because", "the", "staging", "data", "has", "already", "been", "moved", "to", "the", "job", "output", "directory", ".", "But", "in", "case", "the", "job", "fails", "and", "data", "is", "not", "committed", "we", "want", "the", "staging", "data", "to", "be", "cleaned", "up", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/AbstractJobLauncher.java#L893-L914
26,237
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/AbstractJobLauncher.java
AbstractJobLauncher.canCleanStagingData
private boolean canCleanStagingData(JobState jobState) throws IOException { return this.jobContext.getSemantics() != DeliverySemantics.EXACTLY_ONCE || !this.jobContext.getCommitSequenceStore() .get().exists(jobState.getJobName()); }
java
private boolean canCleanStagingData(JobState jobState) throws IOException { return this.jobContext.getSemantics() != DeliverySemantics.EXACTLY_ONCE || !this.jobContext.getCommitSequenceStore() .get().exists(jobState.getJobName()); }
[ "private", "boolean", "canCleanStagingData", "(", "JobState", "jobState", ")", "throws", "IOException", "{", "return", "this", ".", "jobContext", ".", "getSemantics", "(", ")", "!=", "DeliverySemantics", ".", "EXACTLY_ONCE", "||", "!", "this", ".", "jobContext", ".", "getCommitSequenceStore", "(", ")", ".", "get", "(", ")", ".", "exists", "(", "jobState", ".", "getJobName", "(", ")", ")", ";", "}" ]
Staging data cannot be cleaned if exactly once semantics is used, and the job has unfinished commit sequences.
[ "Staging", "data", "cannot", "be", "cleaned", "if", "exactly", "once", "semantics", "is", "used", "and", "the", "job", "has", "unfinished", "commit", "sequences", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/AbstractJobLauncher.java#L924-L928
26,238
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/api/JobExecutionState.java
JobExecutionState.doRunningStateChange
private void doRunningStateChange(RunningState newState) { RunningState oldState = null; JobExecutionStateListener stateListener = null; this.changeLock.lock(); try { // verify transition if (null == this.runningState) { Preconditions.checkState(RunningState.PENDING == newState); } else { Preconditions.checkState(EXPECTED_PRE_TRANSITION_STATES.get(newState).contains(this.runningState), "unexpected state transition " + this.runningState + " --> " + newState); } oldState = this.runningState; this.runningState = newState; if (this.listener.isPresent()) { stateListener = this.listener.get(); } this.runningStateChanged.signalAll(); } finally { this.changeLock.unlock(); } if (null != stateListener) { stateListener.onStatusChange(this, oldState, newState); } }
java
private void doRunningStateChange(RunningState newState) { RunningState oldState = null; JobExecutionStateListener stateListener = null; this.changeLock.lock(); try { // verify transition if (null == this.runningState) { Preconditions.checkState(RunningState.PENDING == newState); } else { Preconditions.checkState(EXPECTED_PRE_TRANSITION_STATES.get(newState).contains(this.runningState), "unexpected state transition " + this.runningState + " --> " + newState); } oldState = this.runningState; this.runningState = newState; if (this.listener.isPresent()) { stateListener = this.listener.get(); } this.runningStateChanged.signalAll(); } finally { this.changeLock.unlock(); } if (null != stateListener) { stateListener.onStatusChange(this, oldState, newState); } }
[ "private", "void", "doRunningStateChange", "(", "RunningState", "newState", ")", "{", "RunningState", "oldState", "=", "null", ";", "JobExecutionStateListener", "stateListener", "=", "null", ";", "this", ".", "changeLock", ".", "lock", "(", ")", ";", "try", "{", "// verify transition", "if", "(", "null", "==", "this", ".", "runningState", ")", "{", "Preconditions", ".", "checkState", "(", "RunningState", ".", "PENDING", "==", "newState", ")", ";", "}", "else", "{", "Preconditions", ".", "checkState", "(", "EXPECTED_PRE_TRANSITION_STATES", ".", "get", "(", "newState", ")", ".", "contains", "(", "this", ".", "runningState", ")", ",", "\"unexpected state transition \"", "+", "this", ".", "runningState", "+", "\" --> \"", "+", "newState", ")", ";", "}", "oldState", "=", "this", ".", "runningState", ";", "this", ".", "runningState", "=", "newState", ";", "if", "(", "this", ".", "listener", ".", "isPresent", "(", ")", ")", "{", "stateListener", "=", "this", ".", "listener", ".", "get", "(", ")", ";", "}", "this", ".", "runningStateChanged", ".", "signalAll", "(", ")", ";", "}", "finally", "{", "this", ".", "changeLock", ".", "unlock", "(", ")", ";", "}", "if", "(", "null", "!=", "stateListener", ")", "{", "stateListener", ".", "onStatusChange", "(", "this", ",", "oldState", ",", "newState", ")", ";", "}", "}" ]
This must be called only when holding changeLock
[ "This", "must", "be", "called", "only", "when", "holding", "changeLock" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/api/JobExecutionState.java#L173-L200
26,239
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/writer/FsDataWriter.java
FsDataWriter.setStagingFileGroup
protected void setStagingFileGroup() throws IOException { Preconditions.checkArgument(this.fs.exists(this.stagingFile), String.format("Staging output file %s does not exist", this.stagingFile)); if (this.group.isPresent()) { HadoopUtils.setGroup(this.fs, this.stagingFile, this.group.get()); } }
java
protected void setStagingFileGroup() throws IOException { Preconditions.checkArgument(this.fs.exists(this.stagingFile), String.format("Staging output file %s does not exist", this.stagingFile)); if (this.group.isPresent()) { HadoopUtils.setGroup(this.fs, this.stagingFile, this.group.get()); } }
[ "protected", "void", "setStagingFileGroup", "(", ")", "throws", "IOException", "{", "Preconditions", ".", "checkArgument", "(", "this", ".", "fs", ".", "exists", "(", "this", ".", "stagingFile", ")", ",", "String", ".", "format", "(", "\"Staging output file %s does not exist\"", ",", "this", ".", "stagingFile", ")", ")", ";", "if", "(", "this", ".", "group", ".", "isPresent", "(", ")", ")", "{", "HadoopUtils", ".", "setGroup", "(", "this", ".", "fs", ",", "this", ".", "stagingFile", ",", "this", ".", "group", ".", "get", "(", ")", ")", ";", "}", "}" ]
Set the group name of the staging output file. @throws IOException if it fails to set the group name
[ "Set", "the", "group", "name", "of", "the", "staging", "output", "file", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/writer/FsDataWriter.java#L204-L211
26,240
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/conversion/hive/materializer/HiveMaterializer.java
HiveMaterializer.queryResultMaterializationWorkUnit
public static WorkUnit queryResultMaterializationWorkUnit(String query, HiveConverterUtils.StorageFormat storageFormat, StageableTableMetadata destinationTable) { WorkUnit workUnit = new WorkUnit(); workUnit.setProp(MATERIALIZER_MODE_KEY, MaterializerMode.QUERY_RESULT_MATERIALIZATION.name()); workUnit.setProp(STORAGE_FORMAT_KEY, storageFormat.name()); workUnit.setProp(QUERY_RESULT_TO_MATERIALIZE_KEY, query); workUnit.setProp(STAGEABLE_TABLE_METADATA_KEY, HiveSource.GENERICS_AWARE_GSON.toJson(destinationTable)); TaskUtils.setTaskFactoryClass(workUnit, HiveMaterializerTaskFactory.class); HiveTask.disableHiveWatermarker(workUnit); return workUnit; }
java
public static WorkUnit queryResultMaterializationWorkUnit(String query, HiveConverterUtils.StorageFormat storageFormat, StageableTableMetadata destinationTable) { WorkUnit workUnit = new WorkUnit(); workUnit.setProp(MATERIALIZER_MODE_KEY, MaterializerMode.QUERY_RESULT_MATERIALIZATION.name()); workUnit.setProp(STORAGE_FORMAT_KEY, storageFormat.name()); workUnit.setProp(QUERY_RESULT_TO_MATERIALIZE_KEY, query); workUnit.setProp(STAGEABLE_TABLE_METADATA_KEY, HiveSource.GENERICS_AWARE_GSON.toJson(destinationTable)); TaskUtils.setTaskFactoryClass(workUnit, HiveMaterializerTaskFactory.class); HiveTask.disableHiveWatermarker(workUnit); return workUnit; }
[ "public", "static", "WorkUnit", "queryResultMaterializationWorkUnit", "(", "String", "query", ",", "HiveConverterUtils", ".", "StorageFormat", "storageFormat", ",", "StageableTableMetadata", "destinationTable", ")", "{", "WorkUnit", "workUnit", "=", "new", "WorkUnit", "(", ")", ";", "workUnit", ".", "setProp", "(", "MATERIALIZER_MODE_KEY", ",", "MaterializerMode", ".", "QUERY_RESULT_MATERIALIZATION", ".", "name", "(", ")", ")", ";", "workUnit", ".", "setProp", "(", "STORAGE_FORMAT_KEY", ",", "storageFormat", ".", "name", "(", ")", ")", ";", "workUnit", ".", "setProp", "(", "QUERY_RESULT_TO_MATERIALIZE_KEY", ",", "query", ")", ";", "workUnit", ".", "setProp", "(", "STAGEABLE_TABLE_METADATA_KEY", ",", "HiveSource", ".", "GENERICS_AWARE_GSON", ".", "toJson", "(", "destinationTable", ")", ")", ";", "TaskUtils", ".", "setTaskFactoryClass", "(", "workUnit", ",", "HiveMaterializerTaskFactory", ".", "class", ")", ";", "HiveTask", ".", "disableHiveWatermarker", "(", "workUnit", ")", ";", "return", "workUnit", ";", "}" ]
Create a work unit to materialize a query to a target table using a staging table in between. @param query the query to materialize. @param storageFormat format in which target table should be written. @param destinationTable {@link StageableTableMetadata} specifying staging and target tables metadata.
[ "Create", "a", "work", "unit", "to", "materialize", "a", "query", "to", "a", "target", "table", "using", "a", "staging", "table", "in", "between", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/conversion/hive/materializer/HiveMaterializer.java#L95-L105
26,241
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/JobState.java
JobState.filterSkippedTaskStates
public void filterSkippedTaskStates() { List<TaskState> skippedTaskStates = new ArrayList<>(); for (TaskState taskState : this.taskStates.values()) { if (taskState.getWorkingState() == WorkUnitState.WorkingState.SKIPPED) { skippedTaskStates.add(taskState); } } for (TaskState taskState : skippedTaskStates) { removeTaskState(taskState); addSkippedTaskState(taskState); } }
java
public void filterSkippedTaskStates() { List<TaskState> skippedTaskStates = new ArrayList<>(); for (TaskState taskState : this.taskStates.values()) { if (taskState.getWorkingState() == WorkUnitState.WorkingState.SKIPPED) { skippedTaskStates.add(taskState); } } for (TaskState taskState : skippedTaskStates) { removeTaskState(taskState); addSkippedTaskState(taskState); } }
[ "public", "void", "filterSkippedTaskStates", "(", ")", "{", "List", "<", "TaskState", ">", "skippedTaskStates", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "TaskState", "taskState", ":", "this", ".", "taskStates", ".", "values", "(", ")", ")", "{", "if", "(", "taskState", ".", "getWorkingState", "(", ")", "==", "WorkUnitState", ".", "WorkingState", ".", "SKIPPED", ")", "{", "skippedTaskStates", ".", "add", "(", "taskState", ")", ";", "}", "}", "for", "(", "TaskState", "taskState", ":", "skippedTaskStates", ")", "{", "removeTaskState", "(", "taskState", ")", ";", "addSkippedTaskState", "(", "taskState", ")", ";", "}", "}" ]
Filter the task states corresponding to the skipped work units and add it to the skippedTaskStates
[ "Filter", "the", "task", "states", "corresponding", "to", "the", "skipped", "work", "units", "and", "add", "it", "to", "the", "skippedTaskStates" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/JobState.java#L357-L368
26,242
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/JobState.java
JobState.getCompletedTasks
public int getCompletedTasks() { int completedTasks = 0; for (TaskState taskState : this.taskStates.values()) { if (taskState.isCompleted()) { completedTasks++; } } return completedTasks; }
java
public int getCompletedTasks() { int completedTasks = 0; for (TaskState taskState : this.taskStates.values()) { if (taskState.isCompleted()) { completedTasks++; } } return completedTasks; }
[ "public", "int", "getCompletedTasks", "(", ")", "{", "int", "completedTasks", "=", "0", ";", "for", "(", "TaskState", "taskState", ":", "this", ".", "taskStates", ".", "values", "(", ")", ")", "{", "if", "(", "taskState", ".", "isCompleted", "(", ")", ")", "{", "completedTasks", "++", ";", "}", "}", "return", "completedTasks", ";", "}" ]
Get the number of completed tasks. @return number of completed tasks
[ "Get", "the", "number", "of", "completed", "tasks", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/JobState.java#L392-L401
26,243
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/JobState.java
JobState.writeStateSummary
protected void writeStateSummary(JsonWriter jsonWriter) throws IOException { jsonWriter.name("job name").value(this.getJobName()).name("job id").value(this.getJobId()).name("job state") .value(this.getState().name()).name("start time").value(this.getStartTime()).name("end time") .value(this.getEndTime()).name("duration").value(this.getDuration()).name("tasks").value(this.getTaskCount()) .name("completed tasks").value(this.getCompletedTasks()); }
java
protected void writeStateSummary(JsonWriter jsonWriter) throws IOException { jsonWriter.name("job name").value(this.getJobName()).name("job id").value(this.getJobId()).name("job state") .value(this.getState().name()).name("start time").value(this.getStartTime()).name("end time") .value(this.getEndTime()).name("duration").value(this.getDuration()).name("tasks").value(this.getTaskCount()) .name("completed tasks").value(this.getCompletedTasks()); }
[ "protected", "void", "writeStateSummary", "(", "JsonWriter", "jsonWriter", ")", "throws", "IOException", "{", "jsonWriter", ".", "name", "(", "\"job name\"", ")", ".", "value", "(", "this", ".", "getJobName", "(", ")", ")", ".", "name", "(", "\"job id\"", ")", ".", "value", "(", "this", ".", "getJobId", "(", ")", ")", ".", "name", "(", "\"job state\"", ")", ".", "value", "(", "this", ".", "getState", "(", ")", ".", "name", "(", ")", ")", ".", "name", "(", "\"start time\"", ")", ".", "value", "(", "this", ".", "getStartTime", "(", ")", ")", ".", "name", "(", "\"end time\"", ")", ".", "value", "(", "this", ".", "getEndTime", "(", ")", ")", ".", "name", "(", "\"duration\"", ")", ".", "value", "(", "this", ".", "getDuration", "(", ")", ")", ".", "name", "(", "\"tasks\"", ")", ".", "value", "(", "this", ".", "getTaskCount", "(", ")", ")", ".", "name", "(", "\"completed tasks\"", ")", ".", "value", "(", "this", ".", "getCompletedTasks", "(", ")", ")", ";", "}" ]
Write a summary to the json document @param jsonWriter a {@link com.google.gson.stream.JsonWriter} used to write the json document
[ "Write", "a", "summary", "to", "the", "json", "document" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/JobState.java#L614-L619
26,244
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/ApplicationLauncherUtils.java
ApplicationLauncherUtils.newAppId
public static String newAppId(String appName) { String appIdSuffix = String.format("%s_%d", appName, System.currentTimeMillis()); return "app_" + appIdSuffix; }
java
public static String newAppId(String appName) { String appIdSuffix = String.format("%s_%d", appName, System.currentTimeMillis()); return "app_" + appIdSuffix; }
[ "public", "static", "String", "newAppId", "(", "String", "appName", ")", "{", "String", "appIdSuffix", "=", "String", ".", "format", "(", "\"%s_%d\"", ",", "appName", ",", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "return", "\"app_\"", "+", "appIdSuffix", ";", "}" ]
Create a new app ID. @param appName application name @return new app ID
[ "Create", "a", "new", "app", "ID", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/ApplicationLauncherUtils.java#L31-L34
26,245
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/GobblinMultiTaskAttempt.java
GobblinMultiTaskAttempt.taskSuccessfulInPriorAttempt
private boolean taskSuccessfulInPriorAttempt(String taskId) { if (this.taskStateStoreOptional.isPresent()) { StateStore<TaskState> taskStateStore = this.taskStateStoreOptional.get(); // Delete the task state file for the task if it already exists. // This usually happens if the task is retried upon failure. try { if (taskStateStore.exists(jobId, taskId + TASK_STATE_STORE_SUCCESS_MARKER_SUFFIX)) { log.info("Skipping task {} that successfully executed in a prior attempt.", taskId); // skip tasks that executed successfully in a previous attempt return true; } } catch (IOException e) { // if an error while looking up the task state store then treat like it was not processed return false; } } return false; }
java
private boolean taskSuccessfulInPriorAttempt(String taskId) { if (this.taskStateStoreOptional.isPresent()) { StateStore<TaskState> taskStateStore = this.taskStateStoreOptional.get(); // Delete the task state file for the task if it already exists. // This usually happens if the task is retried upon failure. try { if (taskStateStore.exists(jobId, taskId + TASK_STATE_STORE_SUCCESS_MARKER_SUFFIX)) { log.info("Skipping task {} that successfully executed in a prior attempt.", taskId); // skip tasks that executed successfully in a previous attempt return true; } } catch (IOException e) { // if an error while looking up the task state store then treat like it was not processed return false; } } return false; }
[ "private", "boolean", "taskSuccessfulInPriorAttempt", "(", "String", "taskId", ")", "{", "if", "(", "this", ".", "taskStateStoreOptional", ".", "isPresent", "(", ")", ")", "{", "StateStore", "<", "TaskState", ">", "taskStateStore", "=", "this", ".", "taskStateStoreOptional", ".", "get", "(", ")", ";", "// Delete the task state file for the task if it already exists.", "// This usually happens if the task is retried upon failure.", "try", "{", "if", "(", "taskStateStore", ".", "exists", "(", "jobId", ",", "taskId", "+", "TASK_STATE_STORE_SUCCESS_MARKER_SUFFIX", ")", ")", "{", "log", ".", "info", "(", "\"Skipping task {} that successfully executed in a prior attempt.\"", ",", "taskId", ")", ";", "// skip tasks that executed successfully in a previous attempt", "return", "true", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "// if an error while looking up the task state store then treat like it was not processed", "return", "false", ";", "}", "}", "return", "false", ";", "}" ]
Determine if the task executed successfully in a prior attempt by checkitn the task state store for the success marker. @param taskId task id to check @return whether the task was processed successfully in a prior attempt
[ "Determine", "if", "the", "task", "executed", "successfully", "in", "a", "prior", "attempt", "by", "checkitn", "the", "task", "state", "store", "for", "the", "success", "marker", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/GobblinMultiTaskAttempt.java#L328-L347
26,246
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/GobblinMultiTaskAttempt.java
GobblinMultiTaskAttempt.runWorkUnits
public static GobblinMultiTaskAttempt runWorkUnits(JobContext jobContext, Iterator<WorkUnit> workUnits, TaskStateTracker taskStateTracker, TaskExecutor taskExecutor, CommitPolicy multiTaskAttemptCommitPolicy) throws IOException, InterruptedException { GobblinMultiTaskAttempt multiTaskAttempt = new GobblinMultiTaskAttempt(workUnits, jobContext.getJobId(), jobContext.getJobState(), taskStateTracker, taskExecutor, Optional.<String>absent(), Optional.<StateStore<TaskState>>absent(), jobContext.getJobBroker()); multiTaskAttempt.runAndOptionallyCommitTaskAttempt(multiTaskAttemptCommitPolicy); return multiTaskAttempt; }
java
public static GobblinMultiTaskAttempt runWorkUnits(JobContext jobContext, Iterator<WorkUnit> workUnits, TaskStateTracker taskStateTracker, TaskExecutor taskExecutor, CommitPolicy multiTaskAttemptCommitPolicy) throws IOException, InterruptedException { GobblinMultiTaskAttempt multiTaskAttempt = new GobblinMultiTaskAttempt(workUnits, jobContext.getJobId(), jobContext.getJobState(), taskStateTracker, taskExecutor, Optional.<String>absent(), Optional.<StateStore<TaskState>>absent(), jobContext.getJobBroker()); multiTaskAttempt.runAndOptionallyCommitTaskAttempt(multiTaskAttemptCommitPolicy); return multiTaskAttempt; }
[ "public", "static", "GobblinMultiTaskAttempt", "runWorkUnits", "(", "JobContext", "jobContext", ",", "Iterator", "<", "WorkUnit", ">", "workUnits", ",", "TaskStateTracker", "taskStateTracker", ",", "TaskExecutor", "taskExecutor", ",", "CommitPolicy", "multiTaskAttemptCommitPolicy", ")", "throws", "IOException", ",", "InterruptedException", "{", "GobblinMultiTaskAttempt", "multiTaskAttempt", "=", "new", "GobblinMultiTaskAttempt", "(", "workUnits", ",", "jobContext", ".", "getJobId", "(", ")", ",", "jobContext", ".", "getJobState", "(", ")", ",", "taskStateTracker", ",", "taskExecutor", ",", "Optional", ".", "<", "String", ">", "absent", "(", ")", ",", "Optional", ".", "<", "StateStore", "<", "TaskState", ">", ">", "absent", "(", ")", ",", "jobContext", ".", "getJobBroker", "(", ")", ")", ";", "multiTaskAttempt", ".", "runAndOptionallyCommitTaskAttempt", "(", "multiTaskAttemptCommitPolicy", ")", ";", "return", "multiTaskAttempt", ";", "}" ]
FIXME this method is provided for backwards compatibility in the LocalJobLauncher since it does not access the task state store. This should be addressed as all task executions should be updating the task state.
[ "FIXME", "this", "method", "is", "provided", "for", "backwards", "compatibility", "in", "the", "LocalJobLauncher", "since", "it", "does", "not", "access", "the", "task", "state", "store", ".", "This", "should", "be", "addressed", "as", "all", "task", "executions", "should", "be", "updating", "the", "task", "state", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/GobblinMultiTaskAttempt.java#L467-L476
26,247
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/JobContext.java
JobContext.storeJobExecutionInfo
void storeJobExecutionInfo() { if (this.jobHistoryStoreOptional.isPresent()) { try { this.logger.info("Writing job execution information to the job history store"); this.jobHistoryStoreOptional.get().put(this.jobState.toJobExecutionInfo()); } catch (IOException ioe) { this.logger.error("Failed to write job execution information to the job history store: " + ioe, ioe); } } }
java
void storeJobExecutionInfo() { if (this.jobHistoryStoreOptional.isPresent()) { try { this.logger.info("Writing job execution information to the job history store"); this.jobHistoryStoreOptional.get().put(this.jobState.toJobExecutionInfo()); } catch (IOException ioe) { this.logger.error("Failed to write job execution information to the job history store: " + ioe, ioe); } } }
[ "void", "storeJobExecutionInfo", "(", ")", "{", "if", "(", "this", ".", "jobHistoryStoreOptional", ".", "isPresent", "(", ")", ")", "{", "try", "{", "this", ".", "logger", ".", "info", "(", "\"Writing job execution information to the job history store\"", ")", ";", "this", ".", "jobHistoryStoreOptional", ".", "get", "(", ")", ".", "put", "(", "this", ".", "jobState", ".", "toJobExecutionInfo", "(", ")", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "this", ".", "logger", ".", "error", "(", "\"Failed to write job execution information to the job history store: \"", "+", "ioe", ",", "ioe", ")", ";", "}", "}", "}" ]
Store job execution information into the job history store.
[ "Store", "job", "execution", "information", "into", "the", "job", "history", "store", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/JobContext.java#L402-L411
26,248
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/JobContext.java
JobContext.commit
void commit(final boolean isJobCancelled) throws IOException { this.datasetStatesByUrns = Optional.of(computeDatasetStatesByUrns()); final boolean shouldCommitDataInJob = shouldCommitDataInJob(this.jobState); final DeliverySemantics deliverySemantics = DeliverySemantics.parse(this.jobState); final int numCommitThreads = numCommitThreads(); if (!shouldCommitDataInJob) { this.logger.info("Job will not commit data since data are committed by tasks."); } try { if (this.datasetStatesByUrns.isPresent()) { this.logger.info("Persisting dataset urns."); this.datasetStateStore.persistDatasetURNs(this.jobName, this.datasetStatesByUrns.get().keySet()); } List<Either<Void, ExecutionException>> result = new IteratorExecutor<>(Iterables .transform(this.datasetStatesByUrns.get().entrySet(), new Function<Map.Entry<String, DatasetState>, Callable<Void>>() { @Nullable @Override public Callable<Void> apply(final Map.Entry<String, DatasetState> entry) { return createSafeDatasetCommit(shouldCommitDataInJob, isJobCancelled, deliverySemantics, entry.getKey(), entry.getValue(), numCommitThreads > 1, JobContext.this); } }).iterator(), numCommitThreads, ExecutorsUtils.newThreadFactory(Optional.of(this.logger), Optional.of("Commit-thread-%d"))) .executeAndGetResults(); IteratorExecutor.logFailures(result, LOG, 10); if (!IteratorExecutor.verifyAllSuccessful(result)) { this.jobState.setState(JobState.RunningState.FAILED); throw new IOException("Failed to commit dataset state for some dataset(s) of job " + this.jobId); } } catch (InterruptedException exc) { throw new IOException(exc); } this.jobState.setState(JobState.RunningState.COMMITTED); }
java
void commit(final boolean isJobCancelled) throws IOException { this.datasetStatesByUrns = Optional.of(computeDatasetStatesByUrns()); final boolean shouldCommitDataInJob = shouldCommitDataInJob(this.jobState); final DeliverySemantics deliverySemantics = DeliverySemantics.parse(this.jobState); final int numCommitThreads = numCommitThreads(); if (!shouldCommitDataInJob) { this.logger.info("Job will not commit data since data are committed by tasks."); } try { if (this.datasetStatesByUrns.isPresent()) { this.logger.info("Persisting dataset urns."); this.datasetStateStore.persistDatasetURNs(this.jobName, this.datasetStatesByUrns.get().keySet()); } List<Either<Void, ExecutionException>> result = new IteratorExecutor<>(Iterables .transform(this.datasetStatesByUrns.get().entrySet(), new Function<Map.Entry<String, DatasetState>, Callable<Void>>() { @Nullable @Override public Callable<Void> apply(final Map.Entry<String, DatasetState> entry) { return createSafeDatasetCommit(shouldCommitDataInJob, isJobCancelled, deliverySemantics, entry.getKey(), entry.getValue(), numCommitThreads > 1, JobContext.this); } }).iterator(), numCommitThreads, ExecutorsUtils.newThreadFactory(Optional.of(this.logger), Optional.of("Commit-thread-%d"))) .executeAndGetResults(); IteratorExecutor.logFailures(result, LOG, 10); if (!IteratorExecutor.verifyAllSuccessful(result)) { this.jobState.setState(JobState.RunningState.FAILED); throw new IOException("Failed to commit dataset state for some dataset(s) of job " + this.jobId); } } catch (InterruptedException exc) { throw new IOException(exc); } this.jobState.setState(JobState.RunningState.COMMITTED); }
[ "void", "commit", "(", "final", "boolean", "isJobCancelled", ")", "throws", "IOException", "{", "this", ".", "datasetStatesByUrns", "=", "Optional", ".", "of", "(", "computeDatasetStatesByUrns", "(", ")", ")", ";", "final", "boolean", "shouldCommitDataInJob", "=", "shouldCommitDataInJob", "(", "this", ".", "jobState", ")", ";", "final", "DeliverySemantics", "deliverySemantics", "=", "DeliverySemantics", ".", "parse", "(", "this", ".", "jobState", ")", ";", "final", "int", "numCommitThreads", "=", "numCommitThreads", "(", ")", ";", "if", "(", "!", "shouldCommitDataInJob", ")", "{", "this", ".", "logger", ".", "info", "(", "\"Job will not commit data since data are committed by tasks.\"", ")", ";", "}", "try", "{", "if", "(", "this", ".", "datasetStatesByUrns", ".", "isPresent", "(", ")", ")", "{", "this", ".", "logger", ".", "info", "(", "\"Persisting dataset urns.\"", ")", ";", "this", ".", "datasetStateStore", ".", "persistDatasetURNs", "(", "this", ".", "jobName", ",", "this", ".", "datasetStatesByUrns", ".", "get", "(", ")", ".", "keySet", "(", ")", ")", ";", "}", "List", "<", "Either", "<", "Void", ",", "ExecutionException", ">", ">", "result", "=", "new", "IteratorExecutor", "<>", "(", "Iterables", ".", "transform", "(", "this", ".", "datasetStatesByUrns", ".", "get", "(", ")", ".", "entrySet", "(", ")", ",", "new", "Function", "<", "Map", ".", "Entry", "<", "String", ",", "DatasetState", ">", ",", "Callable", "<", "Void", ">", ">", "(", ")", "{", "@", "Nullable", "@", "Override", "public", "Callable", "<", "Void", ">", "apply", "(", "final", "Map", ".", "Entry", "<", "String", ",", "DatasetState", ">", "entry", ")", "{", "return", "createSafeDatasetCommit", "(", "shouldCommitDataInJob", ",", "isJobCancelled", ",", "deliverySemantics", ",", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ",", "numCommitThreads", ">", "1", ",", "JobContext", ".", "this", ")", ";", "}", "}", ")", ".", "iterator", "(", ")", ",", "numCommitThreads", ",", "ExecutorsUtils", ".", "newThreadFactory", "(", "Optional", ".", "of", "(", "this", ".", "logger", ")", ",", "Optional", ".", "of", "(", "\"Commit-thread-%d\"", ")", ")", ")", ".", "executeAndGetResults", "(", ")", ";", "IteratorExecutor", ".", "logFailures", "(", "result", ",", "LOG", ",", "10", ")", ";", "if", "(", "!", "IteratorExecutor", ".", "verifyAllSuccessful", "(", "result", ")", ")", "{", "this", ".", "jobState", ".", "setState", "(", "JobState", ".", "RunningState", ".", "FAILED", ")", ";", "throw", "new", "IOException", "(", "\"Failed to commit dataset state for some dataset(s) of job \"", "+", "this", ".", "jobId", ")", ";", "}", "}", "catch", "(", "InterruptedException", "exc", ")", "{", "throw", "new", "IOException", "(", "exc", ")", ";", "}", "this", ".", "jobState", ".", "setState", "(", "JobState", ".", "RunningState", ".", "COMMITTED", ")", ";", "}" ]
Commit the job based on whether the job is cancelled.
[ "Commit", "the", "job", "based", "on", "whether", "the", "job", "is", "cancelled", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/JobContext.java#L445-L485
26,249
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/JobContext.java
JobContext.createSafeDatasetCommit
@VisibleForTesting protected Callable<Void> createSafeDatasetCommit(boolean shouldCommitDataInJob, boolean isJobCancelled, DeliverySemantics deliverySemantics, String datasetUrn, JobState.DatasetState datasetState, boolean isMultithreaded, JobContext jobContext) { return new SafeDatasetCommit(shouldCommitDataInJob, isJobCancelled, deliverySemantics, datasetUrn, datasetState, isMultithreaded, jobContext); }
java
@VisibleForTesting protected Callable<Void> createSafeDatasetCommit(boolean shouldCommitDataInJob, boolean isJobCancelled, DeliverySemantics deliverySemantics, String datasetUrn, JobState.DatasetState datasetState, boolean isMultithreaded, JobContext jobContext) { return new SafeDatasetCommit(shouldCommitDataInJob, isJobCancelled, deliverySemantics, datasetUrn, datasetState, isMultithreaded, jobContext); }
[ "@", "VisibleForTesting", "protected", "Callable", "<", "Void", ">", "createSafeDatasetCommit", "(", "boolean", "shouldCommitDataInJob", ",", "boolean", "isJobCancelled", ",", "DeliverySemantics", "deliverySemantics", ",", "String", "datasetUrn", ",", "JobState", ".", "DatasetState", "datasetState", ",", "boolean", "isMultithreaded", ",", "JobContext", "jobContext", ")", "{", "return", "new", "SafeDatasetCommit", "(", "shouldCommitDataInJob", ",", "isJobCancelled", ",", "deliverySemantics", ",", "datasetUrn", ",", "datasetState", ",", "isMultithreaded", ",", "jobContext", ")", ";", "}" ]
The only reason for this methods is so that we can test the parallelization of commits. DO NOT OVERRIDE.
[ "The", "only", "reason", "for", "this", "methods", "is", "so", "that", "we", "can", "test", "the", "parallelization", "of", "commits", ".", "DO", "NOT", "OVERRIDE", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/JobContext.java#L501-L507
26,250
apache/incubator-gobblin
gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/writer/initializer/JdbcWriterInitializer.java
JdbcWriterInitializer.validateInput
private static void validateInput(State state) { int branches = state.getPropAsInt(ConfigurationKeys.FORK_BRANCHES_KEY, 1); Set<String> publishTables = Sets.newHashSet(); for (int branchId = 0; branchId < branches; branchId++) { String publishTable = Preconditions.checkNotNull(getProp(state, JdbcPublisher.JDBC_PUBLISHER_FINAL_TABLE_NAME, branches, branchId), JdbcPublisher.JDBC_PUBLISHER_FINAL_TABLE_NAME + " should not be null."); if (publishTables.contains(publishTable)) { throw new IllegalArgumentException( "Duplicate " + JdbcPublisher.JDBC_PUBLISHER_FINAL_TABLE_NAME + " is not allowed across branches"); } publishTables.add(publishTable); } Set<String> stagingTables = Sets.newHashSet(); for (int branchId = 0; branchId < branches; branchId++) { String stagingTable = getProp(state, ConfigurationKeys.WRITER_STAGING_TABLE, branches, branchId); if (!StringUtils.isEmpty(stagingTable) && stagingTables.contains(stagingTable)) { throw new IllegalArgumentException( "Duplicate " + ConfigurationKeys.WRITER_STAGING_TABLE + " is not allowed across branches"); } stagingTables.add(stagingTable); } JobCommitPolicy policy = JobCommitPolicy.getCommitPolicy(state); boolean isPublishJobLevel = state.getPropAsBoolean(ConfigurationKeys.PUBLISH_DATA_AT_JOB_LEVEL, ConfigurationKeys.DEFAULT_PUBLISH_DATA_AT_JOB_LEVEL); if (JobCommitPolicy.COMMIT_ON_FULL_SUCCESS.equals(policy) ^ isPublishJobLevel) { throw new IllegalArgumentException("Job commit policy should be only " + JobCommitPolicy.COMMIT_ON_FULL_SUCCESS + " when " + ConfigurationKeys.PUBLISH_DATA_AT_JOB_LEVEL + " is true." + " Or Job commit policy should not be " + JobCommitPolicy.COMMIT_ON_FULL_SUCCESS + " and " + ConfigurationKeys.PUBLISH_DATA_AT_JOB_LEVEL + " is false."); } }
java
private static void validateInput(State state) { int branches = state.getPropAsInt(ConfigurationKeys.FORK_BRANCHES_KEY, 1); Set<String> publishTables = Sets.newHashSet(); for (int branchId = 0; branchId < branches; branchId++) { String publishTable = Preconditions.checkNotNull(getProp(state, JdbcPublisher.JDBC_PUBLISHER_FINAL_TABLE_NAME, branches, branchId), JdbcPublisher.JDBC_PUBLISHER_FINAL_TABLE_NAME + " should not be null."); if (publishTables.contains(publishTable)) { throw new IllegalArgumentException( "Duplicate " + JdbcPublisher.JDBC_PUBLISHER_FINAL_TABLE_NAME + " is not allowed across branches"); } publishTables.add(publishTable); } Set<String> stagingTables = Sets.newHashSet(); for (int branchId = 0; branchId < branches; branchId++) { String stagingTable = getProp(state, ConfigurationKeys.WRITER_STAGING_TABLE, branches, branchId); if (!StringUtils.isEmpty(stagingTable) && stagingTables.contains(stagingTable)) { throw new IllegalArgumentException( "Duplicate " + ConfigurationKeys.WRITER_STAGING_TABLE + " is not allowed across branches"); } stagingTables.add(stagingTable); } JobCommitPolicy policy = JobCommitPolicy.getCommitPolicy(state); boolean isPublishJobLevel = state.getPropAsBoolean(ConfigurationKeys.PUBLISH_DATA_AT_JOB_LEVEL, ConfigurationKeys.DEFAULT_PUBLISH_DATA_AT_JOB_LEVEL); if (JobCommitPolicy.COMMIT_ON_FULL_SUCCESS.equals(policy) ^ isPublishJobLevel) { throw new IllegalArgumentException("Job commit policy should be only " + JobCommitPolicy.COMMIT_ON_FULL_SUCCESS + " when " + ConfigurationKeys.PUBLISH_DATA_AT_JOB_LEVEL + " is true." + " Or Job commit policy should not be " + JobCommitPolicy.COMMIT_ON_FULL_SUCCESS + " and " + ConfigurationKeys.PUBLISH_DATA_AT_JOB_LEVEL + " is false."); } }
[ "private", "static", "void", "validateInput", "(", "State", "state", ")", "{", "int", "branches", "=", "state", ".", "getPropAsInt", "(", "ConfigurationKeys", ".", "FORK_BRANCHES_KEY", ",", "1", ")", ";", "Set", "<", "String", ">", "publishTables", "=", "Sets", ".", "newHashSet", "(", ")", ";", "for", "(", "int", "branchId", "=", "0", ";", "branchId", "<", "branches", ";", "branchId", "++", ")", "{", "String", "publishTable", "=", "Preconditions", ".", "checkNotNull", "(", "getProp", "(", "state", ",", "JdbcPublisher", ".", "JDBC_PUBLISHER_FINAL_TABLE_NAME", ",", "branches", ",", "branchId", ")", ",", "JdbcPublisher", ".", "JDBC_PUBLISHER_FINAL_TABLE_NAME", "+", "\" should not be null.\"", ")", ";", "if", "(", "publishTables", ".", "contains", "(", "publishTable", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Duplicate \"", "+", "JdbcPublisher", ".", "JDBC_PUBLISHER_FINAL_TABLE_NAME", "+", "\" is not allowed across branches\"", ")", ";", "}", "publishTables", ".", "add", "(", "publishTable", ")", ";", "}", "Set", "<", "String", ">", "stagingTables", "=", "Sets", ".", "newHashSet", "(", ")", ";", "for", "(", "int", "branchId", "=", "0", ";", "branchId", "<", "branches", ";", "branchId", "++", ")", "{", "String", "stagingTable", "=", "getProp", "(", "state", ",", "ConfigurationKeys", ".", "WRITER_STAGING_TABLE", ",", "branches", ",", "branchId", ")", ";", "if", "(", "!", "StringUtils", ".", "isEmpty", "(", "stagingTable", ")", "&&", "stagingTables", ".", "contains", "(", "stagingTable", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Duplicate \"", "+", "ConfigurationKeys", ".", "WRITER_STAGING_TABLE", "+", "\" is not allowed across branches\"", ")", ";", "}", "stagingTables", ".", "add", "(", "stagingTable", ")", ";", "}", "JobCommitPolicy", "policy", "=", "JobCommitPolicy", ".", "getCommitPolicy", "(", "state", ")", ";", "boolean", "isPublishJobLevel", "=", "state", ".", "getPropAsBoolean", "(", "ConfigurationKeys", ".", "PUBLISH_DATA_AT_JOB_LEVEL", ",", "ConfigurationKeys", ".", "DEFAULT_PUBLISH_DATA_AT_JOB_LEVEL", ")", ";", "if", "(", "JobCommitPolicy", ".", "COMMIT_ON_FULL_SUCCESS", ".", "equals", "(", "policy", ")", "^", "isPublishJobLevel", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Job commit policy should be only \"", "+", "JobCommitPolicy", ".", "COMMIT_ON_FULL_SUCCESS", "+", "\" when \"", "+", "ConfigurationKeys", ".", "PUBLISH_DATA_AT_JOB_LEVEL", "+", "\" is true.\"", "+", "\" Or Job commit policy should not be \"", "+", "JobCommitPolicy", ".", "COMMIT_ON_FULL_SUCCESS", "+", "\" and \"", "+", "ConfigurationKeys", ".", "PUBLISH_DATA_AT_JOB_LEVEL", "+", "\" is false.\"", ")", ";", "}", "}" ]
1. User should not define same destination table across different branches. 2. User should not define same staging table across different branches. 3. If commit policy is not full, Gobblin will try to write into final table even there's a failure. This will let Gobblin to write in task level. However, publish data at job level is true, it contradicts with the behavior of Gobblin writing in task level. Thus, validate publish data at job level is false if commit policy is not full. @param state
[ "1", ".", "User", "should", "not", "define", "same", "destination", "table", "across", "different", "branches", ".", "2", ".", "User", "should", "not", "define", "same", "staging", "table", "across", "different", "branches", ".", "3", ".", "If", "commit", "policy", "is", "not", "full", "Gobblin", "will", "try", "to", "write", "into", "final", "table", "even", "there", "s", "a", "failure", ".", "This", "will", "let", "Gobblin", "to", "write", "in", "task", "level", ".", "However", "publish", "data", "at", "job", "level", "is", "true", "it", "contradicts", "with", "the", "behavior", "of", "Gobblin", "writing", "in", "task", "level", ".", "Thus", "validate", "publish", "data", "at", "job", "level", "is", "false", "if", "commit", "policy", "is", "not", "full", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/writer/initializer/JdbcWriterInitializer.java#L296-L330
26,251
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/ProxiedFileSystemUtils.java
ProxiedFileSystemUtils.canProxyAs
public static boolean canProxyAs(String userNameToProxyAs, String superUserName, Path superUserKeytabLocation) { try { loginAndProxyAsUser(userNameToProxyAs, superUserName, superUserKeytabLocation); } catch (IOException e) { return false; } return true; }
java
public static boolean canProxyAs(String userNameToProxyAs, String superUserName, Path superUserKeytabLocation) { try { loginAndProxyAsUser(userNameToProxyAs, superUserName, superUserKeytabLocation); } catch (IOException e) { return false; } return true; }
[ "public", "static", "boolean", "canProxyAs", "(", "String", "userNameToProxyAs", ",", "String", "superUserName", ",", "Path", "superUserKeytabLocation", ")", "{", "try", "{", "loginAndProxyAsUser", "(", "userNameToProxyAs", ",", "superUserName", ",", "superUserKeytabLocation", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Returns true if superUserName can proxy as userNameToProxyAs using the specified superUserKeytabLocation, false otherwise.
[ "Returns", "true", "if", "superUserName", "can", "proxy", "as", "userNameToProxyAs", "using", "the", "specified", "superUserKeytabLocation", "false", "otherwise", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/ProxiedFileSystemUtils.java#L189-L196
26,252
apache/incubator-gobblin
gobblin-service/src/main/java/org/apache/gobblin/service/modules/flow/BaseFlowToJobSpecCompiler.java
BaseFlowToJobSpecCompiler.jobSpecGenerator
protected JobSpec jobSpecGenerator(FlowSpec flowSpec) { JobSpec jobSpec; JobSpec.Builder jobSpecBuilder = JobSpec.builder(jobSpecURIGenerator(flowSpec)) .withConfig(flowSpec.getConfig()) .withDescription(flowSpec.getDescription()) .withVersion(flowSpec.getVersion()); if (flowSpec.getTemplateURIs().isPresent() && templateCatalog.isPresent()) { // Only first template uri will be honored for Identity jobSpecBuilder = jobSpecBuilder.withTemplate(flowSpec.getTemplateURIs().get().iterator().next()); try { jobSpec = new ResolvedJobSpec(jobSpecBuilder.build(), templateCatalog.get()); log.info("Resolved JobSpec properties are: " + jobSpec.getConfigAsProperties()); } catch (SpecNotFoundException | JobTemplate.TemplateException e) { throw new RuntimeException("Could not resolve template in JobSpec from TemplateCatalog", e); } } else { jobSpec = jobSpecBuilder.build(); log.info("Unresolved JobSpec properties are: " + jobSpec.getConfigAsProperties()); } // Remove schedule jobSpec.setConfig(jobSpec.getConfig().withoutPath(ConfigurationKeys.JOB_SCHEDULE_KEY)); // Add job.name and job.group if (flowSpec.getConfig().hasPath(ConfigurationKeys.FLOW_NAME_KEY)) { jobSpec.setConfig(jobSpec.getConfig() .withValue(ConfigurationKeys.JOB_NAME_KEY, flowSpec.getConfig().getValue(ConfigurationKeys.FLOW_NAME_KEY))); } if (flowSpec.getConfig().hasPath(ConfigurationKeys.FLOW_GROUP_KEY)) { jobSpec.setConfig(jobSpec.getConfig() .withValue(ConfigurationKeys.JOB_GROUP_KEY, flowSpec.getConfig().getValue(ConfigurationKeys.FLOW_GROUP_KEY))); } // Add flow execution id for this compilation long flowExecutionId = FlowUtils.getOrCreateFlowExecutionId(flowSpec); jobSpec.setConfig(jobSpec.getConfig().withValue(ConfigurationKeys.FLOW_EXECUTION_ID_KEY, ConfigValueFactory.fromAnyRef(flowExecutionId))); // Reset properties in Spec from Config jobSpec.setConfigAsProperties(ConfigUtils.configToProperties(jobSpec.getConfig())); return jobSpec; }
java
protected JobSpec jobSpecGenerator(FlowSpec flowSpec) { JobSpec jobSpec; JobSpec.Builder jobSpecBuilder = JobSpec.builder(jobSpecURIGenerator(flowSpec)) .withConfig(flowSpec.getConfig()) .withDescription(flowSpec.getDescription()) .withVersion(flowSpec.getVersion()); if (flowSpec.getTemplateURIs().isPresent() && templateCatalog.isPresent()) { // Only first template uri will be honored for Identity jobSpecBuilder = jobSpecBuilder.withTemplate(flowSpec.getTemplateURIs().get().iterator().next()); try { jobSpec = new ResolvedJobSpec(jobSpecBuilder.build(), templateCatalog.get()); log.info("Resolved JobSpec properties are: " + jobSpec.getConfigAsProperties()); } catch (SpecNotFoundException | JobTemplate.TemplateException e) { throw new RuntimeException("Could not resolve template in JobSpec from TemplateCatalog", e); } } else { jobSpec = jobSpecBuilder.build(); log.info("Unresolved JobSpec properties are: " + jobSpec.getConfigAsProperties()); } // Remove schedule jobSpec.setConfig(jobSpec.getConfig().withoutPath(ConfigurationKeys.JOB_SCHEDULE_KEY)); // Add job.name and job.group if (flowSpec.getConfig().hasPath(ConfigurationKeys.FLOW_NAME_KEY)) { jobSpec.setConfig(jobSpec.getConfig() .withValue(ConfigurationKeys.JOB_NAME_KEY, flowSpec.getConfig().getValue(ConfigurationKeys.FLOW_NAME_KEY))); } if (flowSpec.getConfig().hasPath(ConfigurationKeys.FLOW_GROUP_KEY)) { jobSpec.setConfig(jobSpec.getConfig() .withValue(ConfigurationKeys.JOB_GROUP_KEY, flowSpec.getConfig().getValue(ConfigurationKeys.FLOW_GROUP_KEY))); } // Add flow execution id for this compilation long flowExecutionId = FlowUtils.getOrCreateFlowExecutionId(flowSpec); jobSpec.setConfig(jobSpec.getConfig().withValue(ConfigurationKeys.FLOW_EXECUTION_ID_KEY, ConfigValueFactory.fromAnyRef(flowExecutionId))); // Reset properties in Spec from Config jobSpec.setConfigAsProperties(ConfigUtils.configToProperties(jobSpec.getConfig())); return jobSpec; }
[ "protected", "JobSpec", "jobSpecGenerator", "(", "FlowSpec", "flowSpec", ")", "{", "JobSpec", "jobSpec", ";", "JobSpec", ".", "Builder", "jobSpecBuilder", "=", "JobSpec", ".", "builder", "(", "jobSpecURIGenerator", "(", "flowSpec", ")", ")", ".", "withConfig", "(", "flowSpec", ".", "getConfig", "(", ")", ")", ".", "withDescription", "(", "flowSpec", ".", "getDescription", "(", ")", ")", ".", "withVersion", "(", "flowSpec", ".", "getVersion", "(", ")", ")", ";", "if", "(", "flowSpec", ".", "getTemplateURIs", "(", ")", ".", "isPresent", "(", ")", "&&", "templateCatalog", ".", "isPresent", "(", ")", ")", "{", "// Only first template uri will be honored for Identity", "jobSpecBuilder", "=", "jobSpecBuilder", ".", "withTemplate", "(", "flowSpec", ".", "getTemplateURIs", "(", ")", ".", "get", "(", ")", ".", "iterator", "(", ")", ".", "next", "(", ")", ")", ";", "try", "{", "jobSpec", "=", "new", "ResolvedJobSpec", "(", "jobSpecBuilder", ".", "build", "(", ")", ",", "templateCatalog", ".", "get", "(", ")", ")", ";", "log", ".", "info", "(", "\"Resolved JobSpec properties are: \"", "+", "jobSpec", ".", "getConfigAsProperties", "(", ")", ")", ";", "}", "catch", "(", "SpecNotFoundException", "|", "JobTemplate", ".", "TemplateException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Could not resolve template in JobSpec from TemplateCatalog\"", ",", "e", ")", ";", "}", "}", "else", "{", "jobSpec", "=", "jobSpecBuilder", ".", "build", "(", ")", ";", "log", ".", "info", "(", "\"Unresolved JobSpec properties are: \"", "+", "jobSpec", ".", "getConfigAsProperties", "(", ")", ")", ";", "}", "// Remove schedule", "jobSpec", ".", "setConfig", "(", "jobSpec", ".", "getConfig", "(", ")", ".", "withoutPath", "(", "ConfigurationKeys", ".", "JOB_SCHEDULE_KEY", ")", ")", ";", "// Add job.name and job.group", "if", "(", "flowSpec", ".", "getConfig", "(", ")", ".", "hasPath", "(", "ConfigurationKeys", ".", "FLOW_NAME_KEY", ")", ")", "{", "jobSpec", ".", "setConfig", "(", "jobSpec", ".", "getConfig", "(", ")", ".", "withValue", "(", "ConfigurationKeys", ".", "JOB_NAME_KEY", ",", "flowSpec", ".", "getConfig", "(", ")", ".", "getValue", "(", "ConfigurationKeys", ".", "FLOW_NAME_KEY", ")", ")", ")", ";", "}", "if", "(", "flowSpec", ".", "getConfig", "(", ")", ".", "hasPath", "(", "ConfigurationKeys", ".", "FLOW_GROUP_KEY", ")", ")", "{", "jobSpec", ".", "setConfig", "(", "jobSpec", ".", "getConfig", "(", ")", ".", "withValue", "(", "ConfigurationKeys", ".", "JOB_GROUP_KEY", ",", "flowSpec", ".", "getConfig", "(", ")", ".", "getValue", "(", "ConfigurationKeys", ".", "FLOW_GROUP_KEY", ")", ")", ")", ";", "}", "// Add flow execution id for this compilation", "long", "flowExecutionId", "=", "FlowUtils", ".", "getOrCreateFlowExecutionId", "(", "flowSpec", ")", ";", "jobSpec", ".", "setConfig", "(", "jobSpec", ".", "getConfig", "(", ")", ".", "withValue", "(", "ConfigurationKeys", ".", "FLOW_EXECUTION_ID_KEY", ",", "ConfigValueFactory", ".", "fromAnyRef", "(", "flowExecutionId", ")", ")", ")", ";", "// Reset properties in Spec from Config", "jobSpec", ".", "setConfigAsProperties", "(", "ConfigUtils", ".", "configToProperties", "(", "jobSpec", ".", "getConfig", "(", ")", ")", ")", ";", "return", "jobSpec", ";", "}" ]
Naive implementation of generating jobSpec, which fetch the first available template, in an exemplified single-hop FlowCompiler implementation. @param flowSpec @return
[ "Naive", "implementation", "of", "generating", "jobSpec", "which", "fetch", "the", "first", "available", "template", "in", "an", "exemplified", "single", "-", "hop", "FlowCompiler", "implementation", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-service/src/main/java/org/apache/gobblin/service/modules/flow/BaseFlowToJobSpecCompiler.java#L229-L271
26,253
apache/incubator-gobblin
gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/EventReporter.java
EventReporter.getMetricName
protected String getMetricName(Map<String, String> metadata, String eventName) { return JOINER.join(METRIC_KEY_PREFIX, metadata.get(METADATA_JOB_ID), metadata.get(METADATA_TASK_ID), EVENTS_QUALIFIER, eventName); }
java
protected String getMetricName(Map<String, String> metadata, String eventName) { return JOINER.join(METRIC_KEY_PREFIX, metadata.get(METADATA_JOB_ID), metadata.get(METADATA_TASK_ID), EVENTS_QUALIFIER, eventName); }
[ "protected", "String", "getMetricName", "(", "Map", "<", "String", ",", "String", ">", "metadata", ",", "String", "eventName", ")", "{", "return", "JOINER", ".", "join", "(", "METRIC_KEY_PREFIX", ",", "metadata", ".", "get", "(", "METADATA_JOB_ID", ")", ",", "metadata", ".", "get", "(", "METADATA_TASK_ID", ")", ",", "EVENTS_QUALIFIER", ",", "eventName", ")", ";", "}" ]
Constructs the metric key to be emitted. The actual event name is enriched with the current job and task id to be able to keep track of its origin @param metadata metadata of the actual {@link GobblinTrackingEvent} @param eventName name of the actual {@link GobblinTrackingEvent} @return prefix of the metric key
[ "Constructs", "the", "metric", "key", "to", "be", "emitted", ".", "The", "actual", "event", "name", "is", "enriched", "with", "the", "current", "job", "and", "task", "id", "to", "be", "able", "to", "keep", "track", "of", "its", "origin" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/reporter/EventReporter.java#L168-L171
26,254
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/SerializationUtils.java
SerializationUtils.serializeIntoBytes
public static <T extends Serializable> byte[] serializeIntoBytes(T obj) throws IOException { try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos)) { oos.writeObject(obj); oos.flush(); return bos.toByteArray(); } }
java
public static <T extends Serializable> byte[] serializeIntoBytes(T obj) throws IOException { try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos)) { oos.writeObject(obj); oos.flush(); return bos.toByteArray(); } }
[ "public", "static", "<", "T", "extends", "Serializable", ">", "byte", "[", "]", "serializeIntoBytes", "(", "T", "obj", ")", "throws", "IOException", "{", "try", "(", "ByteArrayOutputStream", "bos", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "ObjectOutputStream", "oos", "=", "new", "ObjectOutputStream", "(", "bos", ")", ")", "{", "oos", ".", "writeObject", "(", "obj", ")", ";", "oos", ".", "flush", "(", ")", ";", "return", "bos", ".", "toByteArray", "(", ")", ";", "}", "}" ]
Serialize an object into a byte array. @param obj A {@link Serializable} object @return Byte serialization of input object @throws IOException if it fails to serialize the object
[ "Serialize", "an", "object", "into", "a", "byte", "array", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/SerializationUtils.java#L77-L84
26,255
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/source/LoopingDatasetFinderSource.java
LoopingDatasetFinderSource.sortStreamLexicographically
private <T extends URNIdentified> Stream<T> sortStreamLexicographically(Stream<T> inputStream) { Spliterator<T> spliterator = inputStream.spliterator(); if (spliterator.hasCharacteristics(Spliterator.SORTED) && spliterator.getComparator() .equals(this.lexicographicalComparator)) { return StreamSupport.stream(spliterator, false); } return StreamSupport.stream(spliterator, false).sorted(this.lexicographicalComparator); }
java
private <T extends URNIdentified> Stream<T> sortStreamLexicographically(Stream<T> inputStream) { Spliterator<T> spliterator = inputStream.spliterator(); if (spliterator.hasCharacteristics(Spliterator.SORTED) && spliterator.getComparator() .equals(this.lexicographicalComparator)) { return StreamSupport.stream(spliterator, false); } return StreamSupport.stream(spliterator, false).sorted(this.lexicographicalComparator); }
[ "private", "<", "T", "extends", "URNIdentified", ">", "Stream", "<", "T", ">", "sortStreamLexicographically", "(", "Stream", "<", "T", ">", "inputStream", ")", "{", "Spliterator", "<", "T", ">", "spliterator", "=", "inputStream", ".", "spliterator", "(", ")", ";", "if", "(", "spliterator", ".", "hasCharacteristics", "(", "Spliterator", ".", "SORTED", ")", "&&", "spliterator", ".", "getComparator", "(", ")", ".", "equals", "(", "this", ".", "lexicographicalComparator", ")", ")", "{", "return", "StreamSupport", ".", "stream", "(", "spliterator", ",", "false", ")", ";", "}", "return", "StreamSupport", ".", "stream", "(", "spliterator", ",", "false", ")", ".", "sorted", "(", "this", ".", "lexicographicalComparator", ")", ";", "}" ]
Sort input stream lexicographically. Noop if the input stream is already sorted.
[ "Sort", "input", "stream", "lexicographically", ".", "Noop", "if", "the", "input", "stream", "is", "already", "sorted", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/source/LoopingDatasetFinderSource.java#L291-L298
26,256
apache/incubator-gobblin
gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/retention/HivePartitionVersionRetentionReaper.java
HivePartitionVersionRetentionReaper.clean
@Override public void clean() throws IOException { Path versionLocation = ((HivePartitionRetentionVersion) this.datasetVersion).getLocation(); Path datasetLocation = ((CleanableHivePartitionDataset) this.cleanableDataset).getLocation(); String completeName = ((HivePartitionRetentionVersion) this.datasetVersion).datasetURN(); State state = new State(this.state); this.versionOwnerFs = ProxyUtils.getOwnerFs(state, this.versionOwner); try (HiveProxyQueryExecutor queryExecutor = ProxyUtils .getQueryExecutor(state, this.versionOwner, this.backUpOwner)) { if (!this.versionOwnerFs.exists(versionLocation)) { log.info("Data versionLocation doesn't exist. Metadata will be dropped for the version " + completeName); } else if (datasetLocation.toString().equalsIgnoreCase(versionLocation.toString())) { log.info( "Dataset location is same as version location. Won't delete the data but metadata will be dropped for the version " + completeName); } else if (this.simulate) { log.info("Simulate is set to true. Won't move the version " + completeName); return; } else if (completeName.contains(ComplianceConfigurationKeys.STAGING)) { log.info("Deleting data from version " + completeName); this.versionOwnerFs.delete(versionLocation, true); } else if (completeName.contains(ComplianceConfigurationKeys.BACKUP)) { executeAlterQueries(queryExecutor); Path newVersionLocationParent = getNewVersionLocation().getParent(); log.info("Creating new dir " + newVersionLocationParent.toString()); this.versionOwnerFs.mkdirs(newVersionLocationParent); log.info("Moving data from " + versionLocation + " to " + getNewVersionLocation()); fsMove(versionLocation, getNewVersionLocation()); FsPermission permission = new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.NONE); HadoopUtils .setPermissions(newVersionLocationParent, this.versionOwner, this.backUpOwner, this.versionOwnerFs, permission); } executeDropVersionQueries(queryExecutor); } }
java
@Override public void clean() throws IOException { Path versionLocation = ((HivePartitionRetentionVersion) this.datasetVersion).getLocation(); Path datasetLocation = ((CleanableHivePartitionDataset) this.cleanableDataset).getLocation(); String completeName = ((HivePartitionRetentionVersion) this.datasetVersion).datasetURN(); State state = new State(this.state); this.versionOwnerFs = ProxyUtils.getOwnerFs(state, this.versionOwner); try (HiveProxyQueryExecutor queryExecutor = ProxyUtils .getQueryExecutor(state, this.versionOwner, this.backUpOwner)) { if (!this.versionOwnerFs.exists(versionLocation)) { log.info("Data versionLocation doesn't exist. Metadata will be dropped for the version " + completeName); } else if (datasetLocation.toString().equalsIgnoreCase(versionLocation.toString())) { log.info( "Dataset location is same as version location. Won't delete the data but metadata will be dropped for the version " + completeName); } else if (this.simulate) { log.info("Simulate is set to true. Won't move the version " + completeName); return; } else if (completeName.contains(ComplianceConfigurationKeys.STAGING)) { log.info("Deleting data from version " + completeName); this.versionOwnerFs.delete(versionLocation, true); } else if (completeName.contains(ComplianceConfigurationKeys.BACKUP)) { executeAlterQueries(queryExecutor); Path newVersionLocationParent = getNewVersionLocation().getParent(); log.info("Creating new dir " + newVersionLocationParent.toString()); this.versionOwnerFs.mkdirs(newVersionLocationParent); log.info("Moving data from " + versionLocation + " to " + getNewVersionLocation()); fsMove(versionLocation, getNewVersionLocation()); FsPermission permission = new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.NONE); HadoopUtils .setPermissions(newVersionLocationParent, this.versionOwner, this.backUpOwner, this.versionOwnerFs, permission); } executeDropVersionQueries(queryExecutor); } }
[ "@", "Override", "public", "void", "clean", "(", ")", "throws", "IOException", "{", "Path", "versionLocation", "=", "(", "(", "HivePartitionRetentionVersion", ")", "this", ".", "datasetVersion", ")", ".", "getLocation", "(", ")", ";", "Path", "datasetLocation", "=", "(", "(", "CleanableHivePartitionDataset", ")", "this", ".", "cleanableDataset", ")", ".", "getLocation", "(", ")", ";", "String", "completeName", "=", "(", "(", "HivePartitionRetentionVersion", ")", "this", ".", "datasetVersion", ")", ".", "datasetURN", "(", ")", ";", "State", "state", "=", "new", "State", "(", "this", ".", "state", ")", ";", "this", ".", "versionOwnerFs", "=", "ProxyUtils", ".", "getOwnerFs", "(", "state", ",", "this", ".", "versionOwner", ")", ";", "try", "(", "HiveProxyQueryExecutor", "queryExecutor", "=", "ProxyUtils", ".", "getQueryExecutor", "(", "state", ",", "this", ".", "versionOwner", ",", "this", ".", "backUpOwner", ")", ")", "{", "if", "(", "!", "this", ".", "versionOwnerFs", ".", "exists", "(", "versionLocation", ")", ")", "{", "log", ".", "info", "(", "\"Data versionLocation doesn't exist. Metadata will be dropped for the version \"", "+", "completeName", ")", ";", "}", "else", "if", "(", "datasetLocation", ".", "toString", "(", ")", ".", "equalsIgnoreCase", "(", "versionLocation", ".", "toString", "(", ")", ")", ")", "{", "log", ".", "info", "(", "\"Dataset location is same as version location. Won't delete the data but metadata will be dropped for the version \"", "+", "completeName", ")", ";", "}", "else", "if", "(", "this", ".", "simulate", ")", "{", "log", ".", "info", "(", "\"Simulate is set to true. Won't move the version \"", "+", "completeName", ")", ";", "return", ";", "}", "else", "if", "(", "completeName", ".", "contains", "(", "ComplianceConfigurationKeys", ".", "STAGING", ")", ")", "{", "log", ".", "info", "(", "\"Deleting data from version \"", "+", "completeName", ")", ";", "this", ".", "versionOwnerFs", ".", "delete", "(", "versionLocation", ",", "true", ")", ";", "}", "else", "if", "(", "completeName", ".", "contains", "(", "ComplianceConfigurationKeys", ".", "BACKUP", ")", ")", "{", "executeAlterQueries", "(", "queryExecutor", ")", ";", "Path", "newVersionLocationParent", "=", "getNewVersionLocation", "(", ")", ".", "getParent", "(", ")", ";", "log", ".", "info", "(", "\"Creating new dir \"", "+", "newVersionLocationParent", ".", "toString", "(", ")", ")", ";", "this", ".", "versionOwnerFs", ".", "mkdirs", "(", "newVersionLocationParent", ")", ";", "log", ".", "info", "(", "\"Moving data from \"", "+", "versionLocation", "+", "\" to \"", "+", "getNewVersionLocation", "(", ")", ")", ";", "fsMove", "(", "versionLocation", ",", "getNewVersionLocation", "(", ")", ")", ";", "FsPermission", "permission", "=", "new", "FsPermission", "(", "FsAction", ".", "ALL", ",", "FsAction", ".", "ALL", ",", "FsAction", ".", "NONE", ")", ";", "HadoopUtils", ".", "setPermissions", "(", "newVersionLocationParent", ",", "this", ".", "versionOwner", ",", "this", ".", "backUpOwner", ",", "this", ".", "versionOwnerFs", ",", "permission", ")", ";", "}", "executeDropVersionQueries", "(", "queryExecutor", ")", ";", "}", "}" ]
If simulate is set to true, will simply return. If a version is pointing to a non-existing location, then drop the partition and close the jdbc connection. If a version is pointing to the same location as of the dataset, then drop the partition and close the jdbc connection. If a version is staging, it's data will be deleted and metadata is dropped. IF a versions is backup, it's data will be moved to a backup dir, current metadata will be dropped and it will be registered in the backup db.
[ "If", "simulate", "is", "set", "to", "true", "will", "simply", "return", ".", "If", "a", "version", "is", "pointing", "to", "a", "non", "-", "existing", "location", "then", "drop", "the", "partition", "and", "close", "the", "jdbc", "connection", ".", "If", "a", "version", "is", "pointing", "to", "the", "same", "location", "as", "of", "the", "dataset", "then", "drop", "the", "partition", "and", "close", "the", "jdbc", "connection", ".", "If", "a", "version", "is", "staging", "it", "s", "data", "will", "be", "deleted", "and", "metadata", "is", "dropped", ".", "IF", "a", "versions", "is", "backup", "it", "s", "data", "will", "be", "moved", "to", "a", "backup", "dir", "current", "metadata", "will", "be", "dropped", "and", "it", "will", "be", "registered", "in", "the", "backup", "db", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/retention/HivePartitionVersionRetentionReaper.java#L83-L122
26,257
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/util/SchedulerUtils.java
SchedulerUtils.loadGenericJobConfigs
public static List<Properties> loadGenericJobConfigs(Properties sysProps) throws ConfigurationException, IOException { Path rootPath = new Path(sysProps.getProperty(ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY)); PullFileLoader loader = new PullFileLoader(rootPath, rootPath.getFileSystem(new Configuration()), getJobConfigurationFileExtensions(sysProps), PullFileLoader.DEFAULT_HOCON_PULL_FILE_EXTENSIONS); Config sysConfig = ConfigUtils.propertiesToConfig(sysProps); Collection<Config> configs = loader.loadPullFilesRecursively(rootPath, sysConfig, true); List<Properties> jobConfigs = Lists.newArrayList(); for (Config config : configs) { try { jobConfigs.add(resolveTemplate(ConfigUtils.configToProperties(config))); } catch (IOException ioe) { LOGGER.error("Could not parse job config at " + ConfigUtils.getString(config, ConfigurationKeys.JOB_CONFIG_FILE_PATH_KEY, "Unknown path"), ioe); } } return jobConfigs; }
java
public static List<Properties> loadGenericJobConfigs(Properties sysProps) throws ConfigurationException, IOException { Path rootPath = new Path(sysProps.getProperty(ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY)); PullFileLoader loader = new PullFileLoader(rootPath, rootPath.getFileSystem(new Configuration()), getJobConfigurationFileExtensions(sysProps), PullFileLoader.DEFAULT_HOCON_PULL_FILE_EXTENSIONS); Config sysConfig = ConfigUtils.propertiesToConfig(sysProps); Collection<Config> configs = loader.loadPullFilesRecursively(rootPath, sysConfig, true); List<Properties> jobConfigs = Lists.newArrayList(); for (Config config : configs) { try { jobConfigs.add(resolveTemplate(ConfigUtils.configToProperties(config))); } catch (IOException ioe) { LOGGER.error("Could not parse job config at " + ConfigUtils.getString(config, ConfigurationKeys.JOB_CONFIG_FILE_PATH_KEY, "Unknown path"), ioe); } } return jobConfigs; }
[ "public", "static", "List", "<", "Properties", ">", "loadGenericJobConfigs", "(", "Properties", "sysProps", ")", "throws", "ConfigurationException", ",", "IOException", "{", "Path", "rootPath", "=", "new", "Path", "(", "sysProps", ".", "getProperty", "(", "ConfigurationKeys", ".", "JOB_CONFIG_FILE_GENERAL_PATH_KEY", ")", ")", ";", "PullFileLoader", "loader", "=", "new", "PullFileLoader", "(", "rootPath", ",", "rootPath", ".", "getFileSystem", "(", "new", "Configuration", "(", ")", ")", ",", "getJobConfigurationFileExtensions", "(", "sysProps", ")", ",", "PullFileLoader", ".", "DEFAULT_HOCON_PULL_FILE_EXTENSIONS", ")", ";", "Config", "sysConfig", "=", "ConfigUtils", ".", "propertiesToConfig", "(", "sysProps", ")", ";", "Collection", "<", "Config", ">", "configs", "=", "loader", ".", "loadPullFilesRecursively", "(", "rootPath", ",", "sysConfig", ",", "true", ")", ";", "List", "<", "Properties", ">", "jobConfigs", "=", "Lists", ".", "newArrayList", "(", ")", ";", "for", "(", "Config", "config", ":", "configs", ")", "{", "try", "{", "jobConfigs", ".", "add", "(", "resolveTemplate", "(", "ConfigUtils", ".", "configToProperties", "(", "config", ")", ")", ")", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "LOGGER", ".", "error", "(", "\"Could not parse job config at \"", "+", "ConfigUtils", ".", "getString", "(", "config", ",", "ConfigurationKeys", ".", "JOB_CONFIG_FILE_PATH_KEY", ",", "\"Unknown path\"", ")", ",", "ioe", ")", ";", "}", "}", "return", "jobConfigs", ";", "}" ]
Load job configuration from job configuration files stored in general file system, located by Path @param sysProps Gobblin framework configuration properties @return a list of job configurations in the form of {@link java.util.Properties}
[ "Load", "job", "configuration", "from", "job", "configuration", "files", "stored", "in", "general", "file", "system", "located", "by", "Path" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/util/SchedulerUtils.java#L68-L88
26,258
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/util/SchedulerUtils.java
SchedulerUtils.loadGenericJobConfig
public static Properties loadGenericJobConfig(Properties sysProps, Path jobConfigPath, Path jobConfigPathDir) throws ConfigurationException, IOException { PullFileLoader loader = new PullFileLoader(jobConfigPathDir, jobConfigPathDir.getFileSystem(new Configuration()), getJobConfigurationFileExtensions(sysProps), PullFileLoader.DEFAULT_HOCON_PULL_FILE_EXTENSIONS); Config sysConfig = ConfigUtils.propertiesToConfig(sysProps); Config config = loader.loadPullFile(jobConfigPath, sysConfig, true); return resolveTemplate(ConfigUtils.configToProperties(config)); }
java
public static Properties loadGenericJobConfig(Properties sysProps, Path jobConfigPath, Path jobConfigPathDir) throws ConfigurationException, IOException { PullFileLoader loader = new PullFileLoader(jobConfigPathDir, jobConfigPathDir.getFileSystem(new Configuration()), getJobConfigurationFileExtensions(sysProps), PullFileLoader.DEFAULT_HOCON_PULL_FILE_EXTENSIONS); Config sysConfig = ConfigUtils.propertiesToConfig(sysProps); Config config = loader.loadPullFile(jobConfigPath, sysConfig, true); return resolveTemplate(ConfigUtils.configToProperties(config)); }
[ "public", "static", "Properties", "loadGenericJobConfig", "(", "Properties", "sysProps", ",", "Path", "jobConfigPath", ",", "Path", "jobConfigPathDir", ")", "throws", "ConfigurationException", ",", "IOException", "{", "PullFileLoader", "loader", "=", "new", "PullFileLoader", "(", "jobConfigPathDir", ",", "jobConfigPathDir", ".", "getFileSystem", "(", "new", "Configuration", "(", ")", ")", ",", "getJobConfigurationFileExtensions", "(", "sysProps", ")", ",", "PullFileLoader", ".", "DEFAULT_HOCON_PULL_FILE_EXTENSIONS", ")", ";", "Config", "sysConfig", "=", "ConfigUtils", ".", "propertiesToConfig", "(", "sysProps", ")", ";", "Config", "config", "=", "loader", ".", "loadPullFile", "(", "jobConfigPath", ",", "sysConfig", ",", "true", ")", ";", "return", "resolveTemplate", "(", "ConfigUtils", ".", "configToProperties", "(", "config", ")", ")", ";", "}" ]
Load a given job configuration file from a general file system. @param sysProps Gobblin framework configuration properties @param jobConfigPath job configuration file to be loaded @param jobConfigPathDir root job configuration file directory @return a job configuration in the form of {@link java.util.Properties}
[ "Load", "a", "given", "job", "configuration", "file", "from", "a", "general", "file", "system", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/util/SchedulerUtils.java#L129-L138
26,259
apache/incubator-gobblin
gobblin-hive-registration/src/main/java/org/apache/gobblin/hive/policy/HiveRegistrationPolicyBase.java
HiveRegistrationPolicyBase.getRuntimePropsEnrichedTblProps
protected State getRuntimePropsEnrichedTblProps() { State tableProps = new State(this.props.getTablePartitionProps()); if (this.props.getRuntimeTableProps().isPresent()){ tableProps.setProp(HiveMetaStoreUtils.RUNTIME_PROPS, this.props.getRuntimeTableProps().get()); } return tableProps; }
java
protected State getRuntimePropsEnrichedTblProps() { State tableProps = new State(this.props.getTablePartitionProps()); if (this.props.getRuntimeTableProps().isPresent()){ tableProps.setProp(HiveMetaStoreUtils.RUNTIME_PROPS, this.props.getRuntimeTableProps().get()); } return tableProps; }
[ "protected", "State", "getRuntimePropsEnrichedTblProps", "(", ")", "{", "State", "tableProps", "=", "new", "State", "(", "this", ".", "props", ".", "getTablePartitionProps", "(", ")", ")", ";", "if", "(", "this", ".", "props", ".", "getRuntimeTableProps", "(", ")", ".", "isPresent", "(", ")", ")", "{", "tableProps", ".", "setProp", "(", "HiveMetaStoreUtils", ".", "RUNTIME_PROPS", ",", "this", ".", "props", ".", "getRuntimeTableProps", "(", ")", ".", "get", "(", ")", ")", ";", "}", "return", "tableProps", ";", "}" ]
Enrich the table-level properties with properties carried over from ingestion runtime. Extend this class to add more runtime properties if required.
[ "Enrich", "the", "table", "-", "level", "properties", "with", "properties", "carried", "over", "from", "ingestion", "runtime", ".", "Extend", "this", "class", "to", "add", "more", "runtime", "properties", "if", "required", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-hive-registration/src/main/java/org/apache/gobblin/hive/policy/HiveRegistrationPolicyBase.java#L377-L383
26,260
apache/incubator-gobblin
gobblin-hive-registration/src/main/java/org/apache/gobblin/hive/policy/HiveRegistrationPolicyBase.java
HiveRegistrationPolicyBase.isNameValid
protected static boolean isNameValid(String name) { Preconditions.checkNotNull(name); name = name.toLowerCase(); return VALID_DB_TABLE_NAME_PATTERN_1.matcher(name).matches() && VALID_DB_TABLE_NAME_PATTERN_2.matcher(name).matches(); }
java
protected static boolean isNameValid(String name) { Preconditions.checkNotNull(name); name = name.toLowerCase(); return VALID_DB_TABLE_NAME_PATTERN_1.matcher(name).matches() && VALID_DB_TABLE_NAME_PATTERN_2.matcher(name).matches(); }
[ "protected", "static", "boolean", "isNameValid", "(", "String", "name", ")", "{", "Preconditions", ".", "checkNotNull", "(", "name", ")", ";", "name", "=", "name", ".", "toLowerCase", "(", ")", ";", "return", "VALID_DB_TABLE_NAME_PATTERN_1", ".", "matcher", "(", "name", ")", ".", "matches", "(", ")", "&&", "VALID_DB_TABLE_NAME_PATTERN_2", ".", "matcher", "(", "name", ")", ".", "matches", "(", ")", ";", "}" ]
Determine whether a database or table name is valid. A name is valid if and only if: it starts with an alphanumeric character, contains only alphanumeric characters and '_', and is NOT composed of numbers only.
[ "Determine", "whether", "a", "database", "or", "table", "name", "is", "valid", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-hive-registration/src/main/java/org/apache/gobblin/hive/policy/HiveRegistrationPolicyBase.java#L399-L404
26,261
liaohuqiu/android-Ultra-Pull-To-Refresh
ptr-lib/src/in/srain/cube/views/ptr/PtrFrameLayout.java
PtrFrameLayout.movePos
private void movePos(float deltaY) { // has reached the top if ((deltaY < 0 && mPtrIndicator.isInStartPosition())) { if (DEBUG) { PtrCLog.e(LOG_TAG, String.format("has reached the top")); } return; } int to = mPtrIndicator.getCurrentPosY() + (int) deltaY; // over top if (mPtrIndicator.willOverTop(to)) { if (DEBUG) { PtrCLog.e(LOG_TAG, String.format("over top")); } to = PtrIndicator.POS_START; } mPtrIndicator.setCurrentPos(to); int change = to - mPtrIndicator.getLastPosY(); updatePos(change); }
java
private void movePos(float deltaY) { // has reached the top if ((deltaY < 0 && mPtrIndicator.isInStartPosition())) { if (DEBUG) { PtrCLog.e(LOG_TAG, String.format("has reached the top")); } return; } int to = mPtrIndicator.getCurrentPosY() + (int) deltaY; // over top if (mPtrIndicator.willOverTop(to)) { if (DEBUG) { PtrCLog.e(LOG_TAG, String.format("over top")); } to = PtrIndicator.POS_START; } mPtrIndicator.setCurrentPos(to); int change = to - mPtrIndicator.getLastPosY(); updatePos(change); }
[ "private", "void", "movePos", "(", "float", "deltaY", ")", "{", "// has reached the top", "if", "(", "(", "deltaY", "<", "0", "&&", "mPtrIndicator", ".", "isInStartPosition", "(", ")", ")", ")", "{", "if", "(", "DEBUG", ")", "{", "PtrCLog", ".", "e", "(", "LOG_TAG", ",", "String", ".", "format", "(", "\"has reached the top\"", ")", ")", ";", "}", "return", ";", "}", "int", "to", "=", "mPtrIndicator", ".", "getCurrentPosY", "(", ")", "+", "(", "int", ")", "deltaY", ";", "// over top", "if", "(", "mPtrIndicator", ".", "willOverTop", "(", "to", ")", ")", "{", "if", "(", "DEBUG", ")", "{", "PtrCLog", ".", "e", "(", "LOG_TAG", ",", "String", ".", "format", "(", "\"over top\"", ")", ")", ";", "}", "to", "=", "PtrIndicator", ".", "POS_START", ";", "}", "mPtrIndicator", ".", "setCurrentPos", "(", "to", ")", ";", "int", "change", "=", "to", "-", "mPtrIndicator", ".", "getLastPosY", "(", ")", ";", "updatePos", "(", "change", ")", ";", "}" ]
if deltaY > 0, move the content down @param deltaY
[ "if", "deltaY", ">", "0", "move", "the", "content", "down" ]
46fdc861243a3d90dca1f5d31f3c82559ee9e4fa
https://github.com/liaohuqiu/android-Ultra-Pull-To-Refresh/blob/46fdc861243a3d90dca1f5d31f3c82559ee9e4fa/ptr-lib/src/in/srain/cube/views/ptr/PtrFrameLayout.java#L353-L375
26,262
liaohuqiu/android-Ultra-Pull-To-Refresh
ptr-lib/src/in/srain/cube/views/ptr/PtrFrameLayout.java
PtrFrameLayout.setRefreshCompleteHook
public void setRefreshCompleteHook(PtrUIHandlerHook hook) { mRefreshCompleteHook = hook; hook.setResumeAction(new Runnable() { @Override public void run() { if (DEBUG) { PtrCLog.d(LOG_TAG, "mRefreshCompleteHook resume."); } notifyUIRefreshComplete(true); } }); }
java
public void setRefreshCompleteHook(PtrUIHandlerHook hook) { mRefreshCompleteHook = hook; hook.setResumeAction(new Runnable() { @Override public void run() { if (DEBUG) { PtrCLog.d(LOG_TAG, "mRefreshCompleteHook resume."); } notifyUIRefreshComplete(true); } }); }
[ "public", "void", "setRefreshCompleteHook", "(", "PtrUIHandlerHook", "hook", ")", "{", "mRefreshCompleteHook", "=", "hook", ";", "hook", ".", "setResumeAction", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "if", "(", "DEBUG", ")", "{", "PtrCLog", ".", "d", "(", "LOG_TAG", ",", "\"mRefreshCompleteHook resume.\"", ")", ";", "}", "notifyUIRefreshComplete", "(", "true", ")", ";", "}", "}", ")", ";", "}" ]
please DO REMEMBER resume the hook @param hook
[ "please", "DO", "REMEMBER", "resume", "the", "hook" ]
46fdc861243a3d90dca1f5d31f3c82559ee9e4fa
https://github.com/liaohuqiu/android-Ultra-Pull-To-Refresh/blob/46fdc861243a3d90dca1f5d31f3c82559ee9e4fa/ptr-lib/src/in/srain/cube/views/ptr/PtrFrameLayout.java#L480-L491
26,263
liaohuqiu/android-Ultra-Pull-To-Refresh
ptr-lib/src/in/srain/cube/views/ptr/PtrFrameLayout.java
PtrFrameLayout.tryToNotifyReset
private boolean tryToNotifyReset() { if ((mStatus == PTR_STATUS_COMPLETE || mStatus == PTR_STATUS_PREPARE) && mPtrIndicator.isInStartPosition()) { if (mPtrUIHandlerHolder.hasHandler()) { mPtrUIHandlerHolder.onUIReset(this); if (DEBUG) { PtrCLog.i(LOG_TAG, "PtrUIHandler: onUIReset"); } } mStatus = PTR_STATUS_INIT; clearFlag(); return true; } return false; }
java
private boolean tryToNotifyReset() { if ((mStatus == PTR_STATUS_COMPLETE || mStatus == PTR_STATUS_PREPARE) && mPtrIndicator.isInStartPosition()) { if (mPtrUIHandlerHolder.hasHandler()) { mPtrUIHandlerHolder.onUIReset(this); if (DEBUG) { PtrCLog.i(LOG_TAG, "PtrUIHandler: onUIReset"); } } mStatus = PTR_STATUS_INIT; clearFlag(); return true; } return false; }
[ "private", "boolean", "tryToNotifyReset", "(", ")", "{", "if", "(", "(", "mStatus", "==", "PTR_STATUS_COMPLETE", "||", "mStatus", "==", "PTR_STATUS_PREPARE", ")", "&&", "mPtrIndicator", ".", "isInStartPosition", "(", ")", ")", "{", "if", "(", "mPtrUIHandlerHolder", ".", "hasHandler", "(", ")", ")", "{", "mPtrUIHandlerHolder", ".", "onUIReset", "(", "this", ")", ";", "if", "(", "DEBUG", ")", "{", "PtrCLog", ".", "i", "(", "LOG_TAG", ",", "\"PtrUIHandler: onUIReset\"", ")", ";", "}", "}", "mStatus", "=", "PTR_STATUS_INIT", ";", "clearFlag", "(", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
If at the top and not in loading, reset
[ "If", "at", "the", "top", "and", "not", "in", "loading", "reset" ]
46fdc861243a3d90dca1f5d31f3c82559ee9e4fa
https://github.com/liaohuqiu/android-Ultra-Pull-To-Refresh/blob/46fdc861243a3d90dca1f5d31f3c82559ee9e4fa/ptr-lib/src/in/srain/cube/views/ptr/PtrFrameLayout.java#L552-L565
26,264
liaohuqiu/android-Ultra-Pull-To-Refresh
ptr-lib/src/in/srain/cube/views/ptr/PtrFrameLayout.java
PtrFrameLayout.notifyUIRefreshComplete
private void notifyUIRefreshComplete(boolean ignoreHook) { /** * After hook operation is done, {@link #notifyUIRefreshComplete} will be call in resume action to ignore hook. */ if (mPtrIndicator.hasLeftStartPosition() && !ignoreHook && mRefreshCompleteHook != null) { if (DEBUG) { PtrCLog.d(LOG_TAG, "notifyUIRefreshComplete mRefreshCompleteHook run."); } mRefreshCompleteHook.takeOver(); return; } if (mPtrUIHandlerHolder.hasHandler()) { if (DEBUG) { PtrCLog.i(LOG_TAG, "PtrUIHandler: onUIRefreshComplete"); } mPtrUIHandlerHolder.onUIRefreshComplete(this); } mPtrIndicator.onUIRefreshComplete(); tryScrollBackToTopAfterComplete(); tryToNotifyReset(); }
java
private void notifyUIRefreshComplete(boolean ignoreHook) { /** * After hook operation is done, {@link #notifyUIRefreshComplete} will be call in resume action to ignore hook. */ if (mPtrIndicator.hasLeftStartPosition() && !ignoreHook && mRefreshCompleteHook != null) { if (DEBUG) { PtrCLog.d(LOG_TAG, "notifyUIRefreshComplete mRefreshCompleteHook run."); } mRefreshCompleteHook.takeOver(); return; } if (mPtrUIHandlerHolder.hasHandler()) { if (DEBUG) { PtrCLog.i(LOG_TAG, "PtrUIHandler: onUIRefreshComplete"); } mPtrUIHandlerHolder.onUIRefreshComplete(this); } mPtrIndicator.onUIRefreshComplete(); tryScrollBackToTopAfterComplete(); tryToNotifyReset(); }
[ "private", "void", "notifyUIRefreshComplete", "(", "boolean", "ignoreHook", ")", "{", "/**\n * After hook operation is done, {@link #notifyUIRefreshComplete} will be call in resume action to ignore hook.\n */", "if", "(", "mPtrIndicator", ".", "hasLeftStartPosition", "(", ")", "&&", "!", "ignoreHook", "&&", "mRefreshCompleteHook", "!=", "null", ")", "{", "if", "(", "DEBUG", ")", "{", "PtrCLog", ".", "d", "(", "LOG_TAG", ",", "\"notifyUIRefreshComplete mRefreshCompleteHook run.\"", ")", ";", "}", "mRefreshCompleteHook", ".", "takeOver", "(", ")", ";", "return", ";", "}", "if", "(", "mPtrUIHandlerHolder", ".", "hasHandler", "(", ")", ")", "{", "if", "(", "DEBUG", ")", "{", "PtrCLog", ".", "i", "(", "LOG_TAG", ",", "\"PtrUIHandler: onUIRefreshComplete\"", ")", ";", "}", "mPtrUIHandlerHolder", ".", "onUIRefreshComplete", "(", "this", ")", ";", "}", "mPtrIndicator", ".", "onUIRefreshComplete", "(", ")", ";", "tryScrollBackToTopAfterComplete", "(", ")", ";", "tryToNotifyReset", "(", ")", ";", "}" ]
Do real refresh work. If there is a hook, execute the hook first. @param ignoreHook
[ "Do", "real", "refresh", "work", ".", "If", "there", "is", "a", "hook", "execute", "the", "hook", "first", "." ]
46fdc861243a3d90dca1f5d31f3c82559ee9e4fa
https://github.com/liaohuqiu/android-Ultra-Pull-To-Refresh/blob/46fdc861243a3d90dca1f5d31f3c82559ee9e4fa/ptr-lib/src/in/srain/cube/views/ptr/PtrFrameLayout.java#L645-L666
26,265
rholder/guava-retrying
src/main/java/com/github/rholder/retry/WaitStrategies.java
WaitStrategies.join
public static WaitStrategy join(WaitStrategy... waitStrategies) { Preconditions.checkState(waitStrategies.length > 0, "Must have at least one wait strategy"); List<WaitStrategy> waitStrategyList = Lists.newArrayList(waitStrategies); Preconditions.checkState(!waitStrategyList.contains(null), "Cannot have a null wait strategy"); return new CompositeWaitStrategy(waitStrategyList); }
java
public static WaitStrategy join(WaitStrategy... waitStrategies) { Preconditions.checkState(waitStrategies.length > 0, "Must have at least one wait strategy"); List<WaitStrategy> waitStrategyList = Lists.newArrayList(waitStrategies); Preconditions.checkState(!waitStrategyList.contains(null), "Cannot have a null wait strategy"); return new CompositeWaitStrategy(waitStrategyList); }
[ "public", "static", "WaitStrategy", "join", "(", "WaitStrategy", "...", "waitStrategies", ")", "{", "Preconditions", ".", "checkState", "(", "waitStrategies", ".", "length", ">", "0", ",", "\"Must have at least one wait strategy\"", ")", ";", "List", "<", "WaitStrategy", ">", "waitStrategyList", "=", "Lists", ".", "newArrayList", "(", "waitStrategies", ")", ";", "Preconditions", ".", "checkState", "(", "!", "waitStrategyList", ".", "contains", "(", "null", ")", ",", "\"Cannot have a null wait strategy\"", ")", ";", "return", "new", "CompositeWaitStrategy", "(", "waitStrategyList", ")", ";", "}" ]
Joins one or more wait strategies to derive a composite wait strategy. The new joined strategy will have a wait time which is total of all wait times computed one after another in order. @param waitStrategies Wait strategies that need to be applied one after another for computing the sleep time. @return A composite wait strategy
[ "Joins", "one", "or", "more", "wait", "strategies", "to", "derive", "a", "composite", "wait", "strategy", ".", "The", "new", "joined", "strategy", "will", "have", "a", "wait", "time", "which", "is", "total", "of", "all", "wait", "times", "computed", "one", "after", "another", "in", "order", "." ]
177b6c9b9f3e7957f404f0bdb8e23374cb1de43f
https://github.com/rholder/guava-retrying/blob/177b6c9b9f3e7957f404f0bdb8e23374cb1de43f/src/main/java/com/github/rholder/retry/WaitStrategies.java#L225-L230
26,266
rholder/guava-retrying
src/main/java/com/github/rholder/retry/RetryerBuilder.java
RetryerBuilder.build
public Retryer<V> build() { AttemptTimeLimiter<V> theAttemptTimeLimiter = attemptTimeLimiter == null ? AttemptTimeLimiters.<V>noTimeLimit() : attemptTimeLimiter; StopStrategy theStopStrategy = stopStrategy == null ? StopStrategies.neverStop() : stopStrategy; WaitStrategy theWaitStrategy = waitStrategy == null ? WaitStrategies.noWait() : waitStrategy; BlockStrategy theBlockStrategy = blockStrategy == null ? BlockStrategies.threadSleepStrategy() : blockStrategy; return new Retryer<V>(theAttemptTimeLimiter, theStopStrategy, theWaitStrategy, theBlockStrategy, rejectionPredicate, listeners); }
java
public Retryer<V> build() { AttemptTimeLimiter<V> theAttemptTimeLimiter = attemptTimeLimiter == null ? AttemptTimeLimiters.<V>noTimeLimit() : attemptTimeLimiter; StopStrategy theStopStrategy = stopStrategy == null ? StopStrategies.neverStop() : stopStrategy; WaitStrategy theWaitStrategy = waitStrategy == null ? WaitStrategies.noWait() : waitStrategy; BlockStrategy theBlockStrategy = blockStrategy == null ? BlockStrategies.threadSleepStrategy() : blockStrategy; return new Retryer<V>(theAttemptTimeLimiter, theStopStrategy, theWaitStrategy, theBlockStrategy, rejectionPredicate, listeners); }
[ "public", "Retryer", "<", "V", ">", "build", "(", ")", "{", "AttemptTimeLimiter", "<", "V", ">", "theAttemptTimeLimiter", "=", "attemptTimeLimiter", "==", "null", "?", "AttemptTimeLimiters", ".", "<", "V", ">", "noTimeLimit", "(", ")", ":", "attemptTimeLimiter", ";", "StopStrategy", "theStopStrategy", "=", "stopStrategy", "==", "null", "?", "StopStrategies", ".", "neverStop", "(", ")", ":", "stopStrategy", ";", "WaitStrategy", "theWaitStrategy", "=", "waitStrategy", "==", "null", "?", "WaitStrategies", ".", "noWait", "(", ")", ":", "waitStrategy", ";", "BlockStrategy", "theBlockStrategy", "=", "blockStrategy", "==", "null", "?", "BlockStrategies", ".", "threadSleepStrategy", "(", ")", ":", "blockStrategy", ";", "return", "new", "Retryer", "<", "V", ">", "(", "theAttemptTimeLimiter", ",", "theStopStrategy", ",", "theWaitStrategy", ",", "theBlockStrategy", ",", "rejectionPredicate", ",", "listeners", ")", ";", "}" ]
Builds the retryer. @return the built retryer.
[ "Builds", "the", "retryer", "." ]
177b6c9b9f3e7957f404f0bdb8e23374cb1de43f
https://github.com/rholder/guava-retrying/blob/177b6c9b9f3e7957f404f0bdb8e23374cb1de43f/src/main/java/com/github/rholder/retry/RetryerBuilder.java#L190-L197
26,267
rholder/guava-retrying
src/main/java/com/github/rholder/retry/Retryer.java
Retryer.call
public V call(Callable<V> callable) throws ExecutionException, RetryException { long startTime = System.nanoTime(); for (int attemptNumber = 1; ; attemptNumber++) { Attempt<V> attempt; try { V result = attemptTimeLimiter.call(callable); attempt = new ResultAttempt<V>(result, attemptNumber, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)); } catch (Throwable t) { attempt = new ExceptionAttempt<V>(t, attemptNumber, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)); } for (RetryListener listener : listeners) { listener.onRetry(attempt); } if (!rejectionPredicate.apply(attempt)) { return attempt.get(); } if (stopStrategy.shouldStop(attempt)) { throw new RetryException(attemptNumber, attempt); } else { long sleepTime = waitStrategy.computeSleepTime(attempt); try { blockStrategy.block(sleepTime); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RetryException(attemptNumber, attempt); } } } }
java
public V call(Callable<V> callable) throws ExecutionException, RetryException { long startTime = System.nanoTime(); for (int attemptNumber = 1; ; attemptNumber++) { Attempt<V> attempt; try { V result = attemptTimeLimiter.call(callable); attempt = new ResultAttempt<V>(result, attemptNumber, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)); } catch (Throwable t) { attempt = new ExceptionAttempt<V>(t, attemptNumber, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)); } for (RetryListener listener : listeners) { listener.onRetry(attempt); } if (!rejectionPredicate.apply(attempt)) { return attempt.get(); } if (stopStrategy.shouldStop(attempt)) { throw new RetryException(attemptNumber, attempt); } else { long sleepTime = waitStrategy.computeSleepTime(attempt); try { blockStrategy.block(sleepTime); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RetryException(attemptNumber, attempt); } } } }
[ "public", "V", "call", "(", "Callable", "<", "V", ">", "callable", ")", "throws", "ExecutionException", ",", "RetryException", "{", "long", "startTime", "=", "System", ".", "nanoTime", "(", ")", ";", "for", "(", "int", "attemptNumber", "=", "1", ";", ";", "attemptNumber", "++", ")", "{", "Attempt", "<", "V", ">", "attempt", ";", "try", "{", "V", "result", "=", "attemptTimeLimiter", ".", "call", "(", "callable", ")", ";", "attempt", "=", "new", "ResultAttempt", "<", "V", ">", "(", "result", ",", "attemptNumber", ",", "TimeUnit", ".", "NANOSECONDS", ".", "toMillis", "(", "System", ".", "nanoTime", "(", ")", "-", "startTime", ")", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "attempt", "=", "new", "ExceptionAttempt", "<", "V", ">", "(", "t", ",", "attemptNumber", ",", "TimeUnit", ".", "NANOSECONDS", ".", "toMillis", "(", "System", ".", "nanoTime", "(", ")", "-", "startTime", ")", ")", ";", "}", "for", "(", "RetryListener", "listener", ":", "listeners", ")", "{", "listener", ".", "onRetry", "(", "attempt", ")", ";", "}", "if", "(", "!", "rejectionPredicate", ".", "apply", "(", "attempt", ")", ")", "{", "return", "attempt", ".", "get", "(", ")", ";", "}", "if", "(", "stopStrategy", ".", "shouldStop", "(", "attempt", ")", ")", "{", "throw", "new", "RetryException", "(", "attemptNumber", ",", "attempt", ")", ";", "}", "else", "{", "long", "sleepTime", "=", "waitStrategy", ".", "computeSleepTime", "(", "attempt", ")", ";", "try", "{", "blockStrategy", ".", "block", "(", "sleepTime", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "throw", "new", "RetryException", "(", "attemptNumber", ",", "attempt", ")", ";", "}", "}", "}", "}" ]
Executes the given callable. If the rejection predicate accepts the attempt, the stop strategy is used to decide if a new attempt must be made. Then the wait strategy is used to decide how much time to sleep and a new attempt is made. @param callable the callable task to be executed @return the computed result of the given callable @throws ExecutionException if the given callable throws an exception, and the rejection predicate considers the attempt as successful. The original exception is wrapped into an ExecutionException. @throws RetryException if all the attempts failed before the stop strategy decided to abort, or the thread was interrupted. Note that if the thread is interrupted, this exception is thrown and the thread's interrupt status is set.
[ "Executes", "the", "given", "callable", ".", "If", "the", "rejection", "predicate", "accepts", "the", "attempt", "the", "stop", "strategy", "is", "used", "to", "decide", "if", "a", "new", "attempt", "must", "be", "made", ".", "Then", "the", "wait", "strategy", "is", "used", "to", "decide", "how", "much", "time", "to", "sleep", "and", "a", "new", "attempt", "is", "made", "." ]
177b6c9b9f3e7957f404f0bdb8e23374cb1de43f
https://github.com/rholder/guava-retrying/blob/177b6c9b9f3e7957f404f0bdb8e23374cb1de43f/src/main/java/com/github/rholder/retry/Retryer.java#L155-L185
26,268
ikew0ng/SwipeBackLayout
library/src/main/java/me/imid/swipebacklayout/lib/Utils.java
Utils.convertActivityToTranslucentBeforeL
public static void convertActivityToTranslucentBeforeL(Activity activity) { try { Class<?>[] classes = Activity.class.getDeclaredClasses(); Class<?> translucentConversionListenerClazz = null; for (Class clazz : classes) { if (clazz.getSimpleName().contains("TranslucentConversionListener")) { translucentConversionListenerClazz = clazz; } } Method method = Activity.class.getDeclaredMethod("convertToTranslucent", translucentConversionListenerClazz); method.setAccessible(true); method.invoke(activity, new Object[] { null }); } catch (Throwable t) { } }
java
public static void convertActivityToTranslucentBeforeL(Activity activity) { try { Class<?>[] classes = Activity.class.getDeclaredClasses(); Class<?> translucentConversionListenerClazz = null; for (Class clazz : classes) { if (clazz.getSimpleName().contains("TranslucentConversionListener")) { translucentConversionListenerClazz = clazz; } } Method method = Activity.class.getDeclaredMethod("convertToTranslucent", translucentConversionListenerClazz); method.setAccessible(true); method.invoke(activity, new Object[] { null }); } catch (Throwable t) { } }
[ "public", "static", "void", "convertActivityToTranslucentBeforeL", "(", "Activity", "activity", ")", "{", "try", "{", "Class", "<", "?", ">", "[", "]", "classes", "=", "Activity", ".", "class", ".", "getDeclaredClasses", "(", ")", ";", "Class", "<", "?", ">", "translucentConversionListenerClazz", "=", "null", ";", "for", "(", "Class", "clazz", ":", "classes", ")", "{", "if", "(", "clazz", ".", "getSimpleName", "(", ")", ".", "contains", "(", "\"TranslucentConversionListener\"", ")", ")", "{", "translucentConversionListenerClazz", "=", "clazz", ";", "}", "}", "Method", "method", "=", "Activity", ".", "class", ".", "getDeclaredMethod", "(", "\"convertToTranslucent\"", ",", "translucentConversionListenerClazz", ")", ";", "method", ".", "setAccessible", "(", "true", ")", ";", "method", ".", "invoke", "(", "activity", ",", "new", "Object", "[", "]", "{", "null", "}", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "}", "}" ]
Calling the convertToTranslucent method on platforms before Android 5.0
[ "Calling", "the", "convertToTranslucent", "method", "on", "platforms", "before", "Android", "5", ".", "0" ]
7c6b0ac424813266cec57db86d65a7c9d9ff5fa6
https://github.com/ikew0ng/SwipeBackLayout/blob/7c6b0ac424813266cec57db86d65a7c9d9ff5fa6/library/src/main/java/me/imid/swipebacklayout/lib/Utils.java#L61-L78
26,269
ikew0ng/SwipeBackLayout
library/src/main/java/me/imid/swipebacklayout/lib/Utils.java
Utils.convertActivityToTranslucentAfterL
private static void convertActivityToTranslucentAfterL(Activity activity) { try { Method getActivityOptions = Activity.class.getDeclaredMethod("getActivityOptions"); getActivityOptions.setAccessible(true); Object options = getActivityOptions.invoke(activity); Class<?>[] classes = Activity.class.getDeclaredClasses(); Class<?> translucentConversionListenerClazz = null; for (Class clazz : classes) { if (clazz.getSimpleName().contains("TranslucentConversionListener")) { translucentConversionListenerClazz = clazz; } } Method convertToTranslucent = Activity.class.getDeclaredMethod("convertToTranslucent", translucentConversionListenerClazz, ActivityOptions.class); convertToTranslucent.setAccessible(true); convertToTranslucent.invoke(activity, null, options); } catch (Throwable t) { } }
java
private static void convertActivityToTranslucentAfterL(Activity activity) { try { Method getActivityOptions = Activity.class.getDeclaredMethod("getActivityOptions"); getActivityOptions.setAccessible(true); Object options = getActivityOptions.invoke(activity); Class<?>[] classes = Activity.class.getDeclaredClasses(); Class<?> translucentConversionListenerClazz = null; for (Class clazz : classes) { if (clazz.getSimpleName().contains("TranslucentConversionListener")) { translucentConversionListenerClazz = clazz; } } Method convertToTranslucent = Activity.class.getDeclaredMethod("convertToTranslucent", translucentConversionListenerClazz, ActivityOptions.class); convertToTranslucent.setAccessible(true); convertToTranslucent.invoke(activity, null, options); } catch (Throwable t) { } }
[ "private", "static", "void", "convertActivityToTranslucentAfterL", "(", "Activity", "activity", ")", "{", "try", "{", "Method", "getActivityOptions", "=", "Activity", ".", "class", ".", "getDeclaredMethod", "(", "\"getActivityOptions\"", ")", ";", "getActivityOptions", ".", "setAccessible", "(", "true", ")", ";", "Object", "options", "=", "getActivityOptions", ".", "invoke", "(", "activity", ")", ";", "Class", "<", "?", ">", "[", "]", "classes", "=", "Activity", ".", "class", ".", "getDeclaredClasses", "(", ")", ";", "Class", "<", "?", ">", "translucentConversionListenerClazz", "=", "null", ";", "for", "(", "Class", "clazz", ":", "classes", ")", "{", "if", "(", "clazz", ".", "getSimpleName", "(", ")", ".", "contains", "(", "\"TranslucentConversionListener\"", ")", ")", "{", "translucentConversionListenerClazz", "=", "clazz", ";", "}", "}", "Method", "convertToTranslucent", "=", "Activity", ".", "class", ".", "getDeclaredMethod", "(", "\"convertToTranslucent\"", ",", "translucentConversionListenerClazz", ",", "ActivityOptions", ".", "class", ")", ";", "convertToTranslucent", ".", "setAccessible", "(", "true", ")", ";", "convertToTranslucent", ".", "invoke", "(", "activity", ",", "null", ",", "options", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "}", "}" ]
Calling the convertToTranslucent method on platforms after Android 5.0
[ "Calling", "the", "convertToTranslucent", "method", "on", "platforms", "after", "Android", "5", ".", "0" ]
7c6b0ac424813266cec57db86d65a7c9d9ff5fa6
https://github.com/ikew0ng/SwipeBackLayout/blob/7c6b0ac424813266cec57db86d65a7c9d9ff5fa6/library/src/main/java/me/imid/swipebacklayout/lib/Utils.java#L83-L102
26,270
ikew0ng/SwipeBackLayout
library/src/main/java/me/imid/swipebacklayout/lib/SwipeBackLayout.java
SwipeBackLayout.addSwipeListener
public void addSwipeListener(SwipeListener listener) { if (mListeners == null) { mListeners = new ArrayList<SwipeListener>(); } mListeners.add(listener); }
java
public void addSwipeListener(SwipeListener listener) { if (mListeners == null) { mListeners = new ArrayList<SwipeListener>(); } mListeners.add(listener); }
[ "public", "void", "addSwipeListener", "(", "SwipeListener", "listener", ")", "{", "if", "(", "mListeners", "==", "null", ")", "{", "mListeners", "=", "new", "ArrayList", "<", "SwipeListener", ">", "(", ")", ";", "}", "mListeners", ".", "add", "(", "listener", ")", ";", "}" ]
Add a callback to be invoked when a swipe event is sent to this view. @param listener the swipe listener to attach to this view
[ "Add", "a", "callback", "to", "be", "invoked", "when", "a", "swipe", "event", "is", "sent", "to", "this", "view", "." ]
7c6b0ac424813266cec57db86d65a7c9d9ff5fa6
https://github.com/ikew0ng/SwipeBackLayout/blob/7c6b0ac424813266cec57db86d65a7c9d9ff5fa6/library/src/main/java/me/imid/swipebacklayout/lib/SwipeBackLayout.java#L245-L250
26,271
ikew0ng/SwipeBackLayout
library/src/main/java/me/imid/swipebacklayout/lib/SwipeBackLayout.java
SwipeBackLayout.setShadow
public void setShadow(Drawable shadow, int edgeFlag) { if ((edgeFlag & EDGE_LEFT) != 0) { mShadowLeft = shadow; } else if ((edgeFlag & EDGE_RIGHT) != 0) { mShadowRight = shadow; } else if ((edgeFlag & EDGE_BOTTOM) != 0) { mShadowBottom = shadow; } invalidate(); }
java
public void setShadow(Drawable shadow, int edgeFlag) { if ((edgeFlag & EDGE_LEFT) != 0) { mShadowLeft = shadow; } else if ((edgeFlag & EDGE_RIGHT) != 0) { mShadowRight = shadow; } else if ((edgeFlag & EDGE_BOTTOM) != 0) { mShadowBottom = shadow; } invalidate(); }
[ "public", "void", "setShadow", "(", "Drawable", "shadow", ",", "int", "edgeFlag", ")", "{", "if", "(", "(", "edgeFlag", "&", "EDGE_LEFT", ")", "!=", "0", ")", "{", "mShadowLeft", "=", "shadow", ";", "}", "else", "if", "(", "(", "edgeFlag", "&", "EDGE_RIGHT", ")", "!=", "0", ")", "{", "mShadowRight", "=", "shadow", ";", "}", "else", "if", "(", "(", "edgeFlag", "&", "EDGE_BOTTOM", ")", "!=", "0", ")", "{", "mShadowBottom", "=", "shadow", ";", "}", "invalidate", "(", ")", ";", "}" ]
Set a drawable used for edge shadow. @param shadow Drawable to use @param edgeFlags Combination of edge flags describing the edge to set @see #EDGE_LEFT @see #EDGE_RIGHT @see #EDGE_BOTTOM
[ "Set", "a", "drawable", "used", "for", "edge", "shadow", "." ]
7c6b0ac424813266cec57db86d65a7c9d9ff5fa6
https://github.com/ikew0ng/SwipeBackLayout/blob/7c6b0ac424813266cec57db86d65a7c9d9ff5fa6/library/src/main/java/me/imid/swipebacklayout/lib/SwipeBackLayout.java#L318-L327
26,272
ikew0ng/SwipeBackLayout
library/src/main/java/me/imid/swipebacklayout/lib/SwipeBackLayout.java
SwipeBackLayout.scrollToFinishActivity
public void scrollToFinishActivity() { final int childWidth = mContentView.getWidth(); final int childHeight = mContentView.getHeight(); int left = 0, top = 0; if ((mEdgeFlag & EDGE_LEFT) != 0) { left = childWidth + mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE; mTrackingEdge = EDGE_LEFT; } else if ((mEdgeFlag & EDGE_RIGHT) != 0) { left = -childWidth - mShadowRight.getIntrinsicWidth() - OVERSCROLL_DISTANCE; mTrackingEdge = EDGE_RIGHT; } else if ((mEdgeFlag & EDGE_BOTTOM) != 0) { top = -childHeight - mShadowBottom.getIntrinsicHeight() - OVERSCROLL_DISTANCE; mTrackingEdge = EDGE_BOTTOM; } mDragHelper.smoothSlideViewTo(mContentView, left, top); invalidate(); }
java
public void scrollToFinishActivity() { final int childWidth = mContentView.getWidth(); final int childHeight = mContentView.getHeight(); int left = 0, top = 0; if ((mEdgeFlag & EDGE_LEFT) != 0) { left = childWidth + mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE; mTrackingEdge = EDGE_LEFT; } else if ((mEdgeFlag & EDGE_RIGHT) != 0) { left = -childWidth - mShadowRight.getIntrinsicWidth() - OVERSCROLL_DISTANCE; mTrackingEdge = EDGE_RIGHT; } else if ((mEdgeFlag & EDGE_BOTTOM) != 0) { top = -childHeight - mShadowBottom.getIntrinsicHeight() - OVERSCROLL_DISTANCE; mTrackingEdge = EDGE_BOTTOM; } mDragHelper.smoothSlideViewTo(mContentView, left, top); invalidate(); }
[ "public", "void", "scrollToFinishActivity", "(", ")", "{", "final", "int", "childWidth", "=", "mContentView", ".", "getWidth", "(", ")", ";", "final", "int", "childHeight", "=", "mContentView", ".", "getHeight", "(", ")", ";", "int", "left", "=", "0", ",", "top", "=", "0", ";", "if", "(", "(", "mEdgeFlag", "&", "EDGE_LEFT", ")", "!=", "0", ")", "{", "left", "=", "childWidth", "+", "mShadowLeft", ".", "getIntrinsicWidth", "(", ")", "+", "OVERSCROLL_DISTANCE", ";", "mTrackingEdge", "=", "EDGE_LEFT", ";", "}", "else", "if", "(", "(", "mEdgeFlag", "&", "EDGE_RIGHT", ")", "!=", "0", ")", "{", "left", "=", "-", "childWidth", "-", "mShadowRight", ".", "getIntrinsicWidth", "(", ")", "-", "OVERSCROLL_DISTANCE", ";", "mTrackingEdge", "=", "EDGE_RIGHT", ";", "}", "else", "if", "(", "(", "mEdgeFlag", "&", "EDGE_BOTTOM", ")", "!=", "0", ")", "{", "top", "=", "-", "childHeight", "-", "mShadowBottom", ".", "getIntrinsicHeight", "(", ")", "-", "OVERSCROLL_DISTANCE", ";", "mTrackingEdge", "=", "EDGE_BOTTOM", ";", "}", "mDragHelper", ".", "smoothSlideViewTo", "(", "mContentView", ",", "left", ",", "top", ")", ";", "invalidate", "(", ")", ";", "}" ]
Scroll out contentView and finish the activity
[ "Scroll", "out", "contentView", "and", "finish", "the", "activity" ]
7c6b0ac424813266cec57db86d65a7c9d9ff5fa6
https://github.com/ikew0ng/SwipeBackLayout/blob/7c6b0ac424813266cec57db86d65a7c9d9ff5fa6/library/src/main/java/me/imid/swipebacklayout/lib/SwipeBackLayout.java#L345-L363
26,273
ikew0ng/SwipeBackLayout
library/src/main/java/me/imid/swipebacklayout/lib/ViewDragHelper.java
ViewDragHelper.setSensitivity
public void setSensitivity(Context context, float sensitivity) { float s = Math.max(0f, Math.min(1.0f, sensitivity)); ViewConfiguration viewConfiguration = ViewConfiguration.get(context); mTouchSlop = (int) (viewConfiguration.getScaledTouchSlop() * (1 / s)); }
java
public void setSensitivity(Context context, float sensitivity) { float s = Math.max(0f, Math.min(1.0f, sensitivity)); ViewConfiguration viewConfiguration = ViewConfiguration.get(context); mTouchSlop = (int) (viewConfiguration.getScaledTouchSlop() * (1 / s)); }
[ "public", "void", "setSensitivity", "(", "Context", "context", ",", "float", "sensitivity", ")", "{", "float", "s", "=", "Math", ".", "max", "(", "0f", ",", "Math", ".", "min", "(", "1.0f", ",", "sensitivity", ")", ")", ";", "ViewConfiguration", "viewConfiguration", "=", "ViewConfiguration", ".", "get", "(", "context", ")", ";", "mTouchSlop", "=", "(", "int", ")", "(", "viewConfiguration", ".", "getScaledTouchSlop", "(", ")", "*", "(", "1", "/", "s", ")", ")", ";", "}" ]
Sets the sensitivity of the dragger. @param context The application context. @param sensitivity value between 0 and 1, the final value for touchSlop = ViewConfiguration.getScaledTouchSlop * (1 / s);
[ "Sets", "the", "sensitivity", "of", "the", "dragger", "." ]
7c6b0ac424813266cec57db86d65a7c9d9ff5fa6
https://github.com/ikew0ng/SwipeBackLayout/blob/7c6b0ac424813266cec57db86d65a7c9d9ff5fa6/library/src/main/java/me/imid/swipebacklayout/lib/ViewDragHelper.java#L439-L443
26,274
spring-cloud/spring-cloud-commons
spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/InetUtils.java
InetUtils.isPreferredAddress
boolean isPreferredAddress(InetAddress address) { if (this.properties.isUseOnlySiteLocalInterfaces()) { final boolean siteLocalAddress = address.isSiteLocalAddress(); if (!siteLocalAddress) { this.log.trace("Ignoring address: " + address.getHostAddress()); } return siteLocalAddress; } final List<String> preferredNetworks = this.properties.getPreferredNetworks(); if (preferredNetworks.isEmpty()) { return true; } for (String regex : preferredNetworks) { final String hostAddress = address.getHostAddress(); if (hostAddress.matches(regex) || hostAddress.startsWith(regex)) { return true; } } this.log.trace("Ignoring address: " + address.getHostAddress()); return false; }
java
boolean isPreferredAddress(InetAddress address) { if (this.properties.isUseOnlySiteLocalInterfaces()) { final boolean siteLocalAddress = address.isSiteLocalAddress(); if (!siteLocalAddress) { this.log.trace("Ignoring address: " + address.getHostAddress()); } return siteLocalAddress; } final List<String> preferredNetworks = this.properties.getPreferredNetworks(); if (preferredNetworks.isEmpty()) { return true; } for (String regex : preferredNetworks) { final String hostAddress = address.getHostAddress(); if (hostAddress.matches(regex) || hostAddress.startsWith(regex)) { return true; } } this.log.trace("Ignoring address: " + address.getHostAddress()); return false; }
[ "boolean", "isPreferredAddress", "(", "InetAddress", "address", ")", "{", "if", "(", "this", ".", "properties", ".", "isUseOnlySiteLocalInterfaces", "(", ")", ")", "{", "final", "boolean", "siteLocalAddress", "=", "address", ".", "isSiteLocalAddress", "(", ")", ";", "if", "(", "!", "siteLocalAddress", ")", "{", "this", ".", "log", ".", "trace", "(", "\"Ignoring address: \"", "+", "address", ".", "getHostAddress", "(", ")", ")", ";", "}", "return", "siteLocalAddress", ";", "}", "final", "List", "<", "String", ">", "preferredNetworks", "=", "this", ".", "properties", ".", "getPreferredNetworks", "(", ")", ";", "if", "(", "preferredNetworks", ".", "isEmpty", "(", ")", ")", "{", "return", "true", ";", "}", "for", "(", "String", "regex", ":", "preferredNetworks", ")", "{", "final", "String", "hostAddress", "=", "address", ".", "getHostAddress", "(", ")", ";", "if", "(", "hostAddress", ".", "matches", "(", "regex", ")", "||", "hostAddress", ".", "startsWith", "(", "regex", ")", ")", "{", "return", "true", ";", "}", "}", "this", ".", "log", ".", "trace", "(", "\"Ignoring address: \"", "+", "address", ".", "getHostAddress", "(", ")", ")", ";", "return", "false", ";", "}" ]
For testing.
[ "For", "testing", "." ]
10e93d3ef740a3a4c7d67283f5f275823fafcbb5
https://github.com/spring-cloud/spring-cloud-commons/blob/10e93d3ef740a3a4c7d67283f5f275823fafcbb5/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/InetUtils.java#L127-L148
26,275
datacleaner/DataCleaner
desktop/ui/src/main/java/org/datacleaner/widgets/tabs/CloseableTabbedPaneUI.java
CloseableTabbedPaneUI.closeRectFor
public Rectangle closeRectFor(final int tabIndex) { final Rectangle rect = rects[tabIndex]; final int x = rect.x + rect.width - CLOSE_ICON_WIDTH - CLOSE_ICON_RIGHT_MARGIN; final int y = rect.y + (rect.height - CLOSE_ICON_WIDTH) / 2; final int width = CLOSE_ICON_WIDTH; return new Rectangle(x, y, width, width); }
java
public Rectangle closeRectFor(final int tabIndex) { final Rectangle rect = rects[tabIndex]; final int x = rect.x + rect.width - CLOSE_ICON_WIDTH - CLOSE_ICON_RIGHT_MARGIN; final int y = rect.y + (rect.height - CLOSE_ICON_WIDTH) / 2; final int width = CLOSE_ICON_WIDTH; return new Rectangle(x, y, width, width); }
[ "public", "Rectangle", "closeRectFor", "(", "final", "int", "tabIndex", ")", "{", "final", "Rectangle", "rect", "=", "rects", "[", "tabIndex", "]", ";", "final", "int", "x", "=", "rect", ".", "x", "+", "rect", ".", "width", "-", "CLOSE_ICON_WIDTH", "-", "CLOSE_ICON_RIGHT_MARGIN", ";", "final", "int", "y", "=", "rect", ".", "y", "+", "(", "rect", ".", "height", "-", "CLOSE_ICON_WIDTH", ")", "/", "2", ";", "final", "int", "width", "=", "CLOSE_ICON_WIDTH", ";", "return", "new", "Rectangle", "(", "x", ",", "y", ",", "width", ",", "width", ")", ";", "}" ]
Helper-method to get a rectangle definition for the close-icon @param tabIndex @return
[ "Helper", "-", "method", "to", "get", "a", "rectangle", "definition", "for", "the", "close", "-", "icon" ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/desktop/ui/src/main/java/org/datacleaner/widgets/tabs/CloseableTabbedPaneUI.java#L120-L126
26,276
datacleaner/DataCleaner
desktop/ui/src/main/java/org/datacleaner/widgets/tabs/CloseableTabbedPaneUI.java
CloseableTabbedPaneUI.calculateTabWidth
@Override protected int calculateTabWidth(final int tabPlacement, final int tabIndex, final FontMetrics metrics) { if (_pane.getSeparators().contains(tabIndex)) { return SEPARATOR_WIDTH; } int width = super.calculateTabWidth(tabPlacement, tabIndex, metrics); if (!_pane.getUnclosables().contains(tabIndex)) { width += CLOSE_ICON_WIDTH; } return width; }
java
@Override protected int calculateTabWidth(final int tabPlacement, final int tabIndex, final FontMetrics metrics) { if (_pane.getSeparators().contains(tabIndex)) { return SEPARATOR_WIDTH; } int width = super.calculateTabWidth(tabPlacement, tabIndex, metrics); if (!_pane.getUnclosables().contains(tabIndex)) { width += CLOSE_ICON_WIDTH; } return width; }
[ "@", "Override", "protected", "int", "calculateTabWidth", "(", "final", "int", "tabPlacement", ",", "final", "int", "tabIndex", ",", "final", "FontMetrics", "metrics", ")", "{", "if", "(", "_pane", ".", "getSeparators", "(", ")", ".", "contains", "(", "tabIndex", ")", ")", "{", "return", "SEPARATOR_WIDTH", ";", "}", "int", "width", "=", "super", ".", "calculateTabWidth", "(", "tabPlacement", ",", "tabIndex", ",", "metrics", ")", ";", "if", "(", "!", "_pane", ".", "getUnclosables", "(", ")", ".", "contains", "(", "tabIndex", ")", ")", "{", "width", "+=", "CLOSE_ICON_WIDTH", ";", "}", "return", "width", ";", "}" ]
Override this to provide extra space on right for close button
[ "Override", "this", "to", "provide", "extra", "space", "on", "right", "for", "close", "button" ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/desktop/ui/src/main/java/org/datacleaner/widgets/tabs/CloseableTabbedPaneUI.java#L131-L141
26,277
datacleaner/DataCleaner
desktop/ui/src/main/java/org/datacleaner/widgets/tabs/CloseableTabbedPaneUI.java
CloseableTabbedPaneUI.paintContentBorder
@Override protected void paintContentBorder(final Graphics g, final int tabPlacement, final int tabIndex) { final int w = tabPane.getWidth(); final int h = tabPane.getHeight(); final Insets tabAreaInsets = getTabAreaInsets(tabPlacement); final int x = 0; final int y = calculateTabAreaHeight(tabPlacement, runCount, maxTabHeight) + tabAreaInsets.bottom; g.setColor(_tabSelectedBackgroundColor); g.fillRect(x, y, w, h); g.setColor(_tabBorderColor); // top line, except below selected tab final Rectangle selectTabBounds = getTabBounds(tabPane, tabIndex); g.drawLine(x, y, selectTabBounds.x, y); g.drawLine(selectTabBounds.x + selectTabBounds.width, y, x + w, y); }
java
@Override protected void paintContentBorder(final Graphics g, final int tabPlacement, final int tabIndex) { final int w = tabPane.getWidth(); final int h = tabPane.getHeight(); final Insets tabAreaInsets = getTabAreaInsets(tabPlacement); final int x = 0; final int y = calculateTabAreaHeight(tabPlacement, runCount, maxTabHeight) + tabAreaInsets.bottom; g.setColor(_tabSelectedBackgroundColor); g.fillRect(x, y, w, h); g.setColor(_tabBorderColor); // top line, except below selected tab final Rectangle selectTabBounds = getTabBounds(tabPane, tabIndex); g.drawLine(x, y, selectTabBounds.x, y); g.drawLine(selectTabBounds.x + selectTabBounds.width, y, x + w, y); }
[ "@", "Override", "protected", "void", "paintContentBorder", "(", "final", "Graphics", "g", ",", "final", "int", "tabPlacement", ",", "final", "int", "tabIndex", ")", "{", "final", "int", "w", "=", "tabPane", ".", "getWidth", "(", ")", ";", "final", "int", "h", "=", "tabPane", ".", "getHeight", "(", ")", ";", "final", "Insets", "tabAreaInsets", "=", "getTabAreaInsets", "(", "tabPlacement", ")", ";", "final", "int", "x", "=", "0", ";", "final", "int", "y", "=", "calculateTabAreaHeight", "(", "tabPlacement", ",", "runCount", ",", "maxTabHeight", ")", "+", "tabAreaInsets", ".", "bottom", ";", "g", ".", "setColor", "(", "_tabSelectedBackgroundColor", ")", ";", "g", ".", "fillRect", "(", "x", ",", "y", ",", "w", ",", "h", ")", ";", "g", ".", "setColor", "(", "_tabBorderColor", ")", ";", "// top line, except below selected tab", "final", "Rectangle", "selectTabBounds", "=", "getTabBounds", "(", "tabPane", ",", "tabIndex", ")", ";", "g", ".", "drawLine", "(", "x", ",", "y", ",", "selectTabBounds", ".", "x", ",", "y", ")", ";", "g", ".", "drawLine", "(", "selectTabBounds", ".", "x", "+", "selectTabBounds", ".", "width", ",", "y", ",", "x", "+", "w", ",", "y", ")", ";", "}" ]
Paints the border for the tab's content, ie. the area below the tabs
[ "Paints", "the", "border", "for", "the", "tab", "s", "content", "ie", ".", "the", "area", "below", "the", "tabs" ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/desktop/ui/src/main/java/org/datacleaner/widgets/tabs/CloseableTabbedPaneUI.java#L224-L242
26,278
datacleaner/DataCleaner
components/i18n/src/main/java/org/datacleaner/beans/CharacterSetDistributionAnalyzer.java
CharacterSetDistributionAnalyzer.createUnicodeSets
protected static Map<String, UnicodeSet> createUnicodeSets() { final Map<String, UnicodeSet> unicodeSets = new TreeMap<>(); unicodeSets.put("Latin, ASCII", new UnicodeSet("[:ASCII:]")); unicodeSets.put("Latin, non-ASCII", subUnicodeSet("[:Latin:]", "[:ASCII:]")); unicodeSets.put("Arabic", new UnicodeSet("[:Script=Arabic:]")); unicodeSets.put("Armenian", new UnicodeSet("[:Script=Armenian:]")); unicodeSets.put("Bengali", new UnicodeSet("[:Script=Bengali:]")); unicodeSets.put("Cyrillic", new UnicodeSet("[:Script=Cyrillic:]")); unicodeSets.put("Devanagari", new UnicodeSet("[:Script=Devanagari:]")); unicodeSets.put("Greek", new UnicodeSet("[:Script=Greek:]")); unicodeSets.put("Han", new UnicodeSet("[:Script=Han:]")); unicodeSets.put("Gujarati", new UnicodeSet("[:Script=Gujarati:]")); unicodeSets.put("Georgian", new UnicodeSet("[:Script=Georgian:]")); unicodeSets.put("Gurmukhi", new UnicodeSet("[:Script=Gurmukhi:]")); unicodeSets.put("Hangul", new UnicodeSet("[:Script=Hangul:]")); unicodeSets.put("Hebrew", new UnicodeSet("[:Script=Hebrew:]")); unicodeSets.put("Hiragana", new UnicodeSet("[:Script=Hiragana:]")); // unicodeSets.put("Kanji", new UnicodeSet("[:Script=Kanji:]")); unicodeSets.put("Kannada", new UnicodeSet("[:Script=Kannada:]")); unicodeSets.put("Katakana", new UnicodeSet("[:Script=Katakana:]")); unicodeSets.put("Malayalam", new UnicodeSet("[:Script=Malayalam:]")); // unicodeSets.put("Mandarin", new UnicodeSet("[:Script=Mandarin:]")); unicodeSets.put("Oriya", new UnicodeSet("[:Script=Oriya:]")); unicodeSets.put("Syriac", new UnicodeSet("[:Script=Syriac:]")); unicodeSets.put("Tamil", new UnicodeSet("[:Script=Tamil:]")); unicodeSets.put("Telugu", new UnicodeSet("[:Script=Telugu:]")); unicodeSets.put("Thaana", new UnicodeSet("[:Script=Thaana:]")); unicodeSets.put("Thai", new UnicodeSet("[:Script=Thai:]")); return unicodeSets; }
java
protected static Map<String, UnicodeSet> createUnicodeSets() { final Map<String, UnicodeSet> unicodeSets = new TreeMap<>(); unicodeSets.put("Latin, ASCII", new UnicodeSet("[:ASCII:]")); unicodeSets.put("Latin, non-ASCII", subUnicodeSet("[:Latin:]", "[:ASCII:]")); unicodeSets.put("Arabic", new UnicodeSet("[:Script=Arabic:]")); unicodeSets.put("Armenian", new UnicodeSet("[:Script=Armenian:]")); unicodeSets.put("Bengali", new UnicodeSet("[:Script=Bengali:]")); unicodeSets.put("Cyrillic", new UnicodeSet("[:Script=Cyrillic:]")); unicodeSets.put("Devanagari", new UnicodeSet("[:Script=Devanagari:]")); unicodeSets.put("Greek", new UnicodeSet("[:Script=Greek:]")); unicodeSets.put("Han", new UnicodeSet("[:Script=Han:]")); unicodeSets.put("Gujarati", new UnicodeSet("[:Script=Gujarati:]")); unicodeSets.put("Georgian", new UnicodeSet("[:Script=Georgian:]")); unicodeSets.put("Gurmukhi", new UnicodeSet("[:Script=Gurmukhi:]")); unicodeSets.put("Hangul", new UnicodeSet("[:Script=Hangul:]")); unicodeSets.put("Hebrew", new UnicodeSet("[:Script=Hebrew:]")); unicodeSets.put("Hiragana", new UnicodeSet("[:Script=Hiragana:]")); // unicodeSets.put("Kanji", new UnicodeSet("[:Script=Kanji:]")); unicodeSets.put("Kannada", new UnicodeSet("[:Script=Kannada:]")); unicodeSets.put("Katakana", new UnicodeSet("[:Script=Katakana:]")); unicodeSets.put("Malayalam", new UnicodeSet("[:Script=Malayalam:]")); // unicodeSets.put("Mandarin", new UnicodeSet("[:Script=Mandarin:]")); unicodeSets.put("Oriya", new UnicodeSet("[:Script=Oriya:]")); unicodeSets.put("Syriac", new UnicodeSet("[:Script=Syriac:]")); unicodeSets.put("Tamil", new UnicodeSet("[:Script=Tamil:]")); unicodeSets.put("Telugu", new UnicodeSet("[:Script=Telugu:]")); unicodeSets.put("Thaana", new UnicodeSet("[:Script=Thaana:]")); unicodeSets.put("Thai", new UnicodeSet("[:Script=Thai:]")); return unicodeSets; }
[ "protected", "static", "Map", "<", "String", ",", "UnicodeSet", ">", "createUnicodeSets", "(", ")", "{", "final", "Map", "<", "String", ",", "UnicodeSet", ">", "unicodeSets", "=", "new", "TreeMap", "<>", "(", ")", ";", "unicodeSets", ".", "put", "(", "\"Latin, ASCII\"", ",", "new", "UnicodeSet", "(", "\"[:ASCII:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Latin, non-ASCII\"", ",", "subUnicodeSet", "(", "\"[:Latin:]\"", ",", "\"[:ASCII:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Arabic\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Arabic:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Armenian\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Armenian:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Bengali\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Bengali:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Cyrillic\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Cyrillic:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Devanagari\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Devanagari:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Greek\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Greek:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Han\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Han:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Gujarati\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Gujarati:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Georgian\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Georgian:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Gurmukhi\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Gurmukhi:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Hangul\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Hangul:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Hebrew\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Hebrew:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Hiragana\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Hiragana:]\"", ")", ")", ";", "// unicodeSets.put(\"Kanji\", new UnicodeSet(\"[:Script=Kanji:]\"));", "unicodeSets", ".", "put", "(", "\"Kannada\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Kannada:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Katakana\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Katakana:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Malayalam\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Malayalam:]\"", ")", ")", ";", "// unicodeSets.put(\"Mandarin\", new UnicodeSet(\"[:Script=Mandarin:]\"));", "unicodeSets", ".", "put", "(", "\"Oriya\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Oriya:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Syriac\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Syriac:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Tamil\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Tamil:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Telugu\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Telugu:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Thaana\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Thaana:]\"", ")", ")", ";", "unicodeSets", ".", "put", "(", "\"Thai\"", ",", "new", "UnicodeSet", "(", "\"[:Script=Thai:]\"", ")", ")", ";", "return", "unicodeSets", ";", "}" ]
Creates a map of unicode sets, with their names as keys. There's a usable list of Unicode scripts on this page: http://unicode.org/cldr/utility/properties.jsp?a=Script#Script Additionally, this page has some explanations on some of the more exotic sources, like japanese: http://userguide.icu-project.org/transforms/general#TOC-Japanese @return
[ "Creates", "a", "map", "of", "unicode", "sets", "with", "their", "names", "as", "keys", "." ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/components/i18n/src/main/java/org/datacleaner/beans/CharacterSetDistributionAnalyzer.java#L81-L110
26,279
datacleaner/DataCleaner
engine/core/src/main/java/org/datacleaner/job/builder/AnalysisJobBuilder.java
AnalysisJobBuilder.isConfigured
public boolean isConfigured(final boolean throwException) throws UnconfiguredConfiguredPropertyException, ComponentValidationException, NoResultProducingComponentsException, IllegalStateException { return checkConfiguration(throwException) && isConsumedOutDataStreamsJobBuilderConfigured(throwException); }
java
public boolean isConfigured(final boolean throwException) throws UnconfiguredConfiguredPropertyException, ComponentValidationException, NoResultProducingComponentsException, IllegalStateException { return checkConfiguration(throwException) && isConsumedOutDataStreamsJobBuilderConfigured(throwException); }
[ "public", "boolean", "isConfigured", "(", "final", "boolean", "throwException", ")", "throws", "UnconfiguredConfiguredPropertyException", ",", "ComponentValidationException", ",", "NoResultProducingComponentsException", ",", "IllegalStateException", "{", "return", "checkConfiguration", "(", "throwException", ")", "&&", "isConsumedOutDataStreamsJobBuilderConfigured", "(", "throwException", ")", ";", "}" ]
Used to verify whether or not the builder's and its immediate children configuration is valid and all properties are satisfied. @param throwException whether or not an exception should be thrown in case of invalid configuration. Typically an exception message will contain more detailed information about the cause of the validation error, whereas a boolean contains no details. @return true if the analysis job builder is correctly configured @throws UnconfiguredConfiguredPropertyException if a required property is not configured @throws ComponentValidationException if custom validation (using {@link Validate} method or so) of a component fails. @throws NoResultProducingComponentsException if no result producing components (see {@link HasAnalyzerResult}) exist in the job. @throws IllegalStateException if any other (mostly unexpected) configuration issue occurs
[ "Used", "to", "verify", "whether", "or", "not", "the", "builder", "s", "and", "its", "immediate", "children", "configuration", "is", "valid", "and", "all", "properties", "are", "satisfied", "." ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/engine/core/src/main/java/org/datacleaner/job/builder/AnalysisJobBuilder.java#L747-L751
26,280
datacleaner/DataCleaner
engine/core/src/main/java/org/datacleaner/job/builder/AnalysisJobBuilder.java
AnalysisJobBuilder.isConsumedOutDataStreamsJobBuilderConfigured
private boolean isConsumedOutDataStreamsJobBuilderConfigured(final boolean throwException) { final List<AnalysisJobBuilder> consumedOutputDataStreamsJobBuilders = getConsumedOutputDataStreamsJobBuilders(); for (final AnalysisJobBuilder analysisJobBuilder : consumedOutputDataStreamsJobBuilders) { if (!analysisJobBuilder.isConfigured(throwException)) { return false; } } return true; }
java
private boolean isConsumedOutDataStreamsJobBuilderConfigured(final boolean throwException) { final List<AnalysisJobBuilder> consumedOutputDataStreamsJobBuilders = getConsumedOutputDataStreamsJobBuilders(); for (final AnalysisJobBuilder analysisJobBuilder : consumedOutputDataStreamsJobBuilders) { if (!analysisJobBuilder.isConfigured(throwException)) { return false; } } return true; }
[ "private", "boolean", "isConsumedOutDataStreamsJobBuilderConfigured", "(", "final", "boolean", "throwException", ")", "{", "final", "List", "<", "AnalysisJobBuilder", ">", "consumedOutputDataStreamsJobBuilders", "=", "getConsumedOutputDataStreamsJobBuilders", "(", ")", ";", "for", "(", "final", "AnalysisJobBuilder", "analysisJobBuilder", ":", "consumedOutputDataStreamsJobBuilders", ")", "{", "if", "(", "!", "analysisJobBuilder", ".", "isConfigured", "(", "throwException", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks if a job children are configured.
[ "Checks", "if", "a", "job", "children", "are", "configured", "." ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/engine/core/src/main/java/org/datacleaner/job/builder/AnalysisJobBuilder.java#L1399-L1407
26,281
datacleaner/DataCleaner
engine/core/src/main/java/org/datacleaner/job/builder/AnalysisJobBuilder.java
AnalysisJobBuilder.isDistributable
public boolean isDistributable() { final Collection<ComponentBuilder> componentBuilders = getComponentBuilders(); for (final ComponentBuilder componentBuilder : componentBuilders) { if (!componentBuilder.isDistributable()) { return false; } } final List<AnalysisJobBuilder> childJobBuilders = getConsumedOutputDataStreamsJobBuilders(); for (final AnalysisJobBuilder childJobBuilder : childJobBuilders) { if (!childJobBuilder.isDistributable()) { return false; } } return true; }
java
public boolean isDistributable() { final Collection<ComponentBuilder> componentBuilders = getComponentBuilders(); for (final ComponentBuilder componentBuilder : componentBuilders) { if (!componentBuilder.isDistributable()) { return false; } } final List<AnalysisJobBuilder> childJobBuilders = getConsumedOutputDataStreamsJobBuilders(); for (final AnalysisJobBuilder childJobBuilder : childJobBuilders) { if (!childJobBuilder.isDistributable()) { return false; } } return true; }
[ "public", "boolean", "isDistributable", "(", ")", "{", "final", "Collection", "<", "ComponentBuilder", ">", "componentBuilders", "=", "getComponentBuilders", "(", ")", ";", "for", "(", "final", "ComponentBuilder", "componentBuilder", ":", "componentBuilders", ")", "{", "if", "(", "!", "componentBuilder", ".", "isDistributable", "(", ")", ")", "{", "return", "false", ";", "}", "}", "final", "List", "<", "AnalysisJobBuilder", ">", "childJobBuilders", "=", "getConsumedOutputDataStreamsJobBuilders", "(", ")", ";", "for", "(", "final", "AnalysisJobBuilder", "childJobBuilder", ":", "childJobBuilders", ")", "{", "if", "(", "!", "childJobBuilder", ".", "isDistributable", "(", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Determines if the job being built is going to be distributable in a cluster execution environment. @return
[ "Determines", "if", "the", "job", "being", "built", "is", "going", "to", "be", "distributable", "in", "a", "cluster", "execution", "environment", "." ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/engine/core/src/main/java/org/datacleaner/job/builder/AnalysisJobBuilder.java#L1415-L1431
26,282
datacleaner/DataCleaner
engine/env/spark/src/main/java/org/datacleaner/spark/utils/HadoopUtils.java
HadoopUtils.getDirectoryIfExists
private static File getDirectoryIfExists(final File existingCandidate, final String path) { if (existingCandidate != null) { return existingCandidate; } if (!Strings.isNullOrEmpty(path)) { final File directory = new File(path); if (directory.exists() && directory.isDirectory()) { return directory; } } return null; }
java
private static File getDirectoryIfExists(final File existingCandidate, final String path) { if (existingCandidate != null) { return existingCandidate; } if (!Strings.isNullOrEmpty(path)) { final File directory = new File(path); if (directory.exists() && directory.isDirectory()) { return directory; } } return null; }
[ "private", "static", "File", "getDirectoryIfExists", "(", "final", "File", "existingCandidate", ",", "final", "String", "path", ")", "{", "if", "(", "existingCandidate", "!=", "null", ")", "{", "return", "existingCandidate", ";", "}", "if", "(", "!", "Strings", ".", "isNullOrEmpty", "(", "path", ")", ")", "{", "final", "File", "directory", "=", "new", "File", "(", "path", ")", ";", "if", "(", "directory", ".", "exists", "(", ")", "&&", "directory", ".", "isDirectory", "(", ")", ")", "{", "return", "directory", ";", "}", "}", "return", "null", ";", "}" ]
Gets a candidate directory based on a file path, if it exists, and if it another candidate hasn't already been resolved. @param existingCandidate an existing candidate directory. If this is non-null, it will be returned immediately. @param path the path of a directory @return a candidate directory, or null if none was resolved.
[ "Gets", "a", "candidate", "directory", "based", "on", "a", "file", "path", "if", "it", "exists", "and", "if", "it", "another", "candidate", "hasn", "t", "already", "been", "resolved", "." ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/engine/env/spark/src/main/java/org/datacleaner/spark/utils/HadoopUtils.java#L53-L64
26,283
datacleaner/DataCleaner
desktop/ui/src/main/java/org/datacleaner/widgets/result/PatternFinderResultSwingRenderer.java
PatternFinderResultSwingRenderer.main
public static void main(final String[] args) { LookAndFeelManager.get().init(); final Injector injector = Guice.createInjector(new DCModuleImpl()); // run a small job final AnalysisJobBuilder ajb = injector.getInstance(AnalysisJobBuilder.class); final Datastore ds = injector.getInstance(DatastoreCatalog.class).getDatastore("orderdb"); final DatastoreConnection con = ds.openConnection(); final Table table = con.getSchemaNavigator().convertToTable("PUBLIC.CUSTOMERS"); ajb.setDatastore(ds); ajb.addSourceColumns(table.getLiteralColumns()); ajb.addAnalyzer(PatternFinderAnalyzer.class).addInputColumns(ajb.getSourceColumns()) .setName("Ungrouped pattern finders"); final AnalyzerComponentBuilder<PatternFinderAnalyzer> groupedPatternFinder = ajb.addAnalyzer(PatternFinderAnalyzer.class); ajb.addSourceColumns("PUBLIC.OFFICES.CITY", "PUBLIC.OFFICES.TERRITORY"); groupedPatternFinder.setName("Grouped PF"); groupedPatternFinder.addInputColumn(ajb.getSourceColumnByName("PUBLIC.OFFICES.CITY")); groupedPatternFinder.addInputColumn(ajb.getSourceColumnByName("PUBLIC.OFFICES.TERRITORY"), groupedPatternFinder.getDescriptor().getConfiguredProperty("Group column")); final ResultWindow resultWindow = injector.getInstance(ResultWindow.class); resultWindow.setVisible(true); resultWindow.startAnalysis(); }
java
public static void main(final String[] args) { LookAndFeelManager.get().init(); final Injector injector = Guice.createInjector(new DCModuleImpl()); // run a small job final AnalysisJobBuilder ajb = injector.getInstance(AnalysisJobBuilder.class); final Datastore ds = injector.getInstance(DatastoreCatalog.class).getDatastore("orderdb"); final DatastoreConnection con = ds.openConnection(); final Table table = con.getSchemaNavigator().convertToTable("PUBLIC.CUSTOMERS"); ajb.setDatastore(ds); ajb.addSourceColumns(table.getLiteralColumns()); ajb.addAnalyzer(PatternFinderAnalyzer.class).addInputColumns(ajb.getSourceColumns()) .setName("Ungrouped pattern finders"); final AnalyzerComponentBuilder<PatternFinderAnalyzer> groupedPatternFinder = ajb.addAnalyzer(PatternFinderAnalyzer.class); ajb.addSourceColumns("PUBLIC.OFFICES.CITY", "PUBLIC.OFFICES.TERRITORY"); groupedPatternFinder.setName("Grouped PF"); groupedPatternFinder.addInputColumn(ajb.getSourceColumnByName("PUBLIC.OFFICES.CITY")); groupedPatternFinder.addInputColumn(ajb.getSourceColumnByName("PUBLIC.OFFICES.TERRITORY"), groupedPatternFinder.getDescriptor().getConfiguredProperty("Group column")); final ResultWindow resultWindow = injector.getInstance(ResultWindow.class); resultWindow.setVisible(true); resultWindow.startAnalysis(); }
[ "public", "static", "void", "main", "(", "final", "String", "[", "]", "args", ")", "{", "LookAndFeelManager", ".", "get", "(", ")", ".", "init", "(", ")", ";", "final", "Injector", "injector", "=", "Guice", ".", "createInjector", "(", "new", "DCModuleImpl", "(", ")", ")", ";", "// run a small job", "final", "AnalysisJobBuilder", "ajb", "=", "injector", ".", "getInstance", "(", "AnalysisJobBuilder", ".", "class", ")", ";", "final", "Datastore", "ds", "=", "injector", ".", "getInstance", "(", "DatastoreCatalog", ".", "class", ")", ".", "getDatastore", "(", "\"orderdb\"", ")", ";", "final", "DatastoreConnection", "con", "=", "ds", ".", "openConnection", "(", ")", ";", "final", "Table", "table", "=", "con", ".", "getSchemaNavigator", "(", ")", ".", "convertToTable", "(", "\"PUBLIC.CUSTOMERS\"", ")", ";", "ajb", ".", "setDatastore", "(", "ds", ")", ";", "ajb", ".", "addSourceColumns", "(", "table", ".", "getLiteralColumns", "(", ")", ")", ";", "ajb", ".", "addAnalyzer", "(", "PatternFinderAnalyzer", ".", "class", ")", ".", "addInputColumns", "(", "ajb", ".", "getSourceColumns", "(", ")", ")", ".", "setName", "(", "\"Ungrouped pattern finders\"", ")", ";", "final", "AnalyzerComponentBuilder", "<", "PatternFinderAnalyzer", ">", "groupedPatternFinder", "=", "ajb", ".", "addAnalyzer", "(", "PatternFinderAnalyzer", ".", "class", ")", ";", "ajb", ".", "addSourceColumns", "(", "\"PUBLIC.OFFICES.CITY\"", ",", "\"PUBLIC.OFFICES.TERRITORY\"", ")", ";", "groupedPatternFinder", ".", "setName", "(", "\"Grouped PF\"", ")", ";", "groupedPatternFinder", ".", "addInputColumn", "(", "ajb", ".", "getSourceColumnByName", "(", "\"PUBLIC.OFFICES.CITY\"", ")", ")", ";", "groupedPatternFinder", ".", "addInputColumn", "(", "ajb", ".", "getSourceColumnByName", "(", "\"PUBLIC.OFFICES.TERRITORY\"", ")", ",", "groupedPatternFinder", ".", "getDescriptor", "(", ")", ".", "getConfiguredProperty", "(", "\"Group column\"", ")", ")", ";", "final", "ResultWindow", "resultWindow", "=", "injector", ".", "getInstance", "(", "ResultWindow", ".", "class", ")", ";", "resultWindow", ".", "setVisible", "(", "true", ")", ";", "resultWindow", ".", "startAnalysis", "(", ")", ";", "}" ]
A main method that will display the results of a few example pattern finder analyzers. Useful for tweaking the charts and UI. @param args
[ "A", "main", "method", "that", "will", "display", "the", "results", "of", "a", "few", "example", "pattern", "finder", "analyzers", ".", "Useful", "for", "tweaking", "the", "charts", "and", "UI", "." ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/desktop/ui/src/main/java/org/datacleaner/widgets/result/PatternFinderResultSwingRenderer.java#L161-L187
26,284
datacleaner/DataCleaner
desktop/ui/src/main/java/org/datacleaner/widgets/result/NumberAnalyzerResultSwingRenderer.java
NumberAnalyzerResultSwingRenderer.main
public static void main(final String[] args) throws Exception { LookAndFeelManager.get().init(); final Injector injector = Guice.createInjector(new DCModuleImpl(VFSUtils.getFileSystemManager().resolveFile("."), null)); // run a small job final AnalysisJobBuilder ajb = injector.getInstance(AnalysisJobBuilder.class); final Datastore ds = injector.getInstance(DatastoreCatalog.class).getDatastore("orderdb"); final DatastoreConnection con = ds.openConnection(); final Table table = con.getSchemaNavigator().convertToTable("PUBLIC.CUSTOMERS"); ajb.setDatastore(ds); ajb.addSourceColumns(table.getNumberColumns()); ajb.addAnalyzer(NumberAnalyzer.class).addInputColumns(ajb.getSourceColumns()); final ResultWindow resultWindow = injector.getInstance(ResultWindow.class); resultWindow.setVisible(true); resultWindow.startAnalysis(); }
java
public static void main(final String[] args) throws Exception { LookAndFeelManager.get().init(); final Injector injector = Guice.createInjector(new DCModuleImpl(VFSUtils.getFileSystemManager().resolveFile("."), null)); // run a small job final AnalysisJobBuilder ajb = injector.getInstance(AnalysisJobBuilder.class); final Datastore ds = injector.getInstance(DatastoreCatalog.class).getDatastore("orderdb"); final DatastoreConnection con = ds.openConnection(); final Table table = con.getSchemaNavigator().convertToTable("PUBLIC.CUSTOMERS"); ajb.setDatastore(ds); ajb.addSourceColumns(table.getNumberColumns()); ajb.addAnalyzer(NumberAnalyzer.class).addInputColumns(ajb.getSourceColumns()); final ResultWindow resultWindow = injector.getInstance(ResultWindow.class); resultWindow.setVisible(true); resultWindow.startAnalysis(); }
[ "public", "static", "void", "main", "(", "final", "String", "[", "]", "args", ")", "throws", "Exception", "{", "LookAndFeelManager", ".", "get", "(", ")", ".", "init", "(", ")", ";", "final", "Injector", "injector", "=", "Guice", ".", "createInjector", "(", "new", "DCModuleImpl", "(", "VFSUtils", ".", "getFileSystemManager", "(", ")", ".", "resolveFile", "(", "\".\"", ")", ",", "null", ")", ")", ";", "// run a small job", "final", "AnalysisJobBuilder", "ajb", "=", "injector", ".", "getInstance", "(", "AnalysisJobBuilder", ".", "class", ")", ";", "final", "Datastore", "ds", "=", "injector", ".", "getInstance", "(", "DatastoreCatalog", ".", "class", ")", ".", "getDatastore", "(", "\"orderdb\"", ")", ";", "final", "DatastoreConnection", "con", "=", "ds", ".", "openConnection", "(", ")", ";", "final", "Table", "table", "=", "con", ".", "getSchemaNavigator", "(", ")", ".", "convertToTable", "(", "\"PUBLIC.CUSTOMERS\"", ")", ";", "ajb", ".", "setDatastore", "(", "ds", ")", ";", "ajb", ".", "addSourceColumns", "(", "table", ".", "getNumberColumns", "(", ")", ")", ";", "ajb", ".", "addAnalyzer", "(", "NumberAnalyzer", ".", "class", ")", ".", "addInputColumns", "(", "ajb", ".", "getSourceColumns", "(", ")", ")", ";", "final", "ResultWindow", "resultWindow", "=", "injector", ".", "getInstance", "(", "ResultWindow", ".", "class", ")", ";", "resultWindow", ".", "setVisible", "(", "true", ")", ";", "resultWindow", ".", "startAnalysis", "(", ")", ";", "}" ]
A main method that will display the results of a few example number analyzers. Useful for tweaking the charts and UI. @param args
[ "A", "main", "method", "that", "will", "display", "the", "results", "of", "a", "few", "example", "number", "analyzers", ".", "Useful", "for", "tweaking", "the", "charts", "and", "UI", "." ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/desktop/ui/src/main/java/org/datacleaner/widgets/result/NumberAnalyzerResultSwingRenderer.java#L145-L163
26,285
datacleaner/DataCleaner
engine/env/spark/src/main/java/org/datacleaner/spark/functions/RowProcessingFunction.java
RowProcessingFunction.configureComponentsBeforeBuilding
private void configureComponentsBeforeBuilding(final AnalysisJobBuilder jobBuilder, final int partitionNumber) { // update datastores and resource properties to point to node-specific // targets if possible. This way parallel writing to files on HDFS does // not cause any inconsistencies because each node is writing to a // separate file. for (final ComponentBuilder cb : jobBuilder.getComponentBuilders()) { // find any datastore properties that point to HDFS files final Set<ConfiguredPropertyDescriptor> targetDatastoreProperties = cb.getDescriptor().getConfiguredPropertiesByType(UpdateableDatastore.class, false); for (final ConfiguredPropertyDescriptor targetDatastoreProperty : targetDatastoreProperties) { final Object datastoreObject = cb.getConfiguredProperty(targetDatastoreProperty); if (datastoreObject instanceof ResourceDatastore) { final ResourceDatastore resourceDatastore = (ResourceDatastore) datastoreObject; final Resource resource = resourceDatastore.getResource(); final Resource replacementResource = createReplacementResource(resource, partitionNumber); if (replacementResource != null) { final ResourceDatastore replacementDatastore = createReplacementDatastore(cb, resourceDatastore, replacementResource); if (replacementDatastore != null) { cb.setConfiguredProperty(targetDatastoreProperty, replacementDatastore); } } } } final Set<ConfiguredPropertyDescriptor> resourceProperties = cb.getDescriptor().getConfiguredPropertiesByType(Resource.class, false); for (final ConfiguredPropertyDescriptor resourceProperty : resourceProperties) { final Resource resource = (Resource) cb.getConfiguredProperty(resourceProperty); final Resource replacementResource = createReplacementResource(resource, partitionNumber); if (replacementResource != null) { cb.setConfiguredProperty(resourceProperty, replacementResource); } } // special handlings of specific component types are handled here if (cb.getComponentInstance() instanceof CreateCsvFileAnalyzer) { if (partitionNumber > 0) { // ensure header is only created once cb.setConfiguredProperty(CreateCsvFileAnalyzer.PROPERTY_INCLUDE_HEADER, false); } } } // recursively apply this function also on output data stream jobs final List<AnalysisJobBuilder> children = jobBuilder.getConsumedOutputDataStreamsJobBuilders(); for (final AnalysisJobBuilder childJobBuilder : children) { configureComponentsBeforeBuilding(childJobBuilder, partitionNumber); } }
java
private void configureComponentsBeforeBuilding(final AnalysisJobBuilder jobBuilder, final int partitionNumber) { // update datastores and resource properties to point to node-specific // targets if possible. This way parallel writing to files on HDFS does // not cause any inconsistencies because each node is writing to a // separate file. for (final ComponentBuilder cb : jobBuilder.getComponentBuilders()) { // find any datastore properties that point to HDFS files final Set<ConfiguredPropertyDescriptor> targetDatastoreProperties = cb.getDescriptor().getConfiguredPropertiesByType(UpdateableDatastore.class, false); for (final ConfiguredPropertyDescriptor targetDatastoreProperty : targetDatastoreProperties) { final Object datastoreObject = cb.getConfiguredProperty(targetDatastoreProperty); if (datastoreObject instanceof ResourceDatastore) { final ResourceDatastore resourceDatastore = (ResourceDatastore) datastoreObject; final Resource resource = resourceDatastore.getResource(); final Resource replacementResource = createReplacementResource(resource, partitionNumber); if (replacementResource != null) { final ResourceDatastore replacementDatastore = createReplacementDatastore(cb, resourceDatastore, replacementResource); if (replacementDatastore != null) { cb.setConfiguredProperty(targetDatastoreProperty, replacementDatastore); } } } } final Set<ConfiguredPropertyDescriptor> resourceProperties = cb.getDescriptor().getConfiguredPropertiesByType(Resource.class, false); for (final ConfiguredPropertyDescriptor resourceProperty : resourceProperties) { final Resource resource = (Resource) cb.getConfiguredProperty(resourceProperty); final Resource replacementResource = createReplacementResource(resource, partitionNumber); if (replacementResource != null) { cb.setConfiguredProperty(resourceProperty, replacementResource); } } // special handlings of specific component types are handled here if (cb.getComponentInstance() instanceof CreateCsvFileAnalyzer) { if (partitionNumber > 0) { // ensure header is only created once cb.setConfiguredProperty(CreateCsvFileAnalyzer.PROPERTY_INCLUDE_HEADER, false); } } } // recursively apply this function also on output data stream jobs final List<AnalysisJobBuilder> children = jobBuilder.getConsumedOutputDataStreamsJobBuilders(); for (final AnalysisJobBuilder childJobBuilder : children) { configureComponentsBeforeBuilding(childJobBuilder, partitionNumber); } }
[ "private", "void", "configureComponentsBeforeBuilding", "(", "final", "AnalysisJobBuilder", "jobBuilder", ",", "final", "int", "partitionNumber", ")", "{", "// update datastores and resource properties to point to node-specific", "// targets if possible. This way parallel writing to files on HDFS does", "// not cause any inconsistencies because each node is writing to a", "// separate file.", "for", "(", "final", "ComponentBuilder", "cb", ":", "jobBuilder", ".", "getComponentBuilders", "(", ")", ")", "{", "// find any datastore properties that point to HDFS files", "final", "Set", "<", "ConfiguredPropertyDescriptor", ">", "targetDatastoreProperties", "=", "cb", ".", "getDescriptor", "(", ")", ".", "getConfiguredPropertiesByType", "(", "UpdateableDatastore", ".", "class", ",", "false", ")", ";", "for", "(", "final", "ConfiguredPropertyDescriptor", "targetDatastoreProperty", ":", "targetDatastoreProperties", ")", "{", "final", "Object", "datastoreObject", "=", "cb", ".", "getConfiguredProperty", "(", "targetDatastoreProperty", ")", ";", "if", "(", "datastoreObject", "instanceof", "ResourceDatastore", ")", "{", "final", "ResourceDatastore", "resourceDatastore", "=", "(", "ResourceDatastore", ")", "datastoreObject", ";", "final", "Resource", "resource", "=", "resourceDatastore", ".", "getResource", "(", ")", ";", "final", "Resource", "replacementResource", "=", "createReplacementResource", "(", "resource", ",", "partitionNumber", ")", ";", "if", "(", "replacementResource", "!=", "null", ")", "{", "final", "ResourceDatastore", "replacementDatastore", "=", "createReplacementDatastore", "(", "cb", ",", "resourceDatastore", ",", "replacementResource", ")", ";", "if", "(", "replacementDatastore", "!=", "null", ")", "{", "cb", ".", "setConfiguredProperty", "(", "targetDatastoreProperty", ",", "replacementDatastore", ")", ";", "}", "}", "}", "}", "final", "Set", "<", "ConfiguredPropertyDescriptor", ">", "resourceProperties", "=", "cb", ".", "getDescriptor", "(", ")", ".", "getConfiguredPropertiesByType", "(", "Resource", ".", "class", ",", "false", ")", ";", "for", "(", "final", "ConfiguredPropertyDescriptor", "resourceProperty", ":", "resourceProperties", ")", "{", "final", "Resource", "resource", "=", "(", "Resource", ")", "cb", ".", "getConfiguredProperty", "(", "resourceProperty", ")", ";", "final", "Resource", "replacementResource", "=", "createReplacementResource", "(", "resource", ",", "partitionNumber", ")", ";", "if", "(", "replacementResource", "!=", "null", ")", "{", "cb", ".", "setConfiguredProperty", "(", "resourceProperty", ",", "replacementResource", ")", ";", "}", "}", "// special handlings of specific component types are handled here", "if", "(", "cb", ".", "getComponentInstance", "(", ")", "instanceof", "CreateCsvFileAnalyzer", ")", "{", "if", "(", "partitionNumber", ">", "0", ")", "{", "// ensure header is only created once", "cb", ".", "setConfiguredProperty", "(", "CreateCsvFileAnalyzer", ".", "PROPERTY_INCLUDE_HEADER", ",", "false", ")", ";", "}", "}", "}", "// recursively apply this function also on output data stream jobs", "final", "List", "<", "AnalysisJobBuilder", ">", "children", "=", "jobBuilder", ".", "getConsumedOutputDataStreamsJobBuilders", "(", ")", ";", "for", "(", "final", "AnalysisJobBuilder", "childJobBuilder", ":", "children", ")", "{", "configureComponentsBeforeBuilding", "(", "childJobBuilder", ",", "partitionNumber", ")", ";", "}", "}" ]
Applies any partition-specific configuration to the job builder before building it. @param jobBuilder @param partitionNumber
[ "Applies", "any", "partition", "-", "specific", "configuration", "to", "the", "job", "builder", "before", "building", "it", "." ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/engine/env/spark/src/main/java/org/datacleaner/spark/functions/RowProcessingFunction.java#L128-L177
26,286
datacleaner/DataCleaner
engine/core/src/main/java/org/datacleaner/util/CrosstabReducerHelper.java
CrosstabReducerHelper.createDimensionsColumnCrosstab
public static void createDimensionsColumnCrosstab(final List<CrosstabDimension> crosstabDimensions, final Crosstab<Number> partialCrosstab) { if (partialCrosstab != null) { final List<CrosstabDimension> dimensions = partialCrosstab.getDimensions(); for (final CrosstabDimension dimension : dimensions) { if (!dimensionExits(crosstabDimensions, dimension)) { crosstabDimensions.add(dimension); } } } }
java
public static void createDimensionsColumnCrosstab(final List<CrosstabDimension> crosstabDimensions, final Crosstab<Number> partialCrosstab) { if (partialCrosstab != null) { final List<CrosstabDimension> dimensions = partialCrosstab.getDimensions(); for (final CrosstabDimension dimension : dimensions) { if (!dimensionExits(crosstabDimensions, dimension)) { crosstabDimensions.add(dimension); } } } }
[ "public", "static", "void", "createDimensionsColumnCrosstab", "(", "final", "List", "<", "CrosstabDimension", ">", "crosstabDimensions", ",", "final", "Crosstab", "<", "Number", ">", "partialCrosstab", ")", "{", "if", "(", "partialCrosstab", "!=", "null", ")", "{", "final", "List", "<", "CrosstabDimension", ">", "dimensions", "=", "partialCrosstab", ".", "getDimensions", "(", ")", ";", "for", "(", "final", "CrosstabDimension", "dimension", ":", "dimensions", ")", "{", "if", "(", "!", "dimensionExits", "(", "crosstabDimensions", ",", "dimension", ")", ")", "{", "crosstabDimensions", ".", "add", "(", "dimension", ")", ";", "}", "}", "}", "}" ]
Add the croosstab dimensions to the list of dimensions @param crosstabDimensions - list of dimensions @param partialCrosstab - crosstab
[ "Add", "the", "croosstab", "dimensions", "to", "the", "list", "of", "dimensions" ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/engine/core/src/main/java/org/datacleaner/util/CrosstabReducerHelper.java#L45-L55
26,287
datacleaner/DataCleaner
engine/core/src/main/java/org/datacleaner/util/CrosstabReducerHelper.java
CrosstabReducerHelper.addData
public static void addData(final Crosstab<Number> mainCrosstab, final Crosstab<Number> partialCrosstab, final CrosstabDimension columnDimension, final CrosstabDimension measureDimension) { if (partialCrosstab != null) { final CrosstabNavigator<Number> mainNavigator = new CrosstabNavigator<>(mainCrosstab); final CrosstabNavigator<Number> nav = new CrosstabNavigator<>(partialCrosstab); for (final String columnCategory : columnDimension.getCategories()) { // just navigate through the dimensions because is the column // dimension nav.where(columnDimension, columnCategory); mainNavigator.where(columnDimension, columnCategory); // navigate and sum up data final List<String> categories = measureDimension.getCategories(); for (final String measureCategory : categories) { sumUpData(mainNavigator, nav, measureDimension, measureCategory); } } } }
java
public static void addData(final Crosstab<Number> mainCrosstab, final Crosstab<Number> partialCrosstab, final CrosstabDimension columnDimension, final CrosstabDimension measureDimension) { if (partialCrosstab != null) { final CrosstabNavigator<Number> mainNavigator = new CrosstabNavigator<>(mainCrosstab); final CrosstabNavigator<Number> nav = new CrosstabNavigator<>(partialCrosstab); for (final String columnCategory : columnDimension.getCategories()) { // just navigate through the dimensions because is the column // dimension nav.where(columnDimension, columnCategory); mainNavigator.where(columnDimension, columnCategory); // navigate and sum up data final List<String> categories = measureDimension.getCategories(); for (final String measureCategory : categories) { sumUpData(mainNavigator, nav, measureDimension, measureCategory); } } } }
[ "public", "static", "void", "addData", "(", "final", "Crosstab", "<", "Number", ">", "mainCrosstab", ",", "final", "Crosstab", "<", "Number", ">", "partialCrosstab", ",", "final", "CrosstabDimension", "columnDimension", ",", "final", "CrosstabDimension", "measureDimension", ")", "{", "if", "(", "partialCrosstab", "!=", "null", ")", "{", "final", "CrosstabNavigator", "<", "Number", ">", "mainNavigator", "=", "new", "CrosstabNavigator", "<>", "(", "mainCrosstab", ")", ";", "final", "CrosstabNavigator", "<", "Number", ">", "nav", "=", "new", "CrosstabNavigator", "<>", "(", "partialCrosstab", ")", ";", "for", "(", "final", "String", "columnCategory", ":", "columnDimension", ".", "getCategories", "(", ")", ")", "{", "// just navigate through the dimensions because is the column", "// dimension", "nav", ".", "where", "(", "columnDimension", ",", "columnCategory", ")", ";", "mainNavigator", ".", "where", "(", "columnDimension", ",", "columnCategory", ")", ";", "// navigate and sum up data", "final", "List", "<", "String", ">", "categories", "=", "measureDimension", ".", "getCategories", "(", ")", ";", "for", "(", "final", "String", "measureCategory", ":", "categories", ")", "{", "sumUpData", "(", "mainNavigator", ",", "nav", ",", "measureDimension", ",", "measureCategory", ")", ";", "}", "}", "}", "}" ]
Add the values of partial crosstab to the main crosstab @param mainCrosstab - main crosstab @param partialCrosstab - partial crosstab
[ "Add", "the", "values", "of", "partial", "crosstab", "to", "the", "main", "crosstab" ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/engine/core/src/main/java/org/datacleaner/util/CrosstabReducerHelper.java#L79-L98
26,288
datacleaner/DataCleaner
desktop/ui/src/main/java/org/datacleaner/widgets/result/ValueDistributionResultSwingRendererGroupDelegate.java
ValueDistributionResultSwingRendererGroupDelegate.createChartPanel
private ChartPanel createChartPanel(final ValueCountingAnalyzerResult result) { if (_valueCounts.size() > ChartUtils.CATEGORY_COUNT_DISPLAY_THRESHOLD) { logger.info("Display threshold of {} in chart surpassed (got {}). Skipping chart.", ChartUtils.CATEGORY_COUNT_DISPLAY_THRESHOLD, _valueCounts.size()); return null; } final Integer distinctCount = result.getDistinctCount(); final Integer unexpectedValueCount = result.getUnexpectedValueCount(); final int totalCount = result.getTotalCount(); // chart for display of the dataset final String title = "Value distribution of " + _groupOrColumnName; final JFreeChart chart = ChartFactory .createBarChart(title, "Value", "Count", _dataset, PlotOrientation.HORIZONTAL, true, true, false); final List<Title> titles = new ArrayList<>(); titles.add(new ShortTextTitle("Total count: " + totalCount)); if (distinctCount != null) { titles.add(new ShortTextTitle("Distinct count: " + distinctCount)); } if (unexpectedValueCount != null) { titles.add(new ShortTextTitle("Unexpected value count: " + unexpectedValueCount)); } chart.setSubtitles(titles); ChartUtils.applyStyles(chart); // code-block for tweaking style and coloring of chart { final CategoryPlot plot = (CategoryPlot) chart.getPlot(); plot.getDomainAxis().setVisible(false); int colorIndex = 0; for (int i = 0; i < getDataSetItemCount(); i++) { final String key = getDataSetKey(i); final Color color; final String upperCaseKey = key.toUpperCase(); if (_valueColorMap.containsKey(upperCaseKey)) { color = _valueColorMap.get(upperCaseKey); } else { if (i == getDataSetItemCount() - 1) { // the last color should not be the same as the first if (colorIndex == 0) { colorIndex++; } } Color colorCandidate = SLICE_COLORS[colorIndex]; final int darkAmount = i / SLICE_COLORS.length; for (int j = 0; j < darkAmount; j++) { colorCandidate = WidgetUtils.slightlyDarker(colorCandidate); } color = colorCandidate; colorIndex++; if (colorIndex >= SLICE_COLORS.length) { colorIndex = 0; } } plot.getRenderer().setSeriesPaint(i, color); } } return ChartUtils.createPanel(chart, false); }
java
private ChartPanel createChartPanel(final ValueCountingAnalyzerResult result) { if (_valueCounts.size() > ChartUtils.CATEGORY_COUNT_DISPLAY_THRESHOLD) { logger.info("Display threshold of {} in chart surpassed (got {}). Skipping chart.", ChartUtils.CATEGORY_COUNT_DISPLAY_THRESHOLD, _valueCounts.size()); return null; } final Integer distinctCount = result.getDistinctCount(); final Integer unexpectedValueCount = result.getUnexpectedValueCount(); final int totalCount = result.getTotalCount(); // chart for display of the dataset final String title = "Value distribution of " + _groupOrColumnName; final JFreeChart chart = ChartFactory .createBarChart(title, "Value", "Count", _dataset, PlotOrientation.HORIZONTAL, true, true, false); final List<Title> titles = new ArrayList<>(); titles.add(new ShortTextTitle("Total count: " + totalCount)); if (distinctCount != null) { titles.add(new ShortTextTitle("Distinct count: " + distinctCount)); } if (unexpectedValueCount != null) { titles.add(new ShortTextTitle("Unexpected value count: " + unexpectedValueCount)); } chart.setSubtitles(titles); ChartUtils.applyStyles(chart); // code-block for tweaking style and coloring of chart { final CategoryPlot plot = (CategoryPlot) chart.getPlot(); plot.getDomainAxis().setVisible(false); int colorIndex = 0; for (int i = 0; i < getDataSetItemCount(); i++) { final String key = getDataSetKey(i); final Color color; final String upperCaseKey = key.toUpperCase(); if (_valueColorMap.containsKey(upperCaseKey)) { color = _valueColorMap.get(upperCaseKey); } else { if (i == getDataSetItemCount() - 1) { // the last color should not be the same as the first if (colorIndex == 0) { colorIndex++; } } Color colorCandidate = SLICE_COLORS[colorIndex]; final int darkAmount = i / SLICE_COLORS.length; for (int j = 0; j < darkAmount; j++) { colorCandidate = WidgetUtils.slightlyDarker(colorCandidate); } color = colorCandidate; colorIndex++; if (colorIndex >= SLICE_COLORS.length) { colorIndex = 0; } } plot.getRenderer().setSeriesPaint(i, color); } } return ChartUtils.createPanel(chart, false); }
[ "private", "ChartPanel", "createChartPanel", "(", "final", "ValueCountingAnalyzerResult", "result", ")", "{", "if", "(", "_valueCounts", ".", "size", "(", ")", ">", "ChartUtils", ".", "CATEGORY_COUNT_DISPLAY_THRESHOLD", ")", "{", "logger", ".", "info", "(", "\"Display threshold of {} in chart surpassed (got {}). Skipping chart.\"", ",", "ChartUtils", ".", "CATEGORY_COUNT_DISPLAY_THRESHOLD", ",", "_valueCounts", ".", "size", "(", ")", ")", ";", "return", "null", ";", "}", "final", "Integer", "distinctCount", "=", "result", ".", "getDistinctCount", "(", ")", ";", "final", "Integer", "unexpectedValueCount", "=", "result", ".", "getUnexpectedValueCount", "(", ")", ";", "final", "int", "totalCount", "=", "result", ".", "getTotalCount", "(", ")", ";", "// chart for display of the dataset", "final", "String", "title", "=", "\"Value distribution of \"", "+", "_groupOrColumnName", ";", "final", "JFreeChart", "chart", "=", "ChartFactory", ".", "createBarChart", "(", "title", ",", "\"Value\"", ",", "\"Count\"", ",", "_dataset", ",", "PlotOrientation", ".", "HORIZONTAL", ",", "true", ",", "true", ",", "false", ")", ";", "final", "List", "<", "Title", ">", "titles", "=", "new", "ArrayList", "<>", "(", ")", ";", "titles", ".", "add", "(", "new", "ShortTextTitle", "(", "\"Total count: \"", "+", "totalCount", ")", ")", ";", "if", "(", "distinctCount", "!=", "null", ")", "{", "titles", ".", "add", "(", "new", "ShortTextTitle", "(", "\"Distinct count: \"", "+", "distinctCount", ")", ")", ";", "}", "if", "(", "unexpectedValueCount", "!=", "null", ")", "{", "titles", ".", "add", "(", "new", "ShortTextTitle", "(", "\"Unexpected value count: \"", "+", "unexpectedValueCount", ")", ")", ";", "}", "chart", ".", "setSubtitles", "(", "titles", ")", ";", "ChartUtils", ".", "applyStyles", "(", "chart", ")", ";", "// code-block for tweaking style and coloring of chart", "{", "final", "CategoryPlot", "plot", "=", "(", "CategoryPlot", ")", "chart", ".", "getPlot", "(", ")", ";", "plot", ".", "getDomainAxis", "(", ")", ".", "setVisible", "(", "false", ")", ";", "int", "colorIndex", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "getDataSetItemCount", "(", ")", ";", "i", "++", ")", "{", "final", "String", "key", "=", "getDataSetKey", "(", "i", ")", ";", "final", "Color", "color", ";", "final", "String", "upperCaseKey", "=", "key", ".", "toUpperCase", "(", ")", ";", "if", "(", "_valueColorMap", ".", "containsKey", "(", "upperCaseKey", ")", ")", "{", "color", "=", "_valueColorMap", ".", "get", "(", "upperCaseKey", ")", ";", "}", "else", "{", "if", "(", "i", "==", "getDataSetItemCount", "(", ")", "-", "1", ")", "{", "// the last color should not be the same as the first", "if", "(", "colorIndex", "==", "0", ")", "{", "colorIndex", "++", ";", "}", "}", "Color", "colorCandidate", "=", "SLICE_COLORS", "[", "colorIndex", "]", ";", "final", "int", "darkAmount", "=", "i", "/", "SLICE_COLORS", ".", "length", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "darkAmount", ";", "j", "++", ")", "{", "colorCandidate", "=", "WidgetUtils", ".", "slightlyDarker", "(", "colorCandidate", ")", ";", "}", "color", "=", "colorCandidate", ";", "colorIndex", "++", ";", "if", "(", "colorIndex", ">=", "SLICE_COLORS", ".", "length", ")", "{", "colorIndex", "=", "0", ";", "}", "}", "plot", ".", "getRenderer", "(", ")", ".", "setSeriesPaint", "(", "i", ",", "color", ")", ";", "}", "}", "return", "ChartUtils", ".", "createPanel", "(", "chart", ",", "false", ")", ";", "}" ]
Creates a chart panel, or null if chart display is not applicable. @param result @return
[ "Creates", "a", "chart", "panel", "or", "null", "if", "chart", "display", "is", "not", "applicable", "." ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/desktop/ui/src/main/java/org/datacleaner/widgets/result/ValueDistributionResultSwingRendererGroupDelegate.java#L182-L248
26,289
datacleaner/DataCleaner
engine/env/spark/src/main/java/org/datacleaner/spark/SparkJobContext.java
SparkJobContext.getResultPath
public URI getResultPath() { final String str = _customProperties.get(PROPERTY_RESULT_PATH); if (Strings.isNullOrEmpty(str)) { return null; } return URI.create(str); }
java
public URI getResultPath() { final String str = _customProperties.get(PROPERTY_RESULT_PATH); if (Strings.isNullOrEmpty(str)) { return null; } return URI.create(str); }
[ "public", "URI", "getResultPath", "(", ")", "{", "final", "String", "str", "=", "_customProperties", ".", "get", "(", "PROPERTY_RESULT_PATH", ")", ";", "if", "(", "Strings", ".", "isNullOrEmpty", "(", "str", ")", ")", "{", "return", "null", ";", "}", "return", "URI", ".", "create", "(", "str", ")", ";", "}" ]
Gets the path defined in the job properties file @return
[ "Gets", "the", "path", "defined", "in", "the", "job", "properties", "file" ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/engine/env/spark/src/main/java/org/datacleaner/spark/SparkJobContext.java#L246-L252
26,290
datacleaner/DataCleaner
desktop/ui/src/main/java/org/datacleaner/windows/AnalysisJobBuilderWindowImpl.java
AnalysisJobBuilderWindowImpl.setDatastore
@Override public void setDatastore(final Datastore datastore, final boolean expandTree) { final DatastoreConnection con; if (datastore == null) { con = null; } else { con = datastore.openConnection(); } _datastore = datastore; if (_datastoreConnection != null) { _datastoreConnection.close(); } _analysisJobBuilder.setDatastore(datastore); _datastoreConnection = con; if (datastore == null) { _analysisJobBuilder.reset(); changePanel(AnalysisWindowPanelType.WELCOME); } else { changePanel(AnalysisWindowPanelType.EDITING_CONTEXT); addTableToSource(con); } setSchemaTree(datastore, expandTree, con); updateStatusLabel(); _graph.refresh(); }
java
@Override public void setDatastore(final Datastore datastore, final boolean expandTree) { final DatastoreConnection con; if (datastore == null) { con = null; } else { con = datastore.openConnection(); } _datastore = datastore; if (_datastoreConnection != null) { _datastoreConnection.close(); } _analysisJobBuilder.setDatastore(datastore); _datastoreConnection = con; if (datastore == null) { _analysisJobBuilder.reset(); changePanel(AnalysisWindowPanelType.WELCOME); } else { changePanel(AnalysisWindowPanelType.EDITING_CONTEXT); addTableToSource(con); } setSchemaTree(datastore, expandTree, con); updateStatusLabel(); _graph.refresh(); }
[ "@", "Override", "public", "void", "setDatastore", "(", "final", "Datastore", "datastore", ",", "final", "boolean", "expandTree", ")", "{", "final", "DatastoreConnection", "con", ";", "if", "(", "datastore", "==", "null", ")", "{", "con", "=", "null", ";", "}", "else", "{", "con", "=", "datastore", ".", "openConnection", "(", ")", ";", "}", "_datastore", "=", "datastore", ";", "if", "(", "_datastoreConnection", "!=", "null", ")", "{", "_datastoreConnection", ".", "close", "(", ")", ";", "}", "_analysisJobBuilder", ".", "setDatastore", "(", "datastore", ")", ";", "_datastoreConnection", "=", "con", ";", "if", "(", "datastore", "==", "null", ")", "{", "_analysisJobBuilder", ".", "reset", "(", ")", ";", "changePanel", "(", "AnalysisWindowPanelType", ".", "WELCOME", ")", ";", "}", "else", "{", "changePanel", "(", "AnalysisWindowPanelType", ".", "EDITING_CONTEXT", ")", ";", "addTableToSource", "(", "con", ")", ";", "}", "setSchemaTree", "(", "datastore", ",", "expandTree", ",", "con", ")", ";", "updateStatusLabel", "(", ")", ";", "_graph", ".", "refresh", "(", ")", ";", "}" ]
Initializes the window to use a particular datastore in the schema tree. @param datastore @param expandTree true if the datastore tree should be initially expanded.
[ "Initializes", "the", "window", "to", "use", "a", "particular", "datastore", "in", "the", "schema", "tree", "." ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/desktop/ui/src/main/java/org/datacleaner/windows/AnalysisJobBuilderWindowImpl.java#L443-L470
26,291
datacleaner/DataCleaner
desktop/ui/src/main/java/org/datacleaner/user/upgrade/DataCleanerHomeUpgrader.java
DataCleanerHomeUpgrader.upgrade
public boolean upgrade(final FileObject newFolder) { try { if (newFolder.getChildren().length != 0) { // if the folder is not new then we don't want to touch it return false; } final FileObject upgradeFromFolderCandidate = findUpgradeCandidate(newFolder); if (upgradeFromFolderCandidate == null) { logger.info("Did not find a suitable upgrade candidate"); return false; } logger.info("Upgrading DATACLEANER_HOME from : {}", upgradeFromFolderCandidate); newFolder.copyFrom(upgradeFromFolderCandidate, new AllFileSelector()); // special handling of userpreferences.dat - we only want to keep // the good parts ;-) final UserPreferencesUpgrader userPreferencesUpgrader = new UserPreferencesUpgrader(newFolder); userPreferencesUpgrader.upgrade(); // Overwrite example jobs final List<String> allFilePaths = DataCleanerHome.getAllInitialFiles(); for (final String filePath : allFilePaths) { overwriteFileWithDefaults(newFolder, filePath); } return true; } catch (final FileSystemException e) { logger.warn("Exception occured during upgrading: {}", e); return false; } }
java
public boolean upgrade(final FileObject newFolder) { try { if (newFolder.getChildren().length != 0) { // if the folder is not new then we don't want to touch it return false; } final FileObject upgradeFromFolderCandidate = findUpgradeCandidate(newFolder); if (upgradeFromFolderCandidate == null) { logger.info("Did not find a suitable upgrade candidate"); return false; } logger.info("Upgrading DATACLEANER_HOME from : {}", upgradeFromFolderCandidate); newFolder.copyFrom(upgradeFromFolderCandidate, new AllFileSelector()); // special handling of userpreferences.dat - we only want to keep // the good parts ;-) final UserPreferencesUpgrader userPreferencesUpgrader = new UserPreferencesUpgrader(newFolder); userPreferencesUpgrader.upgrade(); // Overwrite example jobs final List<String> allFilePaths = DataCleanerHome.getAllInitialFiles(); for (final String filePath : allFilePaths) { overwriteFileWithDefaults(newFolder, filePath); } return true; } catch (final FileSystemException e) { logger.warn("Exception occured during upgrading: {}", e); return false; } }
[ "public", "boolean", "upgrade", "(", "final", "FileObject", "newFolder", ")", "{", "try", "{", "if", "(", "newFolder", ".", "getChildren", "(", ")", ".", "length", "!=", "0", ")", "{", "// if the folder is not new then we don't want to touch it", "return", "false", ";", "}", "final", "FileObject", "upgradeFromFolderCandidate", "=", "findUpgradeCandidate", "(", "newFolder", ")", ";", "if", "(", "upgradeFromFolderCandidate", "==", "null", ")", "{", "logger", ".", "info", "(", "\"Did not find a suitable upgrade candidate\"", ")", ";", "return", "false", ";", "}", "logger", ".", "info", "(", "\"Upgrading DATACLEANER_HOME from : {}\"", ",", "upgradeFromFolderCandidate", ")", ";", "newFolder", ".", "copyFrom", "(", "upgradeFromFolderCandidate", ",", "new", "AllFileSelector", "(", ")", ")", ";", "// special handling of userpreferences.dat - we only want to keep", "// the good parts ;-)", "final", "UserPreferencesUpgrader", "userPreferencesUpgrader", "=", "new", "UserPreferencesUpgrader", "(", "newFolder", ")", ";", "userPreferencesUpgrader", ".", "upgrade", "(", ")", ";", "// Overwrite example jobs", "final", "List", "<", "String", ">", "allFilePaths", "=", "DataCleanerHome", ".", "getAllInitialFiles", "(", ")", ";", "for", "(", "final", "String", "filePath", ":", "allFilePaths", ")", "{", "overwriteFileWithDefaults", "(", "newFolder", ",", "filePath", ")", ";", "}", "return", "true", ";", "}", "catch", "(", "final", "FileSystemException", "e", ")", "{", "logger", ".", "warn", "(", "\"Exception occured during upgrading: {}\"", ",", "e", ")", ";", "return", "false", ";", "}", "}" ]
Finds a folder to upgrade from based on the "newFolder" parameter - upgrades are performed only within the same major version. @param newFolder The folder we want to upgrade to (the new version) @return true if upgrade was successful, false otherwise
[ "Finds", "a", "folder", "to", "upgrade", "from", "based", "on", "the", "newFolder", "parameter", "-", "upgrades", "are", "performed", "only", "within", "the", "same", "major", "version", "." ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/desktop/ui/src/main/java/org/datacleaner/user/upgrade/DataCleanerHomeUpgrader.java#L135-L167
26,292
datacleaner/DataCleaner
desktop/ui/src/main/java/org/datacleaner/widgets/properties/MultipleMappedEnumsPropertyWidget.java
MultipleMappedEnumsPropertyWidget.getEnumConstants
protected EnumerationValue[] getEnumConstants(final InputColumn<?> inputColumn, final ConfiguredPropertyDescriptor mappedEnumsProperty) { if (mappedEnumsProperty instanceof EnumerationProvider) { return ((EnumerationProvider) mappedEnumsProperty).values(); } else { return EnumerationValue.fromArray(mappedEnumsProperty.getBaseType().getEnumConstants()); } }
java
protected EnumerationValue[] getEnumConstants(final InputColumn<?> inputColumn, final ConfiguredPropertyDescriptor mappedEnumsProperty) { if (mappedEnumsProperty instanceof EnumerationProvider) { return ((EnumerationProvider) mappedEnumsProperty).values(); } else { return EnumerationValue.fromArray(mappedEnumsProperty.getBaseType().getEnumConstants()); } }
[ "protected", "EnumerationValue", "[", "]", "getEnumConstants", "(", "final", "InputColumn", "<", "?", ">", "inputColumn", ",", "final", "ConfiguredPropertyDescriptor", "mappedEnumsProperty", ")", "{", "if", "(", "mappedEnumsProperty", "instanceof", "EnumerationProvider", ")", "{", "return", "(", "(", "EnumerationProvider", ")", "mappedEnumsProperty", ")", ".", "values", "(", ")", ";", "}", "else", "{", "return", "EnumerationValue", ".", "fromArray", "(", "mappedEnumsProperty", ".", "getBaseType", "(", ")", ".", "getEnumConstants", "(", ")", ")", ";", "}", "}" ]
Produces a list of available enum values for a particular input column. @param inputColumn @param mappedEnumsProperty @return
[ "Produces", "a", "list", "of", "available", "enum", "values", "for", "a", "particular", "input", "column", "." ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/desktop/ui/src/main/java/org/datacleaner/widgets/properties/MultipleMappedEnumsPropertyWidget.java#L157-L164
26,293
datacleaner/DataCleaner
desktop/ui/src/main/java/org/datacleaner/widgets/properties/MultipleMappedEnumsPropertyWidget.java
MultipleMappedEnumsPropertyWidget.createComboBox
protected DCComboBox<EnumerationValue> createComboBox(final InputColumn<?> inputColumn, EnumerationValue mappedEnum) { if (mappedEnum == null && inputColumn != null) { mappedEnum = getSuggestedValue(inputColumn); } final EnumerationValue[] enumConstants = getEnumConstants(inputColumn, _mappedEnumsProperty); final DCComboBox<EnumerationValue> comboBox = new DCComboBox<>(enumConstants); comboBox.setRenderer(getComboBoxRenderer(inputColumn, _mappedEnumComboBoxes, enumConstants)); _mappedEnumComboBoxes.put(inputColumn, comboBox); if (mappedEnum != null) { comboBox.setEditable(true); comboBox.setSelectedItem(mappedEnum); comboBox.setEditable(false); } comboBox.addListener(item -> _mappedEnumsPropertyWidget.fireValueChanged()); return comboBox; }
java
protected DCComboBox<EnumerationValue> createComboBox(final InputColumn<?> inputColumn, EnumerationValue mappedEnum) { if (mappedEnum == null && inputColumn != null) { mappedEnum = getSuggestedValue(inputColumn); } final EnumerationValue[] enumConstants = getEnumConstants(inputColumn, _mappedEnumsProperty); final DCComboBox<EnumerationValue> comboBox = new DCComboBox<>(enumConstants); comboBox.setRenderer(getComboBoxRenderer(inputColumn, _mappedEnumComboBoxes, enumConstants)); _mappedEnumComboBoxes.put(inputColumn, comboBox); if (mappedEnum != null) { comboBox.setEditable(true); comboBox.setSelectedItem(mappedEnum); comboBox.setEditable(false); } comboBox.addListener(item -> _mappedEnumsPropertyWidget.fireValueChanged()); return comboBox; }
[ "protected", "DCComboBox", "<", "EnumerationValue", ">", "createComboBox", "(", "final", "InputColumn", "<", "?", ">", "inputColumn", ",", "EnumerationValue", "mappedEnum", ")", "{", "if", "(", "mappedEnum", "==", "null", "&&", "inputColumn", "!=", "null", ")", "{", "mappedEnum", "=", "getSuggestedValue", "(", "inputColumn", ")", ";", "}", "final", "EnumerationValue", "[", "]", "enumConstants", "=", "getEnumConstants", "(", "inputColumn", ",", "_mappedEnumsProperty", ")", ";", "final", "DCComboBox", "<", "EnumerationValue", ">", "comboBox", "=", "new", "DCComboBox", "<>", "(", "enumConstants", ")", ";", "comboBox", ".", "setRenderer", "(", "getComboBoxRenderer", "(", "inputColumn", ",", "_mappedEnumComboBoxes", ",", "enumConstants", ")", ")", ";", "_mappedEnumComboBoxes", ".", "put", "(", "inputColumn", ",", "comboBox", ")", ";", "if", "(", "mappedEnum", "!=", "null", ")", "{", "comboBox", ".", "setEditable", "(", "true", ")", ";", "comboBox", ".", "setSelectedItem", "(", "mappedEnum", ")", ";", "comboBox", ".", "setEditable", "(", "false", ")", ";", "}", "comboBox", ".", "addListener", "(", "item", "->", "_mappedEnumsPropertyWidget", ".", "fireValueChanged", "(", ")", ")", ";", "return", "comboBox", ";", "}" ]
Creates a combobox for a particular input column. @param inputColumn @param mappedEnum @return
[ "Creates", "a", "combobox", "for", "a", "particular", "input", "column", "." ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/desktop/ui/src/main/java/org/datacleaner/widgets/properties/MultipleMappedEnumsPropertyWidget.java#L178-L195
26,294
datacleaner/DataCleaner
desktop/ui/src/main/java/org/datacleaner/widgets/properties/MultipleMappedEnumsPropertyWidget.java
MultipleMappedEnumsPropertyWidget.getComboBoxRenderer
protected ListCellRenderer<? super EnumerationValue> getComboBoxRenderer(final InputColumn<?> inputColumn, final Map<InputColumn<?>, DCComboBox<EnumerationValue>> mappedEnumComboBoxes, final EnumerationValue[] enumConstants) { return new EnumComboBoxListRenderer(); }
java
protected ListCellRenderer<? super EnumerationValue> getComboBoxRenderer(final InputColumn<?> inputColumn, final Map<InputColumn<?>, DCComboBox<EnumerationValue>> mappedEnumComboBoxes, final EnumerationValue[] enumConstants) { return new EnumComboBoxListRenderer(); }
[ "protected", "ListCellRenderer", "<", "?", "super", "EnumerationValue", ">", "getComboBoxRenderer", "(", "final", "InputColumn", "<", "?", ">", "inputColumn", ",", "final", "Map", "<", "InputColumn", "<", "?", ">", ",", "DCComboBox", "<", "EnumerationValue", ">", ">", "mappedEnumComboBoxes", ",", "final", "EnumerationValue", "[", "]", "enumConstants", ")", "{", "return", "new", "EnumComboBoxListRenderer", "(", ")", ";", "}" ]
Gets the renderer of items in the comboboxes presenting the enum values. @param enumConstants @param mappedEnumComboBoxes @param inputColumn @return
[ "Gets", "the", "renderer", "of", "items", "in", "the", "comboboxes", "presenting", "the", "enum", "values", "." ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/desktop/ui/src/main/java/org/datacleaner/widgets/properties/MultipleMappedEnumsPropertyWidget.java#L206-L210
26,295
datacleaner/DataCleaner
engine/core/src/main/java/org/datacleaner/util/LabelUtils.java
LabelUtils.getValueLabel
public static String getValueLabel(final Object value) { if (value == null) { return NULL_LABEL; } if (value instanceof HasLabelAdvice) { final String suggestedLabel = ((HasLabelAdvice) value).getSuggestedLabel(); if (!Strings.isNullOrEmpty(suggestedLabel)) { return suggestedLabel; } } // format decimals if (value instanceof Double || value instanceof Float || value instanceof BigDecimal) { final NumberFormat format = NumberFormat.getNumberInstance(); final String result = format.format((Number) value); logger.debug("Formatted decimal {} to: {}", value, result); return result; } // format dates if (value instanceof Date) { final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); final String result = format.format((Date) value); logger.debug("Formatted date {} to: {}", value, result); return result; } return getLabel(value.toString()); }
java
public static String getValueLabel(final Object value) { if (value == null) { return NULL_LABEL; } if (value instanceof HasLabelAdvice) { final String suggestedLabel = ((HasLabelAdvice) value).getSuggestedLabel(); if (!Strings.isNullOrEmpty(suggestedLabel)) { return suggestedLabel; } } // format decimals if (value instanceof Double || value instanceof Float || value instanceof BigDecimal) { final NumberFormat format = NumberFormat.getNumberInstance(); final String result = format.format((Number) value); logger.debug("Formatted decimal {} to: {}", value, result); return result; } // format dates if (value instanceof Date) { final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); final String result = format.format((Date) value); logger.debug("Formatted date {} to: {}", value, result); return result; } return getLabel(value.toString()); }
[ "public", "static", "String", "getValueLabel", "(", "final", "Object", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "return", "NULL_LABEL", ";", "}", "if", "(", "value", "instanceof", "HasLabelAdvice", ")", "{", "final", "String", "suggestedLabel", "=", "(", "(", "HasLabelAdvice", ")", "value", ")", ".", "getSuggestedLabel", "(", ")", ";", "if", "(", "!", "Strings", ".", "isNullOrEmpty", "(", "suggestedLabel", ")", ")", "{", "return", "suggestedLabel", ";", "}", "}", "// format decimals", "if", "(", "value", "instanceof", "Double", "||", "value", "instanceof", "Float", "||", "value", "instanceof", "BigDecimal", ")", "{", "final", "NumberFormat", "format", "=", "NumberFormat", ".", "getNumberInstance", "(", ")", ";", "final", "String", "result", "=", "format", ".", "format", "(", "(", "Number", ")", "value", ")", ";", "logger", ".", "debug", "(", "\"Formatted decimal {} to: {}\"", ",", "value", ",", "result", ")", ";", "return", "result", ";", "}", "// format dates", "if", "(", "value", "instanceof", "Date", ")", "{", "final", "SimpleDateFormat", "format", "=", "new", "SimpleDateFormat", "(", "\"yyyy-MM-dd hh:mm:ss\"", ")", ";", "final", "String", "result", "=", "format", ".", "format", "(", "(", "Date", ")", "value", ")", ";", "logger", ".", "debug", "(", "\"Formatted date {} to: {}\"", ",", "value", ",", "result", ")", ";", "return", "result", ";", "}", "return", "getLabel", "(", "value", ".", "toString", "(", ")", ")", ";", "}" ]
Gets the label of a value, eg. a value in a crosstab. @param value @return
[ "Gets", "the", "label", "of", "a", "value", "eg", ".", "a", "value", "in", "a", "crosstab", "." ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/engine/core/src/main/java/org/datacleaner/util/LabelUtils.java#L196-L225
26,296
datacleaner/DataCleaner
desktop/ui/src/main/java/org/datacleaner/windows/MultiSourceColumnComboBoxPanel.java
MultiSourceColumnComboBoxPanel.createPanel
public DCPanel createPanel() { final DCPanel parentPanel = new DCPanel(); parentPanel.setLayout(new BorderLayout()); parentPanel.add(_sourceComboBoxPanel, BorderLayout.CENTER); parentPanel.add(_buttonPanel, BorderLayout.EAST); return parentPanel; }
java
public DCPanel createPanel() { final DCPanel parentPanel = new DCPanel(); parentPanel.setLayout(new BorderLayout()); parentPanel.add(_sourceComboBoxPanel, BorderLayout.CENTER); parentPanel.add(_buttonPanel, BorderLayout.EAST); return parentPanel; }
[ "public", "DCPanel", "createPanel", "(", ")", "{", "final", "DCPanel", "parentPanel", "=", "new", "DCPanel", "(", ")", ";", "parentPanel", ".", "setLayout", "(", "new", "BorderLayout", "(", ")", ")", ";", "parentPanel", ".", "add", "(", "_sourceComboBoxPanel", ",", "BorderLayout", ".", "CENTER", ")", ";", "parentPanel", ".", "add", "(", "_buttonPanel", ",", "BorderLayout", ".", "EAST", ")", ";", "return", "parentPanel", ";", "}" ]
Creates a panel containing ButtonPanel and SourceComboboxPanel @return DCPanel
[ "Creates", "a", "panel", "containing", "ButtonPanel", "and", "SourceComboboxPanel" ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/desktop/ui/src/main/java/org/datacleaner/windows/MultiSourceColumnComboBoxPanel.java#L94-L100
26,297
datacleaner/DataCleaner
desktop/ui/src/main/java/org/datacleaner/windows/MultiSourceColumnComboBoxPanel.java
MultiSourceColumnComboBoxPanel.updateSourceComboBoxes
public void updateSourceComboBoxes(final Datastore datastore, final Table table) { _datastore = datastore; _table = table; for (final SourceColumnComboBox sourceColComboBox : _sourceColumnComboBoxes) { sourceColComboBox.setModel(datastore, table); } }
java
public void updateSourceComboBoxes(final Datastore datastore, final Table table) { _datastore = datastore; _table = table; for (final SourceColumnComboBox sourceColComboBox : _sourceColumnComboBoxes) { sourceColComboBox.setModel(datastore, table); } }
[ "public", "void", "updateSourceComboBoxes", "(", "final", "Datastore", "datastore", ",", "final", "Table", "table", ")", "{", "_datastore", "=", "datastore", ";", "_table", "=", "table", ";", "for", "(", "final", "SourceColumnComboBox", "sourceColComboBox", ":", "_sourceColumnComboBoxes", ")", "{", "sourceColComboBox", ".", "setModel", "(", "datastore", ",", "table", ")", ";", "}", "}" ]
updates the SourceColumnComboBoxes with the provided datastore and table
[ "updates", "the", "SourceColumnComboBoxes", "with", "the", "provided", "datastore", "and", "table" ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/desktop/ui/src/main/java/org/datacleaner/windows/MultiSourceColumnComboBoxPanel.java#L163-L169
26,298
datacleaner/DataCleaner
components/date-gap/src/main/java/org/datacleaner/beans/dategap/TimeLine.java
TimeLine.getFrom
public Date getFrom() { final TimeInterval first = intervals.first(); if (first != null) { return new Date(first.getFrom()); } return null; }
java
public Date getFrom() { final TimeInterval first = intervals.first(); if (first != null) { return new Date(first.getFrom()); } return null; }
[ "public", "Date", "getFrom", "(", ")", "{", "final", "TimeInterval", "first", "=", "intervals", ".", "first", "(", ")", ";", "if", "(", "first", "!=", "null", ")", "{", "return", "new", "Date", "(", "first", ".", "getFrom", "(", ")", ")", ";", "}", "return", "null", ";", "}" ]
Gets the first date in this timeline @return
[ "Gets", "the", "first", "date", "in", "this", "timeline" ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/components/date-gap/src/main/java/org/datacleaner/beans/dategap/TimeLine.java#L150-L156
26,299
datacleaner/DataCleaner
components/date-gap/src/main/java/org/datacleaner/beans/dategap/TimeLine.java
TimeLine.getTo
public Date getTo() { Long to = null; for (final TimeInterval interval : intervals) { if (to == null) { to = interval.getTo(); } else { to = Math.max(interval.getTo(), to); } } if (to != null) { return new Date(to); } return null; }
java
public Date getTo() { Long to = null; for (final TimeInterval interval : intervals) { if (to == null) { to = interval.getTo(); } else { to = Math.max(interval.getTo(), to); } } if (to != null) { return new Date(to); } return null; }
[ "public", "Date", "getTo", "(", ")", "{", "Long", "to", "=", "null", ";", "for", "(", "final", "TimeInterval", "interval", ":", "intervals", ")", "{", "if", "(", "to", "==", "null", ")", "{", "to", "=", "interval", ".", "getTo", "(", ")", ";", "}", "else", "{", "to", "=", "Math", ".", "max", "(", "interval", ".", "getTo", "(", ")", ",", "to", ")", ";", "}", "}", "if", "(", "to", "!=", "null", ")", "{", "return", "new", "Date", "(", "to", ")", ";", "}", "return", "null", ";", "}" ]
Gets the last date in this timeline @return
[ "Gets", "the", "last", "date", "in", "this", "timeline" ]
9aa01fdac3560cef51c55df3cb2ac5c690b57639
https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/components/date-gap/src/main/java/org/datacleaner/beans/dategap/TimeLine.java#L163-L176