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,100
apache/incubator-gobblin
gobblin-api/src/main/java/org/apache/gobblin/source/workunit/Extract.java
Extract.setDeltaFields
@Deprecated public void setDeltaFields(String... deltaFieldName) { setProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY, Joiner.on(",").join(deltaFieldName)); }
java
@Deprecated public void setDeltaFields(String... deltaFieldName) { setProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY, Joiner.on(",").join(deltaFieldName)); }
[ "@", "Deprecated", "public", "void", "setDeltaFields", "(", "String", "...", "deltaFieldName", ")", "{", "setProp", "(", "ConfigurationKeys", ".", "EXTRACT_DELTA_FIELDS_KEY", ",", "Joiner", ".", "on", "(", "\",\"", ")", ".", "join", "(", "deltaFieldName", ")", ")", ";", "}" ]
Set delta fields. <p> The order of delta fields does not matter. </p> @param deltaFieldName delta field names @deprecated It is recommended to set delta fields in {@code WorkUnit} instead of {@code Extract}.
[ "Set", "delta", "fields", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/source/workunit/Extract.java#L275-L278
26,101
apache/incubator-gobblin
gobblin-api/src/main/java/org/apache/gobblin/source/workunit/Extract.java
Extract.addDeltaField
@Deprecated public void addDeltaField(String... deltaFieldName) { StringBuilder sb = new StringBuilder(getProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY, "")); Joiner.on(",").appendTo(sb, deltaFieldName); setProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY, sb.toString()); }
java
@Deprecated public void addDeltaField(String... deltaFieldName) { StringBuilder sb = new StringBuilder(getProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY, "")); Joiner.on(",").appendTo(sb, deltaFieldName); setProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY, sb.toString()); }
[ "@", "Deprecated", "public", "void", "addDeltaField", "(", "String", "...", "deltaFieldName", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "getProp", "(", "ConfigurationKeys", ".", "EXTRACT_DELTA_FIELDS_KEY", ",", "\"\"", ")", ")", ";", "Joiner", ".", "on", "(", "\",\"", ")", ".", "appendTo", "(", "sb", ",", "deltaFieldName", ")", ";", "setProp", "(", "ConfigurationKeys", ".", "EXTRACT_DELTA_FIELDS_KEY", ",", "sb", ".", "toString", "(", ")", ")", ";", "}" ]
Add more delta fields to the existing set of delta fields. @param deltaFieldName delta field names @deprecated It is recommended to add delta fields in {@code WorkUnit} instead of {@code Extract}.
[ "Add", "more", "delta", "fields", "to", "the", "existing", "set", "of", "delta", "fields", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/source/workunit/Extract.java#L286-L291
26,102
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/source/extractor/extract/restapi/RestApiConnector.java
RestApiConnector.connect
public boolean connect() throws RestApiConnectionException { if (this.autoEstablishAuthToken) { if (this.authTokenTimeout <= 0) { return false; } else if ((System.currentTimeMillis() - this.createdAt) > this.authTokenTimeout) { return false; } } HttpEntity httpEntity = null; try { httpEntity = getAuthentication(); if (httpEntity != null) { JsonElement json = GSON.fromJson(EntityUtils.toString(httpEntity), JsonObject.class); if (json == null) { log.error("Http entity: " + httpEntity); log.error("entity class: " + httpEntity.getClass().getName()); log.error("entity string size: " + EntityUtils.toString(httpEntity).length()); log.error("content length: " + httpEntity.getContentLength()); log.error("content: " + IOUtils.toString(httpEntity.getContent(), Charsets.UTF_8)); throw new RestApiConnectionException( "JSON is NULL ! Failed on authentication with the following HTTP response received:\n" + EntityUtils.toString(httpEntity)); } JsonObject jsonRet = json.getAsJsonObject(); log.info("jsonRet: " + jsonRet.toString()); parseAuthenticationResponse(jsonRet); } } catch (IOException e) { throw new RestApiConnectionException("Failed to get rest api connection; error - " + e.getMessage(), e); } finally { if (httpEntity != null) { try { EntityUtils.consume(httpEntity); } catch (IOException e) { throw new RestApiConnectionException("Failed to consume httpEntity; error - " + e.getMessage(), e); } } } return true; }
java
public boolean connect() throws RestApiConnectionException { if (this.autoEstablishAuthToken) { if (this.authTokenTimeout <= 0) { return false; } else if ((System.currentTimeMillis() - this.createdAt) > this.authTokenTimeout) { return false; } } HttpEntity httpEntity = null; try { httpEntity = getAuthentication(); if (httpEntity != null) { JsonElement json = GSON.fromJson(EntityUtils.toString(httpEntity), JsonObject.class); if (json == null) { log.error("Http entity: " + httpEntity); log.error("entity class: " + httpEntity.getClass().getName()); log.error("entity string size: " + EntityUtils.toString(httpEntity).length()); log.error("content length: " + httpEntity.getContentLength()); log.error("content: " + IOUtils.toString(httpEntity.getContent(), Charsets.UTF_8)); throw new RestApiConnectionException( "JSON is NULL ! Failed on authentication with the following HTTP response received:\n" + EntityUtils.toString(httpEntity)); } JsonObject jsonRet = json.getAsJsonObject(); log.info("jsonRet: " + jsonRet.toString()); parseAuthenticationResponse(jsonRet); } } catch (IOException e) { throw new RestApiConnectionException("Failed to get rest api connection; error - " + e.getMessage(), e); } finally { if (httpEntity != null) { try { EntityUtils.consume(httpEntity); } catch (IOException e) { throw new RestApiConnectionException("Failed to consume httpEntity; error - " + e.getMessage(), e); } } } return true; }
[ "public", "boolean", "connect", "(", ")", "throws", "RestApiConnectionException", "{", "if", "(", "this", ".", "autoEstablishAuthToken", ")", "{", "if", "(", "this", ".", "authTokenTimeout", "<=", "0", ")", "{", "return", "false", ";", "}", "else", "if", "(", "(", "System", ".", "currentTimeMillis", "(", ")", "-", "this", ".", "createdAt", ")", ">", "this", ".", "authTokenTimeout", ")", "{", "return", "false", ";", "}", "}", "HttpEntity", "httpEntity", "=", "null", ";", "try", "{", "httpEntity", "=", "getAuthentication", "(", ")", ";", "if", "(", "httpEntity", "!=", "null", ")", "{", "JsonElement", "json", "=", "GSON", ".", "fromJson", "(", "EntityUtils", ".", "toString", "(", "httpEntity", ")", ",", "JsonObject", ".", "class", ")", ";", "if", "(", "json", "==", "null", ")", "{", "log", ".", "error", "(", "\"Http entity: \"", "+", "httpEntity", ")", ";", "log", ".", "error", "(", "\"entity class: \"", "+", "httpEntity", ".", "getClass", "(", ")", ".", "getName", "(", ")", ")", ";", "log", ".", "error", "(", "\"entity string size: \"", "+", "EntityUtils", ".", "toString", "(", "httpEntity", ")", ".", "length", "(", ")", ")", ";", "log", ".", "error", "(", "\"content length: \"", "+", "httpEntity", ".", "getContentLength", "(", ")", ")", ";", "log", ".", "error", "(", "\"content: \"", "+", "IOUtils", ".", "toString", "(", "httpEntity", ".", "getContent", "(", ")", ",", "Charsets", ".", "UTF_8", ")", ")", ";", "throw", "new", "RestApiConnectionException", "(", "\"JSON is NULL ! Failed on authentication with the following HTTP response received:\\n\"", "+", "EntityUtils", ".", "toString", "(", "httpEntity", ")", ")", ";", "}", "JsonObject", "jsonRet", "=", "json", ".", "getAsJsonObject", "(", ")", ";", "log", ".", "info", "(", "\"jsonRet: \"", "+", "jsonRet", ".", "toString", "(", ")", ")", ";", "parseAuthenticationResponse", "(", "jsonRet", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RestApiConnectionException", "(", "\"Failed to get rest api connection; error - \"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "finally", "{", "if", "(", "httpEntity", "!=", "null", ")", "{", "try", "{", "EntityUtils", ".", "consume", "(", "httpEntity", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RestApiConnectionException", "(", "\"Failed to consume httpEntity; error - \"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}", "}", "return", "true", ";", "}" ]
get http connection @return true if the connection is success else false
[ "get", "http", "connection" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/source/extractor/extract/restapi/RestApiConnector.java#L84-L127
26,103
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/source/extractor/extract/restapi/RestApiConnector.java
RestApiConnector.getResponse
public CommandOutput<?, ?> getResponse(List<Command> cmds) throws RestApiProcessingException { String url = cmds.get(0).getParams().get(0); log.info("URL: " + url); String jsonStr = null; HttpRequestBase httpRequest = new HttpGet(url); addHeaders(httpRequest); HttpEntity httpEntity = null; HttpResponse httpResponse = null; try { httpResponse = this.httpClient.execute(httpRequest); StatusLine status = httpResponse.getStatusLine(); httpEntity = httpResponse.getEntity(); if (httpEntity != null) { jsonStr = EntityUtils.toString(httpEntity); } if (status.getStatusCode() >= 400) { log.info("Unable to get response using: " + url); JsonElement jsonRet = GSON.fromJson(jsonStr, JsonArray.class); throw new RestApiProcessingException(getFirstErrorMessage("Failed to retrieve response from", jsonRet)); } } catch (Exception e) { throw new RestApiProcessingException("Failed to process rest api request; error - " + e.getMessage(), e); } finally { try { if (httpEntity != null) { EntityUtils.consume(httpEntity); } // httpResponse.close(); } catch (Exception e) { throw new RestApiProcessingException("Failed to consume httpEntity; error - " + e.getMessage(), e); } } CommandOutput<RestApiCommand, String> output = new RestApiCommandOutput(); output.put((RestApiCommand) cmds.get(0), jsonStr); return output; }
java
public CommandOutput<?, ?> getResponse(List<Command> cmds) throws RestApiProcessingException { String url = cmds.get(0).getParams().get(0); log.info("URL: " + url); String jsonStr = null; HttpRequestBase httpRequest = new HttpGet(url); addHeaders(httpRequest); HttpEntity httpEntity = null; HttpResponse httpResponse = null; try { httpResponse = this.httpClient.execute(httpRequest); StatusLine status = httpResponse.getStatusLine(); httpEntity = httpResponse.getEntity(); if (httpEntity != null) { jsonStr = EntityUtils.toString(httpEntity); } if (status.getStatusCode() >= 400) { log.info("Unable to get response using: " + url); JsonElement jsonRet = GSON.fromJson(jsonStr, JsonArray.class); throw new RestApiProcessingException(getFirstErrorMessage("Failed to retrieve response from", jsonRet)); } } catch (Exception e) { throw new RestApiProcessingException("Failed to process rest api request; error - " + e.getMessage(), e); } finally { try { if (httpEntity != null) { EntityUtils.consume(httpEntity); } // httpResponse.close(); } catch (Exception e) { throw new RestApiProcessingException("Failed to consume httpEntity; error - " + e.getMessage(), e); } } CommandOutput<RestApiCommand, String> output = new RestApiCommandOutput(); output.put((RestApiCommand) cmds.get(0), jsonStr); return output; }
[ "public", "CommandOutput", "<", "?", ",", "?", ">", "getResponse", "(", "List", "<", "Command", ">", "cmds", ")", "throws", "RestApiProcessingException", "{", "String", "url", "=", "cmds", ".", "get", "(", "0", ")", ".", "getParams", "(", ")", ".", "get", "(", "0", ")", ";", "log", ".", "info", "(", "\"URL: \"", "+", "url", ")", ";", "String", "jsonStr", "=", "null", ";", "HttpRequestBase", "httpRequest", "=", "new", "HttpGet", "(", "url", ")", ";", "addHeaders", "(", "httpRequest", ")", ";", "HttpEntity", "httpEntity", "=", "null", ";", "HttpResponse", "httpResponse", "=", "null", ";", "try", "{", "httpResponse", "=", "this", ".", "httpClient", ".", "execute", "(", "httpRequest", ")", ";", "StatusLine", "status", "=", "httpResponse", ".", "getStatusLine", "(", ")", ";", "httpEntity", "=", "httpResponse", ".", "getEntity", "(", ")", ";", "if", "(", "httpEntity", "!=", "null", ")", "{", "jsonStr", "=", "EntityUtils", ".", "toString", "(", "httpEntity", ")", ";", "}", "if", "(", "status", ".", "getStatusCode", "(", ")", ">=", "400", ")", "{", "log", ".", "info", "(", "\"Unable to get response using: \"", "+", "url", ")", ";", "JsonElement", "jsonRet", "=", "GSON", ".", "fromJson", "(", "jsonStr", ",", "JsonArray", ".", "class", ")", ";", "throw", "new", "RestApiProcessingException", "(", "getFirstErrorMessage", "(", "\"Failed to retrieve response from\"", ",", "jsonRet", ")", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RestApiProcessingException", "(", "\"Failed to process rest api request; error - \"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "finally", "{", "try", "{", "if", "(", "httpEntity", "!=", "null", ")", "{", "EntityUtils", ".", "consume", "(", "httpEntity", ")", ";", "}", "// httpResponse.close();", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RestApiProcessingException", "(", "\"Failed to consume httpEntity; error - \"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}", "CommandOutput", "<", "RestApiCommand", ",", "String", ">", "output", "=", "new", "RestApiCommandOutput", "(", ")", ";", "output", ".", "put", "(", "(", "RestApiCommand", ")", "cmds", ".", "get", "(", "0", ")", ",", "jsonStr", ")", ";", "return", "output", ";", "}" ]
get http response in json format using url @return json string with the response
[ "get", "http", "response", "in", "json", "format", "using", "url" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/source/extractor/extract/restapi/RestApiConnector.java#L151-L189
26,104
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/source/extractor/extract/restapi/RestApiConnector.java
RestApiConnector.getFirstErrorMessage
private static String getFirstErrorMessage(String defaultMessage, JsonElement json) { if (json == null) { return defaultMessage; } JsonObject jsonObject = null; if (!json.isJsonArray()) { jsonObject = json.getAsJsonObject(); } else { JsonArray jsonArray = json.getAsJsonArray(); if (jsonArray.size() != 0) { jsonObject = jsonArray.get(0).getAsJsonObject(); } } if (jsonObject != null) { if (jsonObject.has("error_description")) { defaultMessage = defaultMessage + jsonObject.get("error_description").getAsString(); } else if (jsonObject.has("message")) { defaultMessage = defaultMessage + jsonObject.get("message").getAsString(); } } return defaultMessage; }
java
private static String getFirstErrorMessage(String defaultMessage, JsonElement json) { if (json == null) { return defaultMessage; } JsonObject jsonObject = null; if (!json.isJsonArray()) { jsonObject = json.getAsJsonObject(); } else { JsonArray jsonArray = json.getAsJsonArray(); if (jsonArray.size() != 0) { jsonObject = jsonArray.get(0).getAsJsonObject(); } } if (jsonObject != null) { if (jsonObject.has("error_description")) { defaultMessage = defaultMessage + jsonObject.get("error_description").getAsString(); } else if (jsonObject.has("message")) { defaultMessage = defaultMessage + jsonObject.get("message").getAsString(); } } return defaultMessage; }
[ "private", "static", "String", "getFirstErrorMessage", "(", "String", "defaultMessage", ",", "JsonElement", "json", ")", "{", "if", "(", "json", "==", "null", ")", "{", "return", "defaultMessage", ";", "}", "JsonObject", "jsonObject", "=", "null", ";", "if", "(", "!", "json", ".", "isJsonArray", "(", ")", ")", "{", "jsonObject", "=", "json", ".", "getAsJsonObject", "(", ")", ";", "}", "else", "{", "JsonArray", "jsonArray", "=", "json", ".", "getAsJsonArray", "(", ")", ";", "if", "(", "jsonArray", ".", "size", "(", ")", "!=", "0", ")", "{", "jsonObject", "=", "jsonArray", ".", "get", "(", "0", ")", ".", "getAsJsonObject", "(", ")", ";", "}", "}", "if", "(", "jsonObject", "!=", "null", ")", "{", "if", "(", "jsonObject", ".", "has", "(", "\"error_description\"", ")", ")", "{", "defaultMessage", "=", "defaultMessage", "+", "jsonObject", ".", "get", "(", "\"error_description\"", ")", ".", "getAsString", "(", ")", ";", "}", "else", "if", "(", "jsonObject", ".", "has", "(", "\"message\"", ")", ")", "{", "defaultMessage", "=", "defaultMessage", "+", "jsonObject", ".", "get", "(", "\"message\"", ")", ".", "getAsString", "(", ")", ";", "}", "}", "return", "defaultMessage", ";", "}" ]
get error message while executing http url @return error message
[ "get", "error", "message", "while", "executing", "http", "url" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/source/extractor/extract/restapi/RestApiConnector.java#L206-L231
26,105
apache/incubator-gobblin
gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/retention/CleanableHivePartitionDatasetFinder.java
CleanableHivePartitionDatasetFinder.findDatasets
public List<HivePartitionDataset> findDatasets() throws IOException { List<HivePartitionDataset> list = new ArrayList<>(); for (HivePartitionDataset hivePartitionDataset : super.findDatasets()) { CleanableHivePartitionDataset dataset = new CleanableHivePartitionDataset(hivePartitionDataset, this.fs, this.state); list.add(dataset); } return list; }
java
public List<HivePartitionDataset> findDatasets() throws IOException { List<HivePartitionDataset> list = new ArrayList<>(); for (HivePartitionDataset hivePartitionDataset : super.findDatasets()) { CleanableHivePartitionDataset dataset = new CleanableHivePartitionDataset(hivePartitionDataset, this.fs, this.state); list.add(dataset); } return list; }
[ "public", "List", "<", "HivePartitionDataset", ">", "findDatasets", "(", ")", "throws", "IOException", "{", "List", "<", "HivePartitionDataset", ">", "list", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "HivePartitionDataset", "hivePartitionDataset", ":", "super", ".", "findDatasets", "(", ")", ")", "{", "CleanableHivePartitionDataset", "dataset", "=", "new", "CleanableHivePartitionDataset", "(", "hivePartitionDataset", ",", "this", ".", "fs", ",", "this", ".", "state", ")", ";", "list", ".", "add", "(", "dataset", ")", ";", "}", "return", "list", ";", "}" ]
Will find all datasets according to whitelist, except the backup and staging tables.
[ "Will", "find", "all", "datasets", "according", "to", "whitelist", "except", "the", "backup", "and", "staging", "tables", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/retention/CleanableHivePartitionDatasetFinder.java#L53-L62
26,106
apache/incubator-gobblin
gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/source/extractor/extract/kafka/ConfigStoreUtils.java
ConfigStoreUtils.getConfig
public static Config getConfig(ConfigClient client, URI u, Optional<Config> runtimeConfig) { try { return client.getConfig(u, runtimeConfig); } catch (ConfigStoreFactoryDoesNotExistsException | ConfigStoreCreationException e) { throw new Error(e); } }
java
public static Config getConfig(ConfigClient client, URI u, Optional<Config> runtimeConfig) { try { return client.getConfig(u, runtimeConfig); } catch (ConfigStoreFactoryDoesNotExistsException | ConfigStoreCreationException e) { throw new Error(e); } }
[ "public", "static", "Config", "getConfig", "(", "ConfigClient", "client", ",", "URI", "u", ",", "Optional", "<", "Config", ">", "runtimeConfig", ")", "{", "try", "{", "return", "client", ".", "getConfig", "(", "u", ",", "runtimeConfig", ")", ";", "}", "catch", "(", "ConfigStoreFactoryDoesNotExistsException", "|", "ConfigStoreCreationException", "e", ")", "{", "throw", "new", "Error", "(", "e", ")", ";", "}", "}" ]
Wrapper to convert Checked Exception to Unchecked Exception Easy to use in lambda expressions
[ "Wrapper", "to", "convert", "Checked", "Exception", "to", "Unchecked", "Exception", "Easy", "to", "use", "in", "lambda", "expressions" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/source/extractor/extract/kafka/ConfigStoreUtils.java#L116-L122
26,107
apache/incubator-gobblin
gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/source/extractor/extract/kafka/ConfigStoreUtils.java
ConfigStoreUtils.getTopicsFromConfigStore
public static List<KafkaTopic> getTopicsFromConfigStore(Properties properties, String configStoreUri, GobblinKafkaConsumerClient kafkaConsumerClient) { ConfigClient configClient = ConfigClient.createConfigClient(VersionStabilityPolicy.WEAK_LOCAL_STABILITY); State state = new State(); state.setProp(KafkaSource.TOPIC_WHITELIST, ".*"); state.setProp(KafkaSource.TOPIC_BLACKLIST, StringUtils.EMPTY); List<KafkaTopic> allTopics = kafkaConsumerClient.getFilteredTopics(DatasetFilterUtils.getPatternList(state, KafkaSource.TOPIC_BLACKLIST), DatasetFilterUtils.getPatternList(state, KafkaSource.TOPIC_WHITELIST)); Optional<Config> runtimeConfig = ConfigClientUtils.getOptionalRuntimeConfig(properties); if (properties.containsKey(GOBBLIN_CONFIG_TAGS_WHITELIST)) { Preconditions.checkArgument(properties.containsKey(GOBBLIN_CONFIG_FILTER), "Missing required property " + GOBBLIN_CONFIG_FILTER); String filterString = properties.getProperty(GOBBLIN_CONFIG_FILTER); Path whiteListTagUri = PathUtils.mergePaths(new Path(configStoreUri), new Path(properties.getProperty(GOBBLIN_CONFIG_TAGS_WHITELIST))); List<String> whitelistedTopics = new ArrayList<>(); ConfigStoreUtils.getTopicsURIFromConfigStore(configClient, whiteListTagUri, filterString, runtimeConfig) .stream() .filter((URI u) -> ConfigUtils.getBoolean(ConfigStoreUtils.getConfig(configClient, u, runtimeConfig), KafkaSource.TOPIC_WHITELIST, false)) .forEach(((URI u) -> whitelistedTopics.add(ConfigStoreUtils.getTopicNameFromURI(u)))); return allTopics.stream() .filter((KafkaTopic p) -> whitelistedTopics.contains(p.getName())) .collect(Collectors.toList()); } else if (properties.containsKey(GOBBLIN_CONFIG_TAGS_BLACKLIST)) { Preconditions.checkArgument(properties.containsKey(GOBBLIN_CONFIG_FILTER), "Missing required property " + GOBBLIN_CONFIG_FILTER); String filterString = properties.getProperty(GOBBLIN_CONFIG_FILTER); Path blackListTagUri = PathUtils.mergePaths(new Path(configStoreUri), new Path(properties.getProperty(GOBBLIN_CONFIG_TAGS_BLACKLIST))); List<String> blacklistedTopics = new ArrayList<>(); ConfigStoreUtils.getTopicsURIFromConfigStore(configClient, blackListTagUri, filterString, runtimeConfig) .stream() .filter((URI u) -> ConfigUtils.getBoolean(ConfigStoreUtils.getConfig(configClient, u, runtimeConfig), KafkaSource.TOPIC_BLACKLIST, false)) .forEach(((URI u) -> blacklistedTopics.add(ConfigStoreUtils.getTopicNameFromURI(u)))); return allTopics.stream() .filter((KafkaTopic p) -> !blacklistedTopics.contains(p.getName())) .collect(Collectors.toList()); } else { log.warn("None of the blacklist or whitelist tags are provided"); return allTopics; } }
java
public static List<KafkaTopic> getTopicsFromConfigStore(Properties properties, String configStoreUri, GobblinKafkaConsumerClient kafkaConsumerClient) { ConfigClient configClient = ConfigClient.createConfigClient(VersionStabilityPolicy.WEAK_LOCAL_STABILITY); State state = new State(); state.setProp(KafkaSource.TOPIC_WHITELIST, ".*"); state.setProp(KafkaSource.TOPIC_BLACKLIST, StringUtils.EMPTY); List<KafkaTopic> allTopics = kafkaConsumerClient.getFilteredTopics(DatasetFilterUtils.getPatternList(state, KafkaSource.TOPIC_BLACKLIST), DatasetFilterUtils.getPatternList(state, KafkaSource.TOPIC_WHITELIST)); Optional<Config> runtimeConfig = ConfigClientUtils.getOptionalRuntimeConfig(properties); if (properties.containsKey(GOBBLIN_CONFIG_TAGS_WHITELIST)) { Preconditions.checkArgument(properties.containsKey(GOBBLIN_CONFIG_FILTER), "Missing required property " + GOBBLIN_CONFIG_FILTER); String filterString = properties.getProperty(GOBBLIN_CONFIG_FILTER); Path whiteListTagUri = PathUtils.mergePaths(new Path(configStoreUri), new Path(properties.getProperty(GOBBLIN_CONFIG_TAGS_WHITELIST))); List<String> whitelistedTopics = new ArrayList<>(); ConfigStoreUtils.getTopicsURIFromConfigStore(configClient, whiteListTagUri, filterString, runtimeConfig) .stream() .filter((URI u) -> ConfigUtils.getBoolean(ConfigStoreUtils.getConfig(configClient, u, runtimeConfig), KafkaSource.TOPIC_WHITELIST, false)) .forEach(((URI u) -> whitelistedTopics.add(ConfigStoreUtils.getTopicNameFromURI(u)))); return allTopics.stream() .filter((KafkaTopic p) -> whitelistedTopics.contains(p.getName())) .collect(Collectors.toList()); } else if (properties.containsKey(GOBBLIN_CONFIG_TAGS_BLACKLIST)) { Preconditions.checkArgument(properties.containsKey(GOBBLIN_CONFIG_FILTER), "Missing required property " + GOBBLIN_CONFIG_FILTER); String filterString = properties.getProperty(GOBBLIN_CONFIG_FILTER); Path blackListTagUri = PathUtils.mergePaths(new Path(configStoreUri), new Path(properties.getProperty(GOBBLIN_CONFIG_TAGS_BLACKLIST))); List<String> blacklistedTopics = new ArrayList<>(); ConfigStoreUtils.getTopicsURIFromConfigStore(configClient, blackListTagUri, filterString, runtimeConfig) .stream() .filter((URI u) -> ConfigUtils.getBoolean(ConfigStoreUtils.getConfig(configClient, u, runtimeConfig), KafkaSource.TOPIC_BLACKLIST, false)) .forEach(((URI u) -> blacklistedTopics.add(ConfigStoreUtils.getTopicNameFromURI(u)))); return allTopics.stream() .filter((KafkaTopic p) -> !blacklistedTopics.contains(p.getName())) .collect(Collectors.toList()); } else { log.warn("None of the blacklist or whitelist tags are provided"); return allTopics; } }
[ "public", "static", "List", "<", "KafkaTopic", ">", "getTopicsFromConfigStore", "(", "Properties", "properties", ",", "String", "configStoreUri", ",", "GobblinKafkaConsumerClient", "kafkaConsumerClient", ")", "{", "ConfigClient", "configClient", "=", "ConfigClient", ".", "createConfigClient", "(", "VersionStabilityPolicy", ".", "WEAK_LOCAL_STABILITY", ")", ";", "State", "state", "=", "new", "State", "(", ")", ";", "state", ".", "setProp", "(", "KafkaSource", ".", "TOPIC_WHITELIST", ",", "\".*\"", ")", ";", "state", ".", "setProp", "(", "KafkaSource", ".", "TOPIC_BLACKLIST", ",", "StringUtils", ".", "EMPTY", ")", ";", "List", "<", "KafkaTopic", ">", "allTopics", "=", "kafkaConsumerClient", ".", "getFilteredTopics", "(", "DatasetFilterUtils", ".", "getPatternList", "(", "state", ",", "KafkaSource", ".", "TOPIC_BLACKLIST", ")", ",", "DatasetFilterUtils", ".", "getPatternList", "(", "state", ",", "KafkaSource", ".", "TOPIC_WHITELIST", ")", ")", ";", "Optional", "<", "Config", ">", "runtimeConfig", "=", "ConfigClientUtils", ".", "getOptionalRuntimeConfig", "(", "properties", ")", ";", "if", "(", "properties", ".", "containsKey", "(", "GOBBLIN_CONFIG_TAGS_WHITELIST", ")", ")", "{", "Preconditions", ".", "checkArgument", "(", "properties", ".", "containsKey", "(", "GOBBLIN_CONFIG_FILTER", ")", ",", "\"Missing required property \"", "+", "GOBBLIN_CONFIG_FILTER", ")", ";", "String", "filterString", "=", "properties", ".", "getProperty", "(", "GOBBLIN_CONFIG_FILTER", ")", ";", "Path", "whiteListTagUri", "=", "PathUtils", ".", "mergePaths", "(", "new", "Path", "(", "configStoreUri", ")", ",", "new", "Path", "(", "properties", ".", "getProperty", "(", "GOBBLIN_CONFIG_TAGS_WHITELIST", ")", ")", ")", ";", "List", "<", "String", ">", "whitelistedTopics", "=", "new", "ArrayList", "<>", "(", ")", ";", "ConfigStoreUtils", ".", "getTopicsURIFromConfigStore", "(", "configClient", ",", "whiteListTagUri", ",", "filterString", ",", "runtimeConfig", ")", ".", "stream", "(", ")", ".", "filter", "(", "(", "URI", "u", ")", "->", "ConfigUtils", ".", "getBoolean", "(", "ConfigStoreUtils", ".", "getConfig", "(", "configClient", ",", "u", ",", "runtimeConfig", ")", ",", "KafkaSource", ".", "TOPIC_WHITELIST", ",", "false", ")", ")", ".", "forEach", "(", "(", "(", "URI", "u", ")", "->", "whitelistedTopics", ".", "add", "(", "ConfigStoreUtils", ".", "getTopicNameFromURI", "(", "u", ")", ")", ")", ")", ";", "return", "allTopics", ".", "stream", "(", ")", ".", "filter", "(", "(", "KafkaTopic", "p", ")", "->", "whitelistedTopics", ".", "contains", "(", "p", ".", "getName", "(", ")", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "}", "else", "if", "(", "properties", ".", "containsKey", "(", "GOBBLIN_CONFIG_TAGS_BLACKLIST", ")", ")", "{", "Preconditions", ".", "checkArgument", "(", "properties", ".", "containsKey", "(", "GOBBLIN_CONFIG_FILTER", ")", ",", "\"Missing required property \"", "+", "GOBBLIN_CONFIG_FILTER", ")", ";", "String", "filterString", "=", "properties", ".", "getProperty", "(", "GOBBLIN_CONFIG_FILTER", ")", ";", "Path", "blackListTagUri", "=", "PathUtils", ".", "mergePaths", "(", "new", "Path", "(", "configStoreUri", ")", ",", "new", "Path", "(", "properties", ".", "getProperty", "(", "GOBBLIN_CONFIG_TAGS_BLACKLIST", ")", ")", ")", ";", "List", "<", "String", ">", "blacklistedTopics", "=", "new", "ArrayList", "<>", "(", ")", ";", "ConfigStoreUtils", ".", "getTopicsURIFromConfigStore", "(", "configClient", ",", "blackListTagUri", ",", "filterString", ",", "runtimeConfig", ")", ".", "stream", "(", ")", ".", "filter", "(", "(", "URI", "u", ")", "->", "ConfigUtils", ".", "getBoolean", "(", "ConfigStoreUtils", ".", "getConfig", "(", "configClient", ",", "u", ",", "runtimeConfig", ")", ",", "KafkaSource", ".", "TOPIC_BLACKLIST", ",", "false", ")", ")", ".", "forEach", "(", "(", "(", "URI", "u", ")", "->", "blacklistedTopics", ".", "add", "(", "ConfigStoreUtils", ".", "getTopicNameFromURI", "(", "u", ")", ")", ")", ")", ";", "return", "allTopics", ".", "stream", "(", ")", ".", "filter", "(", "(", "KafkaTopic", "p", ")", "->", "!", "blacklistedTopics", ".", "contains", "(", "p", ".", "getName", "(", ")", ")", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "}", "else", "{", "log", ".", "warn", "(", "\"None of the blacklist or whitelist tags are provided\"", ")", ";", "return", "allTopics", ";", "}", "}" ]
Get topics from config store. Topics will either be whitelisted or blacklisted using tag. After filtering out topics via tag, their config property is checked. For each shortlisted topic, config must contain either property topic.blacklist or topic.whitelist If tags are not provided, it will return all topics
[ "Get", "topics", "from", "config", "store", ".", "Topics", "will", "either", "be", "whitelisted", "or", "blacklisted", "using", "tag", ".", "After", "filtering", "out", "topics", "via", "tag", "their", "config", "property", "is", "checked", ".", "For", "each", "shortlisted", "topic", "config", "must", "contain", "either", "property", "topic", ".", "blacklist", "or", "topic", ".", "whitelist" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/source/extractor/extract/kafka/ConfigStoreUtils.java#L132-L178
26,108
apache/incubator-gobblin
gobblin-audit/src/main/java/org/apache/gobblin/audit/values/sink/FsAuditSink.java
FsAuditSink.getAuditFilePath
public Path getAuditFilePath() { StringBuilder auditFileNameBuilder = new StringBuilder(); auditFileNameBuilder.append("P=").append(auditMetadata.getPhase()).append(FILE_NAME_DELIMITTER).append("C=") .append(auditMetadata.getCluster()).append(FILE_NAME_DELIMITTER).append("E=") .append(auditMetadata.getExtractId()).append(FILE_NAME_DELIMITTER).append("S=") .append(auditMetadata.getSnapshotId()).append(FILE_NAME_DELIMITTER).append("D=") .append(auditMetadata.getDeltaId()); return new Path(auditDirPath, PathUtils.combinePaths(auditMetadata.getTableMetadata().getDatabase(), auditMetadata .getTableMetadata().getTable(), auditFileNameBuilder.toString(), auditMetadata.getPartFileName())); }
java
public Path getAuditFilePath() { StringBuilder auditFileNameBuilder = new StringBuilder(); auditFileNameBuilder.append("P=").append(auditMetadata.getPhase()).append(FILE_NAME_DELIMITTER).append("C=") .append(auditMetadata.getCluster()).append(FILE_NAME_DELIMITTER).append("E=") .append(auditMetadata.getExtractId()).append(FILE_NAME_DELIMITTER).append("S=") .append(auditMetadata.getSnapshotId()).append(FILE_NAME_DELIMITTER).append("D=") .append(auditMetadata.getDeltaId()); return new Path(auditDirPath, PathUtils.combinePaths(auditMetadata.getTableMetadata().getDatabase(), auditMetadata .getTableMetadata().getTable(), auditFileNameBuilder.toString(), auditMetadata.getPartFileName())); }
[ "public", "Path", "getAuditFilePath", "(", ")", "{", "StringBuilder", "auditFileNameBuilder", "=", "new", "StringBuilder", "(", ")", ";", "auditFileNameBuilder", ".", "append", "(", "\"P=\"", ")", ".", "append", "(", "auditMetadata", ".", "getPhase", "(", ")", ")", ".", "append", "(", "FILE_NAME_DELIMITTER", ")", ".", "append", "(", "\"C=\"", ")", ".", "append", "(", "auditMetadata", ".", "getCluster", "(", ")", ")", ".", "append", "(", "FILE_NAME_DELIMITTER", ")", ".", "append", "(", "\"E=\"", ")", ".", "append", "(", "auditMetadata", ".", "getExtractId", "(", ")", ")", ".", "append", "(", "FILE_NAME_DELIMITTER", ")", ".", "append", "(", "\"S=\"", ")", ".", "append", "(", "auditMetadata", ".", "getSnapshotId", "(", ")", ")", ".", "append", "(", "FILE_NAME_DELIMITTER", ")", ".", "append", "(", "\"D=\"", ")", ".", "append", "(", "auditMetadata", ".", "getDeltaId", "(", ")", ")", ";", "return", "new", "Path", "(", "auditDirPath", ",", "PathUtils", ".", "combinePaths", "(", "auditMetadata", ".", "getTableMetadata", "(", ")", ".", "getDatabase", "(", ")", ",", "auditMetadata", ".", "getTableMetadata", "(", ")", ".", "getTable", "(", ")", ",", "auditFileNameBuilder", ".", "toString", "(", ")", ",", "auditMetadata", ".", "getPartFileName", "(", ")", ")", ")", ";", "}" ]
Returns the complete path of the audit file. Generate the audit file path with format <pre> |-- &lt;Database&gt; |-- &lt;Table&gt; |-- P=&lt;PHASE&gt;.C=&lt;CLUSTER&gt;.E=&lt;EXTRACT_ID&gt;.S=&lt;SNAPSHOT_ID&gt;.D=&lt;DELTA_ID&gt; |-- *.avro </pre>
[ "Returns", "the", "complete", "path", "of", "the", "audit", "file", ".", "Generate", "the", "audit", "file", "path", "with", "format" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-audit/src/main/java/org/apache/gobblin/audit/values/sink/FsAuditSink.java#L97-L107
26,109
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/trash/Trash.java
Trash.createTrashSnapshot
public void createTrashSnapshot() throws IOException { FileStatus[] pathsInTrash = this.fs.listStatus(this.trashLocation, TRASH_NOT_SNAPSHOT_PATH_FILTER); if (pathsInTrash.length <= 0) { LOG.info("Nothing in trash. Will not create snapshot."); return; } Path snapshotDir = new Path(this.trashLocation, new DateTime().toString(TRASH_SNAPSHOT_NAME_FORMATTER)); if (this.fs.exists(snapshotDir)) { throw new IOException("New snapshot directory " + snapshotDir.toString() + " already exists."); } if (!safeFsMkdir(fs, snapshotDir, PERM)) { throw new IOException("Failed to create new snapshot directory at " + snapshotDir.toString()); } LOG.info(String.format("Moving %d paths in Trash directory to newly created snapshot at %s.", pathsInTrash.length, snapshotDir.toString())); int pathsFailedToMove = 0; for (FileStatus fileStatus : pathsInTrash) { Path pathRelativeToTrash = PathUtils.relativizePath(fileStatus.getPath(), this.trashLocation); Path targetPath = new Path(snapshotDir, pathRelativeToTrash); boolean movedThisPath = true; try { movedThisPath = this.fs.rename(fileStatus.getPath(), targetPath); } catch (IOException exception) { LOG.error("Failed to move path " + fileStatus.getPath().toString() + " to snapshot.", exception); pathsFailedToMove += 1; continue; } if (!movedThisPath) { LOG.error("Failed to move path " + fileStatus.getPath().toString() + " to snapshot."); pathsFailedToMove += 1; } } if (pathsFailedToMove > 0) { LOG.error( String.format("Failed to move %d paths to the snapshot at %s.", pathsFailedToMove, snapshotDir.toString())); } }
java
public void createTrashSnapshot() throws IOException { FileStatus[] pathsInTrash = this.fs.listStatus(this.trashLocation, TRASH_NOT_SNAPSHOT_PATH_FILTER); if (pathsInTrash.length <= 0) { LOG.info("Nothing in trash. Will not create snapshot."); return; } Path snapshotDir = new Path(this.trashLocation, new DateTime().toString(TRASH_SNAPSHOT_NAME_FORMATTER)); if (this.fs.exists(snapshotDir)) { throw new IOException("New snapshot directory " + snapshotDir.toString() + " already exists."); } if (!safeFsMkdir(fs, snapshotDir, PERM)) { throw new IOException("Failed to create new snapshot directory at " + snapshotDir.toString()); } LOG.info(String.format("Moving %d paths in Trash directory to newly created snapshot at %s.", pathsInTrash.length, snapshotDir.toString())); int pathsFailedToMove = 0; for (FileStatus fileStatus : pathsInTrash) { Path pathRelativeToTrash = PathUtils.relativizePath(fileStatus.getPath(), this.trashLocation); Path targetPath = new Path(snapshotDir, pathRelativeToTrash); boolean movedThisPath = true; try { movedThisPath = this.fs.rename(fileStatus.getPath(), targetPath); } catch (IOException exception) { LOG.error("Failed to move path " + fileStatus.getPath().toString() + " to snapshot.", exception); pathsFailedToMove += 1; continue; } if (!movedThisPath) { LOG.error("Failed to move path " + fileStatus.getPath().toString() + " to snapshot."); pathsFailedToMove += 1; } } if (pathsFailedToMove > 0) { LOG.error( String.format("Failed to move %d paths to the snapshot at %s.", pathsFailedToMove, snapshotDir.toString())); } }
[ "public", "void", "createTrashSnapshot", "(", ")", "throws", "IOException", "{", "FileStatus", "[", "]", "pathsInTrash", "=", "this", ".", "fs", ".", "listStatus", "(", "this", ".", "trashLocation", ",", "TRASH_NOT_SNAPSHOT_PATH_FILTER", ")", ";", "if", "(", "pathsInTrash", ".", "length", "<=", "0", ")", "{", "LOG", ".", "info", "(", "\"Nothing in trash. Will not create snapshot.\"", ")", ";", "return", ";", "}", "Path", "snapshotDir", "=", "new", "Path", "(", "this", ".", "trashLocation", ",", "new", "DateTime", "(", ")", ".", "toString", "(", "TRASH_SNAPSHOT_NAME_FORMATTER", ")", ")", ";", "if", "(", "this", ".", "fs", ".", "exists", "(", "snapshotDir", ")", ")", "{", "throw", "new", "IOException", "(", "\"New snapshot directory \"", "+", "snapshotDir", ".", "toString", "(", ")", "+", "\" already exists.\"", ")", ";", "}", "if", "(", "!", "safeFsMkdir", "(", "fs", ",", "snapshotDir", ",", "PERM", ")", ")", "{", "throw", "new", "IOException", "(", "\"Failed to create new snapshot directory at \"", "+", "snapshotDir", ".", "toString", "(", ")", ")", ";", "}", "LOG", ".", "info", "(", "String", ".", "format", "(", "\"Moving %d paths in Trash directory to newly created snapshot at %s.\"", ",", "pathsInTrash", ".", "length", ",", "snapshotDir", ".", "toString", "(", ")", ")", ")", ";", "int", "pathsFailedToMove", "=", "0", ";", "for", "(", "FileStatus", "fileStatus", ":", "pathsInTrash", ")", "{", "Path", "pathRelativeToTrash", "=", "PathUtils", ".", "relativizePath", "(", "fileStatus", ".", "getPath", "(", ")", ",", "this", ".", "trashLocation", ")", ";", "Path", "targetPath", "=", "new", "Path", "(", "snapshotDir", ",", "pathRelativeToTrash", ")", ";", "boolean", "movedThisPath", "=", "true", ";", "try", "{", "movedThisPath", "=", "this", ".", "fs", ".", "rename", "(", "fileStatus", ".", "getPath", "(", ")", ",", "targetPath", ")", ";", "}", "catch", "(", "IOException", "exception", ")", "{", "LOG", ".", "error", "(", "\"Failed to move path \"", "+", "fileStatus", ".", "getPath", "(", ")", ".", "toString", "(", ")", "+", "\" to snapshot.\"", ",", "exception", ")", ";", "pathsFailedToMove", "+=", "1", ";", "continue", ";", "}", "if", "(", "!", "movedThisPath", ")", "{", "LOG", ".", "error", "(", "\"Failed to move path \"", "+", "fileStatus", ".", "getPath", "(", ")", ".", "toString", "(", ")", "+", "\" to snapshot.\"", ")", ";", "pathsFailedToMove", "+=", "1", ";", "}", "}", "if", "(", "pathsFailedToMove", ">", "0", ")", "{", "LOG", ".", "error", "(", "String", ".", "format", "(", "\"Failed to move %d paths to the snapshot at %s.\"", ",", "pathsFailedToMove", ",", "snapshotDir", ".", "toString", "(", ")", ")", ")", ";", "}", "}" ]
Moves all current contents of trash directory into a snapshot directory with current timestamp. @throws IOException
[ "Moves", "all", "current", "contents", "of", "trash", "directory", "into", "a", "snapshot", "directory", "with", "current", "timestamp", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/trash/Trash.java#L194-L237
26,110
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/trash/Trash.java
Trash.safeFsMkdir
private boolean safeFsMkdir(FileSystem fs, Path f, FsPermission permission) throws IOException { try { return fs.mkdirs(f, permission); } catch (IOException e) { // To handle the case when trash folder is created by other threads // The case is rare and we don't put synchronized keywords for performance consideration. if (!fs.exists(f)) { throw new IOException("Failed to create trash folder while it is still not existed yet."); } else { LOG.debug("Target folder %s has been created by other threads.", f.toString()); return true; } } }
java
private boolean safeFsMkdir(FileSystem fs, Path f, FsPermission permission) throws IOException { try { return fs.mkdirs(f, permission); } catch (IOException e) { // To handle the case when trash folder is created by other threads // The case is rare and we don't put synchronized keywords for performance consideration. if (!fs.exists(f)) { throw new IOException("Failed to create trash folder while it is still not existed yet."); } else { LOG.debug("Target folder %s has been created by other threads.", f.toString()); return true; } } }
[ "private", "boolean", "safeFsMkdir", "(", "FileSystem", "fs", ",", "Path", "f", ",", "FsPermission", "permission", ")", "throws", "IOException", "{", "try", "{", "return", "fs", ".", "mkdirs", "(", "f", ",", "permission", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "// To handle the case when trash folder is created by other threads", "// The case is rare and we don't put synchronized keywords for performance consideration.", "if", "(", "!", "fs", ".", "exists", "(", "f", ")", ")", "{", "throw", "new", "IOException", "(", "\"Failed to create trash folder while it is still not existed yet.\"", ")", ";", "}", "else", "{", "LOG", ".", "debug", "(", "\"Target folder %s has been created by other threads.\"", ",", "f", ".", "toString", "(", ")", ")", ";", "return", "true", ";", "}", "}", "}" ]
Safe creation of trash folder to ensure thread-safe. @throws IOException
[ "Safe", "creation", "of", "trash", "folder", "to", "ensure", "thread", "-", "safe", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/trash/Trash.java#L287-L300
26,111
apache/incubator-gobblin
gobblin-modules/gobblin-metrics-graphite/src/main/java/org/apache/gobblin/metrics/graphite/GraphitePusher.java
GraphitePusher.push
public void push(String name, String value, long timestamp) throws IOException { graphiteSender.send(name, value, timestamp); }
java
public void push(String name, String value, long timestamp) throws IOException { graphiteSender.send(name, value, timestamp); }
[ "public", "void", "push", "(", "String", "name", ",", "String", "value", ",", "long", "timestamp", ")", "throws", "IOException", "{", "graphiteSender", ".", "send", "(", "name", ",", "value", ",", "timestamp", ")", ";", "}" ]
Pushes a single metrics through the Graphite protocol to the underlying backend @param name metric name @param value metric value @param timestamp associated timestamp @throws IOException
[ "Pushes", "a", "single", "metrics", "through", "the", "Graphite", "protocol", "to", "the", "underlying", "backend" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-metrics-graphite/src/main/java/org/apache/gobblin/metrics/graphite/GraphitePusher.java#L53-L55
26,112
apache/incubator-gobblin
gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GobblinServiceManager.java
GobblinServiceManager.handleLeadershipChange
private void handleLeadershipChange(NotificationContext changeContext) { if (this.helixManager.isPresent() && this.helixManager.get().isLeader()) { LOGGER.info("Leader notification for {} HM.isLeader {}", this.helixManager.get().getInstanceName(), this.helixManager.get().isLeader()); if (this.isSchedulerEnabled) { LOGGER.info("Gobblin Service is now running in master instance mode, enabling Scheduler."); this.scheduler.setActive(true); } if (this.isGitConfigMonitorEnabled) { this.gitConfigMonitor.setActive(true); } if (this.isDagManagerEnabled) { //Activate DagManager only if TopologyCatalog is initialized. If not; skip activation. if (this.topologyCatalog.getInitComplete().getCount() == 0) { this.dagManager.setActive(true); } } } else if (this.helixManager.isPresent()) { LOGGER.info("Leader lost notification for {} HM.isLeader {}", this.helixManager.get().getInstanceName(), this.helixManager.get().isLeader()); if (this.isSchedulerEnabled) { LOGGER.info("Gobblin Service is now running in slave instance mode, disabling Scheduler."); this.scheduler.setActive(false); } if (this.isGitConfigMonitorEnabled) { this.gitConfigMonitor.setActive(false); } if (this.isDagManagerEnabled) { this.dagManager.setActive(false); } } }
java
private void handleLeadershipChange(NotificationContext changeContext) { if (this.helixManager.isPresent() && this.helixManager.get().isLeader()) { LOGGER.info("Leader notification for {} HM.isLeader {}", this.helixManager.get().getInstanceName(), this.helixManager.get().isLeader()); if (this.isSchedulerEnabled) { LOGGER.info("Gobblin Service is now running in master instance mode, enabling Scheduler."); this.scheduler.setActive(true); } if (this.isGitConfigMonitorEnabled) { this.gitConfigMonitor.setActive(true); } if (this.isDagManagerEnabled) { //Activate DagManager only if TopologyCatalog is initialized. If not; skip activation. if (this.topologyCatalog.getInitComplete().getCount() == 0) { this.dagManager.setActive(true); } } } else if (this.helixManager.isPresent()) { LOGGER.info("Leader lost notification for {} HM.isLeader {}", this.helixManager.get().getInstanceName(), this.helixManager.get().isLeader()); if (this.isSchedulerEnabled) { LOGGER.info("Gobblin Service is now running in slave instance mode, disabling Scheduler."); this.scheduler.setActive(false); } if (this.isGitConfigMonitorEnabled) { this.gitConfigMonitor.setActive(false); } if (this.isDagManagerEnabled) { this.dagManager.setActive(false); } } }
[ "private", "void", "handleLeadershipChange", "(", "NotificationContext", "changeContext", ")", "{", "if", "(", "this", ".", "helixManager", ".", "isPresent", "(", ")", "&&", "this", ".", "helixManager", ".", "get", "(", ")", ".", "isLeader", "(", ")", ")", "{", "LOGGER", ".", "info", "(", "\"Leader notification for {} HM.isLeader {}\"", ",", "this", ".", "helixManager", ".", "get", "(", ")", ".", "getInstanceName", "(", ")", ",", "this", ".", "helixManager", ".", "get", "(", ")", ".", "isLeader", "(", ")", ")", ";", "if", "(", "this", ".", "isSchedulerEnabled", ")", "{", "LOGGER", ".", "info", "(", "\"Gobblin Service is now running in master instance mode, enabling Scheduler.\"", ")", ";", "this", ".", "scheduler", ".", "setActive", "(", "true", ")", ";", "}", "if", "(", "this", ".", "isGitConfigMonitorEnabled", ")", "{", "this", ".", "gitConfigMonitor", ".", "setActive", "(", "true", ")", ";", "}", "if", "(", "this", ".", "isDagManagerEnabled", ")", "{", "//Activate DagManager only if TopologyCatalog is initialized. If not; skip activation.", "if", "(", "this", ".", "topologyCatalog", ".", "getInitComplete", "(", ")", ".", "getCount", "(", ")", "==", "0", ")", "{", "this", ".", "dagManager", ".", "setActive", "(", "true", ")", ";", "}", "}", "}", "else", "if", "(", "this", ".", "helixManager", ".", "isPresent", "(", ")", ")", "{", "LOGGER", ".", "info", "(", "\"Leader lost notification for {} HM.isLeader {}\"", ",", "this", ".", "helixManager", ".", "get", "(", ")", ".", "getInstanceName", "(", ")", ",", "this", ".", "helixManager", ".", "get", "(", ")", ".", "isLeader", "(", ")", ")", ";", "if", "(", "this", ".", "isSchedulerEnabled", ")", "{", "LOGGER", ".", "info", "(", "\"Gobblin Service is now running in slave instance mode, disabling Scheduler.\"", ")", ";", "this", ".", "scheduler", ".", "setActive", "(", "false", ")", ";", "}", "if", "(", "this", ".", "isGitConfigMonitorEnabled", ")", "{", "this", ".", "gitConfigMonitor", ".", "setActive", "(", "false", ")", ";", "}", "if", "(", "this", ".", "isDagManagerEnabled", ")", "{", "this", ".", "dagManager", ".", "setActive", "(", "false", ")", ";", "}", "}", "}" ]
Handle leadership change. @param changeContext notification context
[ "Handle", "leadership", "change", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GobblinServiceManager.java#L364-L400
26,113
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/JobLauncherUtils.java
JobLauncherUtils.newJobId
public static String newJobId(String jobName) { return Id.Job.create(jobName, System.currentTimeMillis()).toString(); }
java
public static String newJobId(String jobName) { return Id.Job.create(jobName, System.currentTimeMillis()).toString(); }
[ "public", "static", "String", "newJobId", "(", "String", "jobName", ")", "{", "return", "Id", ".", "Job", ".", "create", "(", "jobName", ",", "System", ".", "currentTimeMillis", "(", ")", ")", ".", "toString", "(", ")", ";", "}" ]
Create a new job ID. @param jobName job name @return new job ID
[ "Create", "a", "new", "job", "ID", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/JobLauncherUtils.java#L67-L69
26,114
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/JobLauncherUtils.java
JobLauncherUtils.newTaskId
public static String newTaskId(String jobId, int sequence) { return Id.Task.create(Id.parse(jobId).get(Id.Parts.INSTANCE_NAME), sequence).toString(); }
java
public static String newTaskId(String jobId, int sequence) { return Id.Task.create(Id.parse(jobId).get(Id.Parts.INSTANCE_NAME), sequence).toString(); }
[ "public", "static", "String", "newTaskId", "(", "String", "jobId", ",", "int", "sequence", ")", "{", "return", "Id", ".", "Task", ".", "create", "(", "Id", ".", "parse", "(", "jobId", ")", ".", "get", "(", "Id", ".", "Parts", ".", "INSTANCE_NAME", ")", ",", "sequence", ")", ".", "toString", "(", ")", ";", "}" ]
Create a new task ID for the job with the given job ID. @param jobId job ID @param sequence task sequence number @return new task ID
[ "Create", "a", "new", "task", "ID", "for", "the", "job", "with", "the", "given", "job", "ID", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/JobLauncherUtils.java#L78-L80
26,115
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/JobLauncherUtils.java
JobLauncherUtils.cleanJobStagingData
public static void cleanJobStagingData(State state, Logger logger) throws IOException { Preconditions.checkArgument(state.contains(ConfigurationKeys.WRITER_STAGING_DIR), "Missing required property " + ConfigurationKeys.WRITER_STAGING_DIR); Preconditions.checkArgument(state.contains(ConfigurationKeys.WRITER_OUTPUT_DIR), "Missing required property " + ConfigurationKeys.WRITER_OUTPUT_DIR); String writerFsUri = state.getProp(ConfigurationKeys.WRITER_FILE_SYSTEM_URI, ConfigurationKeys.LOCAL_FS_URI); FileSystem fs = getFsWithProxy(state, writerFsUri, WriterUtils.getFsConfiguration(state)); Path jobStagingPath = new Path(state.getProp(ConfigurationKeys.WRITER_STAGING_DIR)); logger.info("Cleaning up staging directory " + jobStagingPath); HadoopUtils.deletePath(fs, jobStagingPath, true); if (fs.exists(jobStagingPath.getParent()) && fs.listStatus(jobStagingPath.getParent()).length == 0) { logger.info("Deleting directory " + jobStagingPath.getParent()); HadoopUtils.deletePath(fs, jobStagingPath.getParent(), true); } Path jobOutputPath = new Path(state.getProp(ConfigurationKeys.WRITER_OUTPUT_DIR)); logger.info("Cleaning up output directory " + jobOutputPath); HadoopUtils.deletePath(fs, jobOutputPath, true); if (fs.exists(jobOutputPath.getParent()) && fs.listStatus(jobOutputPath.getParent()).length == 0) { logger.info("Deleting directory " + jobOutputPath.getParent()); HadoopUtils.deletePath(fs, jobOutputPath.getParent(), true); } if (state.contains(ConfigurationKeys.ROW_LEVEL_ERR_FILE)) { if (state.getPropAsBoolean(ConfigurationKeys.CLEAN_ERR_DIR, ConfigurationKeys.DEFAULT_CLEAN_ERR_DIR)) { Path jobErrPath = new Path(state.getProp(ConfigurationKeys.ROW_LEVEL_ERR_FILE)); log.info("Cleaning up err directory : " + jobErrPath); HadoopUtils.deleteIfExists(fs, jobErrPath, true); } } }
java
public static void cleanJobStagingData(State state, Logger logger) throws IOException { Preconditions.checkArgument(state.contains(ConfigurationKeys.WRITER_STAGING_DIR), "Missing required property " + ConfigurationKeys.WRITER_STAGING_DIR); Preconditions.checkArgument(state.contains(ConfigurationKeys.WRITER_OUTPUT_DIR), "Missing required property " + ConfigurationKeys.WRITER_OUTPUT_DIR); String writerFsUri = state.getProp(ConfigurationKeys.WRITER_FILE_SYSTEM_URI, ConfigurationKeys.LOCAL_FS_URI); FileSystem fs = getFsWithProxy(state, writerFsUri, WriterUtils.getFsConfiguration(state)); Path jobStagingPath = new Path(state.getProp(ConfigurationKeys.WRITER_STAGING_DIR)); logger.info("Cleaning up staging directory " + jobStagingPath); HadoopUtils.deletePath(fs, jobStagingPath, true); if (fs.exists(jobStagingPath.getParent()) && fs.listStatus(jobStagingPath.getParent()).length == 0) { logger.info("Deleting directory " + jobStagingPath.getParent()); HadoopUtils.deletePath(fs, jobStagingPath.getParent(), true); } Path jobOutputPath = new Path(state.getProp(ConfigurationKeys.WRITER_OUTPUT_DIR)); logger.info("Cleaning up output directory " + jobOutputPath); HadoopUtils.deletePath(fs, jobOutputPath, true); if (fs.exists(jobOutputPath.getParent()) && fs.listStatus(jobOutputPath.getParent()).length == 0) { logger.info("Deleting directory " + jobOutputPath.getParent()); HadoopUtils.deletePath(fs, jobOutputPath.getParent(), true); } if (state.contains(ConfigurationKeys.ROW_LEVEL_ERR_FILE)) { if (state.getPropAsBoolean(ConfigurationKeys.CLEAN_ERR_DIR, ConfigurationKeys.DEFAULT_CLEAN_ERR_DIR)) { Path jobErrPath = new Path(state.getProp(ConfigurationKeys.ROW_LEVEL_ERR_FILE)); log.info("Cleaning up err directory : " + jobErrPath); HadoopUtils.deleteIfExists(fs, jobErrPath, true); } } }
[ "public", "static", "void", "cleanJobStagingData", "(", "State", "state", ",", "Logger", "logger", ")", "throws", "IOException", "{", "Preconditions", ".", "checkArgument", "(", "state", ".", "contains", "(", "ConfigurationKeys", ".", "WRITER_STAGING_DIR", ")", ",", "\"Missing required property \"", "+", "ConfigurationKeys", ".", "WRITER_STAGING_DIR", ")", ";", "Preconditions", ".", "checkArgument", "(", "state", ".", "contains", "(", "ConfigurationKeys", ".", "WRITER_OUTPUT_DIR", ")", ",", "\"Missing required property \"", "+", "ConfigurationKeys", ".", "WRITER_OUTPUT_DIR", ")", ";", "String", "writerFsUri", "=", "state", ".", "getProp", "(", "ConfigurationKeys", ".", "WRITER_FILE_SYSTEM_URI", ",", "ConfigurationKeys", ".", "LOCAL_FS_URI", ")", ";", "FileSystem", "fs", "=", "getFsWithProxy", "(", "state", ",", "writerFsUri", ",", "WriterUtils", ".", "getFsConfiguration", "(", "state", ")", ")", ";", "Path", "jobStagingPath", "=", "new", "Path", "(", "state", ".", "getProp", "(", "ConfigurationKeys", ".", "WRITER_STAGING_DIR", ")", ")", ";", "logger", ".", "info", "(", "\"Cleaning up staging directory \"", "+", "jobStagingPath", ")", ";", "HadoopUtils", ".", "deletePath", "(", "fs", ",", "jobStagingPath", ",", "true", ")", ";", "if", "(", "fs", ".", "exists", "(", "jobStagingPath", ".", "getParent", "(", ")", ")", "&&", "fs", ".", "listStatus", "(", "jobStagingPath", ".", "getParent", "(", ")", ")", ".", "length", "==", "0", ")", "{", "logger", ".", "info", "(", "\"Deleting directory \"", "+", "jobStagingPath", ".", "getParent", "(", ")", ")", ";", "HadoopUtils", ".", "deletePath", "(", "fs", ",", "jobStagingPath", ".", "getParent", "(", ")", ",", "true", ")", ";", "}", "Path", "jobOutputPath", "=", "new", "Path", "(", "state", ".", "getProp", "(", "ConfigurationKeys", ".", "WRITER_OUTPUT_DIR", ")", ")", ";", "logger", ".", "info", "(", "\"Cleaning up output directory \"", "+", "jobOutputPath", ")", ";", "HadoopUtils", ".", "deletePath", "(", "fs", ",", "jobOutputPath", ",", "true", ")", ";", "if", "(", "fs", ".", "exists", "(", "jobOutputPath", ".", "getParent", "(", ")", ")", "&&", "fs", ".", "listStatus", "(", "jobOutputPath", ".", "getParent", "(", ")", ")", ".", "length", "==", "0", ")", "{", "logger", ".", "info", "(", "\"Deleting directory \"", "+", "jobOutputPath", ".", "getParent", "(", ")", ")", ";", "HadoopUtils", ".", "deletePath", "(", "fs", ",", "jobOutputPath", ".", "getParent", "(", ")", ",", "true", ")", ";", "}", "if", "(", "state", ".", "contains", "(", "ConfigurationKeys", ".", "ROW_LEVEL_ERR_FILE", ")", ")", "{", "if", "(", "state", ".", "getPropAsBoolean", "(", "ConfigurationKeys", ".", "CLEAN_ERR_DIR", ",", "ConfigurationKeys", ".", "DEFAULT_CLEAN_ERR_DIR", ")", ")", "{", "Path", "jobErrPath", "=", "new", "Path", "(", "state", ".", "getProp", "(", "ConfigurationKeys", ".", "ROW_LEVEL_ERR_FILE", ")", ")", ";", "log", ".", "info", "(", "\"Cleaning up err directory : \"", "+", "jobErrPath", ")", ";", "HadoopUtils", ".", "deleteIfExists", "(", "fs", ",", "jobErrPath", ",", "true", ")", ";", "}", "}", "}" ]
Cleanup staging data of all tasks of a job. @param state a {@link State} instance storing job configuration properties @param logger a {@link Logger} used for logging
[ "Cleanup", "staging", "data", "of", "all", "tasks", "of", "a", "job", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/JobLauncherUtils.java#L134-L168
26,116
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/JobLauncherUtils.java
JobLauncherUtils.cleanTaskStagingData
public static void cleanTaskStagingData(State state, Logger logger) throws IOException { int numBranches = state.getPropAsInt(ConfigurationKeys.FORK_BRANCHES_KEY, 1); for (int branchId = 0; branchId < numBranches; branchId++) { String writerFsUri = state.getProp( ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_SYSTEM_URI, numBranches, branchId), ConfigurationKeys.LOCAL_FS_URI); FileSystem fs = getFsWithProxy(state, writerFsUri, WriterUtils.getFsConfiguration(state)); Path stagingPath = WriterUtils.getWriterStagingDir(state, numBranches, branchId); if (fs.exists(stagingPath)) { logger.info("Cleaning up staging directory " + stagingPath.toUri().getPath()); if (!fs.delete(stagingPath, true)) { throw new IOException("Clean up staging directory " + stagingPath.toUri().getPath() + " failed"); } } Path outputPath = WriterUtils.getWriterOutputDir(state, numBranches, branchId); if (fs.exists(outputPath)) { logger.info("Cleaning up output directory " + outputPath.toUri().getPath()); if (!fs.delete(outputPath, true)) { throw new IOException("Clean up output directory " + outputPath.toUri().getPath() + " failed"); } } } }
java
public static void cleanTaskStagingData(State state, Logger logger) throws IOException { int numBranches = state.getPropAsInt(ConfigurationKeys.FORK_BRANCHES_KEY, 1); for (int branchId = 0; branchId < numBranches; branchId++) { String writerFsUri = state.getProp( ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_SYSTEM_URI, numBranches, branchId), ConfigurationKeys.LOCAL_FS_URI); FileSystem fs = getFsWithProxy(state, writerFsUri, WriterUtils.getFsConfiguration(state)); Path stagingPath = WriterUtils.getWriterStagingDir(state, numBranches, branchId); if (fs.exists(stagingPath)) { logger.info("Cleaning up staging directory " + stagingPath.toUri().getPath()); if (!fs.delete(stagingPath, true)) { throw new IOException("Clean up staging directory " + stagingPath.toUri().getPath() + " failed"); } } Path outputPath = WriterUtils.getWriterOutputDir(state, numBranches, branchId); if (fs.exists(outputPath)) { logger.info("Cleaning up output directory " + outputPath.toUri().getPath()); if (!fs.delete(outputPath, true)) { throw new IOException("Clean up output directory " + outputPath.toUri().getPath() + " failed"); } } } }
[ "public", "static", "void", "cleanTaskStagingData", "(", "State", "state", ",", "Logger", "logger", ")", "throws", "IOException", "{", "int", "numBranches", "=", "state", ".", "getPropAsInt", "(", "ConfigurationKeys", ".", "FORK_BRANCHES_KEY", ",", "1", ")", ";", "for", "(", "int", "branchId", "=", "0", ";", "branchId", "<", "numBranches", ";", "branchId", "++", ")", "{", "String", "writerFsUri", "=", "state", ".", "getProp", "(", "ForkOperatorUtils", ".", "getPropertyNameForBranch", "(", "ConfigurationKeys", ".", "WRITER_FILE_SYSTEM_URI", ",", "numBranches", ",", "branchId", ")", ",", "ConfigurationKeys", ".", "LOCAL_FS_URI", ")", ";", "FileSystem", "fs", "=", "getFsWithProxy", "(", "state", ",", "writerFsUri", ",", "WriterUtils", ".", "getFsConfiguration", "(", "state", ")", ")", ";", "Path", "stagingPath", "=", "WriterUtils", ".", "getWriterStagingDir", "(", "state", ",", "numBranches", ",", "branchId", ")", ";", "if", "(", "fs", ".", "exists", "(", "stagingPath", ")", ")", "{", "logger", ".", "info", "(", "\"Cleaning up staging directory \"", "+", "stagingPath", ".", "toUri", "(", ")", ".", "getPath", "(", ")", ")", ";", "if", "(", "!", "fs", ".", "delete", "(", "stagingPath", ",", "true", ")", ")", "{", "throw", "new", "IOException", "(", "\"Clean up staging directory \"", "+", "stagingPath", ".", "toUri", "(", ")", ".", "getPath", "(", ")", "+", "\" failed\"", ")", ";", "}", "}", "Path", "outputPath", "=", "WriterUtils", ".", "getWriterOutputDir", "(", "state", ",", "numBranches", ",", "branchId", ")", ";", "if", "(", "fs", ".", "exists", "(", "outputPath", ")", ")", "{", "logger", ".", "info", "(", "\"Cleaning up output directory \"", "+", "outputPath", ".", "toUri", "(", ")", ".", "getPath", "(", ")", ")", ";", "if", "(", "!", "fs", ".", "delete", "(", "outputPath", ",", "true", ")", ")", "{", "throw", "new", "IOException", "(", "\"Clean up output directory \"", "+", "outputPath", ".", "toUri", "(", ")", ".", "getPath", "(", ")", "+", "\" failed\"", ")", ";", "}", "}", "}", "}" ]
Cleanup staging data of a Gobblin task. @param state a {@link State} instance storing task configuration properties @param logger a {@link Logger} used for logging
[ "Cleanup", "staging", "data", "of", "a", "Gobblin", "task", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/JobLauncherUtils.java#L176-L201
26,117
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/conversion/hive/events/EventWorkunitUtils.java
EventWorkunitUtils.setEvolutionMetadata
public static void setEvolutionMetadata(State state, List<String> evolutionDDLs) { state.setProp(EventConstants.SCHEMA_EVOLUTION_DDLS_NUM, evolutionDDLs == null ? 0 : evolutionDDLs.size()); }
java
public static void setEvolutionMetadata(State state, List<String> evolutionDDLs) { state.setProp(EventConstants.SCHEMA_EVOLUTION_DDLS_NUM, evolutionDDLs == null ? 0 : evolutionDDLs.size()); }
[ "public", "static", "void", "setEvolutionMetadata", "(", "State", "state", ",", "List", "<", "String", ">", "evolutionDDLs", ")", "{", "state", ".", "setProp", "(", "EventConstants", ".", "SCHEMA_EVOLUTION_DDLS_NUM", ",", "evolutionDDLs", "==", "null", "?", "0", ":", "evolutionDDLs", ".", "size", "(", ")", ")", ";", "}" ]
Set number of schema evolution DDLs as Sla event metadata
[ "Set", "number", "of", "schema", "evolution", "DDLs", "as", "Sla", "event", "metadata" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/conversion/hive/events/EventWorkunitUtils.java#L75-L77
26,118
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/conversion/hive/events/EventWorkunitUtils.java
EventWorkunitUtils.setIsFirstPublishMetadata
public static void setIsFirstPublishMetadata(WorkUnitState wus) { if (!Boolean.valueOf(wus.getPropAsBoolean(IS_WATERMARK_WORKUNIT_KEY))) { LongWatermark previousWatermark = wus.getWorkunit().getLowWatermark(LongWatermark.class); wus.setProp(SlaEventKeys.IS_FIRST_PUBLISH, (null == previousWatermark || previousWatermark.getValue() == 0)); } }
java
public static void setIsFirstPublishMetadata(WorkUnitState wus) { if (!Boolean.valueOf(wus.getPropAsBoolean(IS_WATERMARK_WORKUNIT_KEY))) { LongWatermark previousWatermark = wus.getWorkunit().getLowWatermark(LongWatermark.class); wus.setProp(SlaEventKeys.IS_FIRST_PUBLISH, (null == previousWatermark || previousWatermark.getValue() == 0)); } }
[ "public", "static", "void", "setIsFirstPublishMetadata", "(", "WorkUnitState", "wus", ")", "{", "if", "(", "!", "Boolean", ".", "valueOf", "(", "wus", ".", "getPropAsBoolean", "(", "IS_WATERMARK_WORKUNIT_KEY", ")", ")", ")", "{", "LongWatermark", "previousWatermark", "=", "wus", ".", "getWorkunit", "(", ")", ".", "getLowWatermark", "(", "LongWatermark", ".", "class", ")", ";", "wus", ".", "setProp", "(", "SlaEventKeys", ".", "IS_FIRST_PUBLISH", ",", "(", "null", "==", "previousWatermark", "||", "previousWatermark", ".", "getValue", "(", ")", "==", "0", ")", ")", ";", "}", "}" ]
Sets metadata to indicate whether this is the first time this table or partition is being published. @param wus to set if this is first publish for this table or partition
[ "Sets", "metadata", "to", "indicate", "whether", "this", "is", "the", "first", "time", "this", "table", "or", "partition", "is", "being", "published", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/conversion/hive/events/EventWorkunitUtils.java#L107-L112
26,119
apache/incubator-gobblin
gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/kafka/serialize/LiAvroDeserializerBase.java
LiAvroDeserializerBase.configure
public void configure(Map<String, ?> configs, boolean isKey) { Preconditions.checkArgument(isKey==false, "LiAvroDeserializer only works for value fields"); _datumReader = new GenericDatumReader<>(); Properties props = new Properties(); for (Map.Entry<String, ?> entry: configs.entrySet()) { String value = String.valueOf(entry.getValue()); props.setProperty(entry.getKey(), value); } _schemaRegistry = KafkaSchemaRegistryFactory.getSchemaRegistry(props); }
java
public void configure(Map<String, ?> configs, boolean isKey) { Preconditions.checkArgument(isKey==false, "LiAvroDeserializer only works for value fields"); _datumReader = new GenericDatumReader<>(); Properties props = new Properties(); for (Map.Entry<String, ?> entry: configs.entrySet()) { String value = String.valueOf(entry.getValue()); props.setProperty(entry.getKey(), value); } _schemaRegistry = KafkaSchemaRegistryFactory.getSchemaRegistry(props); }
[ "public", "void", "configure", "(", "Map", "<", "String", ",", "?", ">", "configs", ",", "boolean", "isKey", ")", "{", "Preconditions", ".", "checkArgument", "(", "isKey", "==", "false", ",", "\"LiAvroDeserializer only works for value fields\"", ")", ";", "_datumReader", "=", "new", "GenericDatumReader", "<>", "(", ")", ";", "Properties", "props", "=", "new", "Properties", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "?", ">", "entry", ":", "configs", ".", "entrySet", "(", ")", ")", "{", "String", "value", "=", "String", ".", "valueOf", "(", "entry", ".", "getValue", "(", ")", ")", ";", "props", ".", "setProperty", "(", "entry", ".", "getKey", "(", ")", ",", "value", ")", ";", "}", "_schemaRegistry", "=", "KafkaSchemaRegistryFactory", ".", "getSchemaRegistry", "(", "props", ")", ";", "}" ]
Configure this class. @param configs configs in key/value pairs @param isKey whether is for key or value
[ "Configure", "this", "class", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/kafka/serialize/LiAvroDeserializerBase.java#L64-L75
26,120
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/replication/CopyRouteGeneratorBase.java
CopyRouteGeneratorBase.getPushRoutes
@Override public Optional<List<CopyRoute>> getPushRoutes(ReplicationConfiguration rc, EndPoint copyFrom) { if (rc.getCopyMode() == ReplicationCopyMode.PULL) return Optional.absent(); DataFlowTopology topology = rc.getDataFlowToplogy(); List<DataFlowTopology.DataFlowPath> paths = topology.getDataFlowPaths(); for (DataFlowTopology.DataFlowPath p : paths) { /** * Routes are list of pairs that generated from config in the format of topology specification. * For example, source:[holdem, war] will end up with * List<(source, holdem), (source, war)> */ List<CopyRoute> routes = p.getCopyRoutes(); if (routes.isEmpty()) { continue; } // All the routes should has the same copyFrom but different copyTo. if (routes.get(0).getCopyFrom().equals(copyFrom)) { return Optional.of(routes); } } return Optional.absent(); }
java
@Override public Optional<List<CopyRoute>> getPushRoutes(ReplicationConfiguration rc, EndPoint copyFrom) { if (rc.getCopyMode() == ReplicationCopyMode.PULL) return Optional.absent(); DataFlowTopology topology = rc.getDataFlowToplogy(); List<DataFlowTopology.DataFlowPath> paths = topology.getDataFlowPaths(); for (DataFlowTopology.DataFlowPath p : paths) { /** * Routes are list of pairs that generated from config in the format of topology specification. * For example, source:[holdem, war] will end up with * List<(source, holdem), (source, war)> */ List<CopyRoute> routes = p.getCopyRoutes(); if (routes.isEmpty()) { continue; } // All the routes should has the same copyFrom but different copyTo. if (routes.get(0).getCopyFrom().equals(copyFrom)) { return Optional.of(routes); } } return Optional.absent(); }
[ "@", "Override", "public", "Optional", "<", "List", "<", "CopyRoute", ">", ">", "getPushRoutes", "(", "ReplicationConfiguration", "rc", ",", "EndPoint", "copyFrom", ")", "{", "if", "(", "rc", ".", "getCopyMode", "(", ")", "==", "ReplicationCopyMode", ".", "PULL", ")", "return", "Optional", ".", "absent", "(", ")", ";", "DataFlowTopology", "topology", "=", "rc", ".", "getDataFlowToplogy", "(", ")", ";", "List", "<", "DataFlowTopology", ".", "DataFlowPath", ">", "paths", "=", "topology", ".", "getDataFlowPaths", "(", ")", ";", "for", "(", "DataFlowTopology", ".", "DataFlowPath", "p", ":", "paths", ")", "{", "/**\n * Routes are list of pairs that generated from config in the format of topology specification.\n * For example, source:[holdem, war] will end up with\n * List<(source, holdem), (source, war)>\n */", "List", "<", "CopyRoute", ">", "routes", "=", "p", ".", "getCopyRoutes", "(", ")", ";", "if", "(", "routes", ".", "isEmpty", "(", ")", ")", "{", "continue", ";", "}", "// All the routes should has the same copyFrom but different copyTo.", "if", "(", "routes", ".", "get", "(", "0", ")", ".", "getCopyFrom", "(", ")", ".", "equals", "(", "copyFrom", ")", ")", "{", "return", "Optional", ".", "of", "(", "routes", ")", ";", "}", "}", "return", "Optional", ".", "absent", "(", ")", ";", "}" ]
for push mode, there is no optimization
[ "for", "push", "mode", "there", "is", "no", "optimization" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/replication/CopyRouteGeneratorBase.java#L39-L65
26,121
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/ClustersNames.java
ClustersNames.normalizeClusterUrl
private static String normalizeClusterUrl(String clusterIdentifier) { try { URI uri = new URI(clusterIdentifier.trim()); // URIs without protocol prefix if (!uri.isOpaque() && null != uri.getHost()) { clusterIdentifier = uri.getHost(); } else { clusterIdentifier = uri.toString().replaceAll("[/:]"," ").trim().replaceAll(" ", "_"); } } catch (URISyntaxException e) { //leave ID as is } return clusterIdentifier; }
java
private static String normalizeClusterUrl(String clusterIdentifier) { try { URI uri = new URI(clusterIdentifier.trim()); // URIs without protocol prefix if (!uri.isOpaque() && null != uri.getHost()) { clusterIdentifier = uri.getHost(); } else { clusterIdentifier = uri.toString().replaceAll("[/:]"," ").trim().replaceAll(" ", "_"); } } catch (URISyntaxException e) { //leave ID as is } return clusterIdentifier; }
[ "private", "static", "String", "normalizeClusterUrl", "(", "String", "clusterIdentifier", ")", "{", "try", "{", "URI", "uri", "=", "new", "URI", "(", "clusterIdentifier", ".", "trim", "(", ")", ")", ";", "// URIs without protocol prefix", "if", "(", "!", "uri", ".", "isOpaque", "(", ")", "&&", "null", "!=", "uri", ".", "getHost", "(", ")", ")", "{", "clusterIdentifier", "=", "uri", ".", "getHost", "(", ")", ";", "}", "else", "{", "clusterIdentifier", "=", "uri", ".", "toString", "(", ")", ".", "replaceAll", "(", "\"[/:]\"", ",", "\" \"", ")", ".", "trim", "(", ")", ".", "replaceAll", "(", "\" \"", ",", "\"_\"", ")", ";", "}", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "//leave ID as is", "}", "return", "clusterIdentifier", ";", "}" ]
Strip out the port number if it is a valid URI
[ "Strip", "out", "the", "port", "number", "if", "it", "is", "a", "valid", "URI" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/ClustersNames.java#L101-L115
26,122
apache/incubator-gobblin
gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-server/src/main/java/org/apache/gobblin/service/FlowConfigsResource.java
FlowConfigsResource.get
@Override public FlowConfig get(ComplexResourceKey<FlowId, EmptyRecord> key) { String flowGroup = key.getKey().getFlowGroup(); String flowName = key.getKey().getFlowName(); FlowId flowId = new FlowId().setFlowGroup(flowGroup).setFlowName(flowName); return this.flowConfigsResourceHandler.getFlowConfig(flowId); }
java
@Override public FlowConfig get(ComplexResourceKey<FlowId, EmptyRecord> key) { String flowGroup = key.getKey().getFlowGroup(); String flowName = key.getKey().getFlowName(); FlowId flowId = new FlowId().setFlowGroup(flowGroup).setFlowName(flowName); return this.flowConfigsResourceHandler.getFlowConfig(flowId); }
[ "@", "Override", "public", "FlowConfig", "get", "(", "ComplexResourceKey", "<", "FlowId", ",", "EmptyRecord", ">", "key", ")", "{", "String", "flowGroup", "=", "key", ".", "getKey", "(", ")", ".", "getFlowGroup", "(", ")", ";", "String", "flowName", "=", "key", ".", "getKey", "(", ")", ".", "getFlowName", "(", ")", ";", "FlowId", "flowId", "=", "new", "FlowId", "(", ")", ".", "setFlowGroup", "(", "flowGroup", ")", ".", "setFlowName", "(", "flowName", ")", ";", "return", "this", ".", "flowConfigsResourceHandler", ".", "getFlowConfig", "(", "flowId", ")", ";", "}" ]
Retrieve the flow configuration with the given key @param key flow config id key containing group name and flow name @return {@link FlowConfig} with flow configuration
[ "Retrieve", "the", "flow", "configuration", "with", "the", "given", "key" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-server/src/main/java/org/apache/gobblin/service/FlowConfigsResource.java#L76-L82
26,123
apache/incubator-gobblin
gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-server/src/main/java/org/apache/gobblin/service/FlowConfigsResource.java
FlowConfigsResource.create
@Override public CreateResponse create(FlowConfig flowConfig) { List<ServiceRequester> requestorList = this.requesterService.findRequesters(this); try { String serialized = this.requesterService.serialize(requestorList); flowConfig.getProperties().put(RequesterService.REQUESTER_LIST, serialized); LOG.info("Rest requester list is " + serialized); } catch (IOException e) { throw new FlowConfigLoggedException(HttpStatus.S_401_UNAUTHORIZED, "cannot get who is the requester", e); } return this.flowConfigsResourceHandler.createFlowConfig(flowConfig); }
java
@Override public CreateResponse create(FlowConfig flowConfig) { List<ServiceRequester> requestorList = this.requesterService.findRequesters(this); try { String serialized = this.requesterService.serialize(requestorList); flowConfig.getProperties().put(RequesterService.REQUESTER_LIST, serialized); LOG.info("Rest requester list is " + serialized); } catch (IOException e) { throw new FlowConfigLoggedException(HttpStatus.S_401_UNAUTHORIZED, "cannot get who is the requester", e); } return this.flowConfigsResourceHandler.createFlowConfig(flowConfig); }
[ "@", "Override", "public", "CreateResponse", "create", "(", "FlowConfig", "flowConfig", ")", "{", "List", "<", "ServiceRequester", ">", "requestorList", "=", "this", ".", "requesterService", ".", "findRequesters", "(", "this", ")", ";", "try", "{", "String", "serialized", "=", "this", ".", "requesterService", ".", "serialize", "(", "requestorList", ")", ";", "flowConfig", ".", "getProperties", "(", ")", ".", "put", "(", "RequesterService", ".", "REQUESTER_LIST", ",", "serialized", ")", ";", "LOG", ".", "info", "(", "\"Rest requester list is \"", "+", "serialized", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "FlowConfigLoggedException", "(", "HttpStatus", ".", "S_401_UNAUTHORIZED", ",", "\"cannot get who is the requester\"", ",", "e", ")", ";", "}", "return", "this", ".", "flowConfigsResourceHandler", ".", "createFlowConfig", "(", "flowConfig", ")", ";", "}" ]
Create a flow configuration that the service will forward to execution instances for execution @param flowConfig flow configuration @return {@link CreateResponse}
[ "Create", "a", "flow", "configuration", "that", "the", "service", "will", "forward", "to", "execution", "instances", "for", "execution" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-server/src/main/java/org/apache/gobblin/service/FlowConfigsResource.java#L89-L102
26,124
apache/incubator-gobblin
gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-server/src/main/java/org/apache/gobblin/service/FlowConfigsResource.java
FlowConfigsResource.update
@Override public UpdateResponse update(ComplexResourceKey<FlowId, EmptyRecord> key, FlowConfig flowConfig) { String flowGroup = key.getKey().getFlowGroup(); String flowName = key.getKey().getFlowName(); FlowId flowId = new FlowId().setFlowGroup(flowGroup).setFlowName(flowName); return this.flowConfigsResourceHandler.updateFlowConfig(flowId, flowConfig); }
java
@Override public UpdateResponse update(ComplexResourceKey<FlowId, EmptyRecord> key, FlowConfig flowConfig) { String flowGroup = key.getKey().getFlowGroup(); String flowName = key.getKey().getFlowName(); FlowId flowId = new FlowId().setFlowGroup(flowGroup).setFlowName(flowName); return this.flowConfigsResourceHandler.updateFlowConfig(flowId, flowConfig); }
[ "@", "Override", "public", "UpdateResponse", "update", "(", "ComplexResourceKey", "<", "FlowId", ",", "EmptyRecord", ">", "key", ",", "FlowConfig", "flowConfig", ")", "{", "String", "flowGroup", "=", "key", ".", "getKey", "(", ")", ".", "getFlowGroup", "(", ")", ";", "String", "flowName", "=", "key", ".", "getKey", "(", ")", ".", "getFlowName", "(", ")", ";", "FlowId", "flowId", "=", "new", "FlowId", "(", ")", ".", "setFlowGroup", "(", "flowGroup", ")", ".", "setFlowName", "(", "flowName", ")", ";", "return", "this", ".", "flowConfigsResourceHandler", ".", "updateFlowConfig", "(", "flowId", ",", "flowConfig", ")", ";", "}" ]
Update the flow configuration with the specified key. Running flows are not affected. An error is raised if the flow configuration does not exist. @param key composite key containing group name and flow name that identifies the flow to update @param flowConfig new flow configuration @return {@link UpdateResponse}
[ "Update", "the", "flow", "configuration", "with", "the", "specified", "key", ".", "Running", "flows", "are", "not", "affected", ".", "An", "error", "is", "raised", "if", "the", "flow", "configuration", "does", "not", "exist", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-server/src/main/java/org/apache/gobblin/service/FlowConfigsResource.java#L111-L117
26,125
apache/incubator-gobblin
gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-server/src/main/java/org/apache/gobblin/service/FlowConfigsResource.java
FlowConfigsResource.delete
@Override public UpdateResponse delete(ComplexResourceKey<FlowId, EmptyRecord> key) { String flowGroup = key.getKey().getFlowGroup(); String flowName = key.getKey().getFlowName(); FlowId flowId = new FlowId().setFlowGroup(flowGroup).setFlowName(flowName); return this.flowConfigsResourceHandler.deleteFlowConfig(flowId, getHeaders()); }
java
@Override public UpdateResponse delete(ComplexResourceKey<FlowId, EmptyRecord> key) { String flowGroup = key.getKey().getFlowGroup(); String flowName = key.getKey().getFlowName(); FlowId flowId = new FlowId().setFlowGroup(flowGroup).setFlowName(flowName); return this.flowConfigsResourceHandler.deleteFlowConfig(flowId, getHeaders()); }
[ "@", "Override", "public", "UpdateResponse", "delete", "(", "ComplexResourceKey", "<", "FlowId", ",", "EmptyRecord", ">", "key", ")", "{", "String", "flowGroup", "=", "key", ".", "getKey", "(", ")", ".", "getFlowGroup", "(", ")", ";", "String", "flowName", "=", "key", ".", "getKey", "(", ")", ".", "getFlowName", "(", ")", ";", "FlowId", "flowId", "=", "new", "FlowId", "(", ")", ".", "setFlowGroup", "(", "flowGroup", ")", ".", "setFlowName", "(", "flowName", ")", ";", "return", "this", ".", "flowConfigsResourceHandler", ".", "deleteFlowConfig", "(", "flowId", ",", "getHeaders", "(", ")", ")", ";", "}" ]
Delete a configured flow. Running flows are not affected. The schedule will be removed for scheduled flows. @param key composite key containing flow group and flow name that identifies the flow to remove from the flow catalog @return {@link UpdateResponse}
[ "Delete", "a", "configured", "flow", ".", "Running", "flows", "are", "not", "affected", ".", "The", "schedule", "will", "be", "removed", "for", "scheduled", "flows", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-server/src/main/java/org/apache/gobblin/service/FlowConfigsResource.java#L124-L130
26,126
apache/incubator-gobblin
gobblin-cluster/src/main/java/org/apache/gobblin/cluster/GobblinClusterManager.java
GobblinClusterManager.initializeAppLauncherAndServices
private void initializeAppLauncherAndServices() throws Exception { // Done to preserve backwards compatibility with the previously hard-coded timeout of 5 minutes Properties properties = ConfigUtils.configToProperties(this.config); if (!properties.contains(ServiceBasedAppLauncher.APP_STOP_TIME_SECONDS)) { properties.setProperty(ServiceBasedAppLauncher.APP_STOP_TIME_SECONDS, Long.toString(300)); } this.applicationLauncher = new ServiceBasedAppLauncher(properties, this.clusterName); // create a job catalog for keeping track of received jobs if a job config path is specified if (this.config.hasPath(GobblinClusterConfigurationKeys.GOBBLIN_CLUSTER_PREFIX + ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY)) { String jobCatalogClassName = ConfigUtils.getString(config, GobblinClusterConfigurationKeys.JOB_CATALOG_KEY, GobblinClusterConfigurationKeys.DEFAULT_JOB_CATALOG); this.jobCatalog = (MutableJobCatalog) GobblinConstructorUtils.invokeFirstConstructor(Class.forName(jobCatalogClassName), ImmutableList.of(config .getConfig(StringUtils.removeEnd(GobblinClusterConfigurationKeys.GOBBLIN_CLUSTER_PREFIX, ".")) .withFallback(this.config))); } else { this.jobCatalog = null; } SchedulerService schedulerService = new SchedulerService(properties); this.applicationLauncher.addService(schedulerService); this.jobScheduler = buildGobblinHelixJobScheduler(config, this.appWorkDir, getMetadataTags(clusterName, applicationId), schedulerService); this.applicationLauncher.addService(this.jobScheduler); this.jobConfigurationManager = buildJobConfigurationManager(config); this.applicationLauncher.addService(this.jobConfigurationManager); }
java
private void initializeAppLauncherAndServices() throws Exception { // Done to preserve backwards compatibility with the previously hard-coded timeout of 5 minutes Properties properties = ConfigUtils.configToProperties(this.config); if (!properties.contains(ServiceBasedAppLauncher.APP_STOP_TIME_SECONDS)) { properties.setProperty(ServiceBasedAppLauncher.APP_STOP_TIME_SECONDS, Long.toString(300)); } this.applicationLauncher = new ServiceBasedAppLauncher(properties, this.clusterName); // create a job catalog for keeping track of received jobs if a job config path is specified if (this.config.hasPath(GobblinClusterConfigurationKeys.GOBBLIN_CLUSTER_PREFIX + ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY)) { String jobCatalogClassName = ConfigUtils.getString(config, GobblinClusterConfigurationKeys.JOB_CATALOG_KEY, GobblinClusterConfigurationKeys.DEFAULT_JOB_CATALOG); this.jobCatalog = (MutableJobCatalog) GobblinConstructorUtils.invokeFirstConstructor(Class.forName(jobCatalogClassName), ImmutableList.of(config .getConfig(StringUtils.removeEnd(GobblinClusterConfigurationKeys.GOBBLIN_CLUSTER_PREFIX, ".")) .withFallback(this.config))); } else { this.jobCatalog = null; } SchedulerService schedulerService = new SchedulerService(properties); this.applicationLauncher.addService(schedulerService); this.jobScheduler = buildGobblinHelixJobScheduler(config, this.appWorkDir, getMetadataTags(clusterName, applicationId), schedulerService); this.applicationLauncher.addService(this.jobScheduler); this.jobConfigurationManager = buildJobConfigurationManager(config); this.applicationLauncher.addService(this.jobConfigurationManager); }
[ "private", "void", "initializeAppLauncherAndServices", "(", ")", "throws", "Exception", "{", "// Done to preserve backwards compatibility with the previously hard-coded timeout of 5 minutes", "Properties", "properties", "=", "ConfigUtils", ".", "configToProperties", "(", "this", ".", "config", ")", ";", "if", "(", "!", "properties", ".", "contains", "(", "ServiceBasedAppLauncher", ".", "APP_STOP_TIME_SECONDS", ")", ")", "{", "properties", ".", "setProperty", "(", "ServiceBasedAppLauncher", ".", "APP_STOP_TIME_SECONDS", ",", "Long", ".", "toString", "(", "300", ")", ")", ";", "}", "this", ".", "applicationLauncher", "=", "new", "ServiceBasedAppLauncher", "(", "properties", ",", "this", ".", "clusterName", ")", ";", "// create a job catalog for keeping track of received jobs if a job config path is specified", "if", "(", "this", ".", "config", ".", "hasPath", "(", "GobblinClusterConfigurationKeys", ".", "GOBBLIN_CLUSTER_PREFIX", "+", "ConfigurationKeys", ".", "JOB_CONFIG_FILE_GENERAL_PATH_KEY", ")", ")", "{", "String", "jobCatalogClassName", "=", "ConfigUtils", ".", "getString", "(", "config", ",", "GobblinClusterConfigurationKeys", ".", "JOB_CATALOG_KEY", ",", "GobblinClusterConfigurationKeys", ".", "DEFAULT_JOB_CATALOG", ")", ";", "this", ".", "jobCatalog", "=", "(", "MutableJobCatalog", ")", "GobblinConstructorUtils", ".", "invokeFirstConstructor", "(", "Class", ".", "forName", "(", "jobCatalogClassName", ")", ",", "ImmutableList", ".", "of", "(", "config", ".", "getConfig", "(", "StringUtils", ".", "removeEnd", "(", "GobblinClusterConfigurationKeys", ".", "GOBBLIN_CLUSTER_PREFIX", ",", "\".\"", ")", ")", ".", "withFallback", "(", "this", ".", "config", ")", ")", ")", ";", "}", "else", "{", "this", ".", "jobCatalog", "=", "null", ";", "}", "SchedulerService", "schedulerService", "=", "new", "SchedulerService", "(", "properties", ")", ";", "this", ".", "applicationLauncher", ".", "addService", "(", "schedulerService", ")", ";", "this", ".", "jobScheduler", "=", "buildGobblinHelixJobScheduler", "(", "config", ",", "this", ".", "appWorkDir", ",", "getMetadataTags", "(", "clusterName", ",", "applicationId", ")", ",", "schedulerService", ")", ";", "this", ".", "applicationLauncher", ".", "addService", "(", "this", ".", "jobScheduler", ")", ";", "this", ".", "jobConfigurationManager", "=", "buildJobConfigurationManager", "(", "config", ")", ";", "this", ".", "applicationLauncher", ".", "addService", "(", "this", ".", "jobConfigurationManager", ")", ";", "}" ]
Create the service based application launcher and other associated services @throws Exception
[ "Create", "the", "service", "based", "application", "launcher", "and", "other", "associated", "services" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-cluster/src/main/java/org/apache/gobblin/cluster/GobblinClusterManager.java#L163-L193
26,127
apache/incubator-gobblin
gobblin-cluster/src/main/java/org/apache/gobblin/cluster/GobblinClusterManager.java
GobblinClusterManager.stopAppLauncherAndServices
private void stopAppLauncherAndServices() { try { this.applicationLauncher.stop(); } catch (ApplicationException ae) { LOGGER.error("Error while stopping Gobblin Cluster application launcher", ae); } if (this.jobCatalog instanceof Service) { ((Service) this.jobCatalog).stopAsync().awaitTerminated(); } }
java
private void stopAppLauncherAndServices() { try { this.applicationLauncher.stop(); } catch (ApplicationException ae) { LOGGER.error("Error while stopping Gobblin Cluster application launcher", ae); } if (this.jobCatalog instanceof Service) { ((Service) this.jobCatalog).stopAsync().awaitTerminated(); } }
[ "private", "void", "stopAppLauncherAndServices", "(", ")", "{", "try", "{", "this", ".", "applicationLauncher", ".", "stop", "(", ")", ";", "}", "catch", "(", "ApplicationException", "ae", ")", "{", "LOGGER", ".", "error", "(", "\"Error while stopping Gobblin Cluster application launcher\"", ",", "ae", ")", ";", "}", "if", "(", "this", ".", "jobCatalog", "instanceof", "Service", ")", "{", "(", "(", "Service", ")", "this", ".", "jobCatalog", ")", ".", "stopAsync", "(", ")", ".", "awaitTerminated", "(", ")", ";", "}", "}" ]
Stop the application launcher then any services that were started outside of the application launcher
[ "Stop", "the", "application", "launcher", "then", "any", "services", "that", "were", "started", "outside", "of", "the", "application", "launcher" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-cluster/src/main/java/org/apache/gobblin/cluster/GobblinClusterManager.java#L211-L221
26,128
apache/incubator-gobblin
gobblin-cluster/src/main/java/org/apache/gobblin/cluster/GobblinClusterManager.java
GobblinClusterManager.start
@Override public synchronized void start() { LOGGER.info("Starting the Gobblin Cluster Manager"); this.eventBus.register(this); this.multiManager.connect(); configureHelixQuotaBasedTaskScheduling(); if (this.isStandaloneMode) { // standalone mode starts non-daemon threads later, so need to have this thread to keep process up this.idleProcessThread = new Thread(new Runnable() { @Override public void run() { while (!GobblinClusterManager.this.stopStatus.isStopInProgress() && !GobblinClusterManager.this.stopIdleProcessThread) { try { Thread.sleep(300); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } } }); this.idleProcessThread.start(); // Need this in case a kill is issued to the process so that the idle thread does not keep the process up // since GobblinClusterManager.stop() is not called this case. Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { GobblinClusterManager.this.stopIdleProcessThread = true; } }); } else { startAppLauncherAndServices(); } }
java
@Override public synchronized void start() { LOGGER.info("Starting the Gobblin Cluster Manager"); this.eventBus.register(this); this.multiManager.connect(); configureHelixQuotaBasedTaskScheduling(); if (this.isStandaloneMode) { // standalone mode starts non-daemon threads later, so need to have this thread to keep process up this.idleProcessThread = new Thread(new Runnable() { @Override public void run() { while (!GobblinClusterManager.this.stopStatus.isStopInProgress() && !GobblinClusterManager.this.stopIdleProcessThread) { try { Thread.sleep(300); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } } }); this.idleProcessThread.start(); // Need this in case a kill is issued to the process so that the idle thread does not keep the process up // since GobblinClusterManager.stop() is not called this case. Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { GobblinClusterManager.this.stopIdleProcessThread = true; } }); } else { startAppLauncherAndServices(); } }
[ "@", "Override", "public", "synchronized", "void", "start", "(", ")", "{", "LOGGER", ".", "info", "(", "\"Starting the Gobblin Cluster Manager\"", ")", ";", "this", ".", "eventBus", ".", "register", "(", "this", ")", ";", "this", ".", "multiManager", ".", "connect", "(", ")", ";", "configureHelixQuotaBasedTaskScheduling", "(", ")", ";", "if", "(", "this", ".", "isStandaloneMode", ")", "{", "// standalone mode starts non-daemon threads later, so need to have this thread to keep process up", "this", ".", "idleProcessThread", "=", "new", "Thread", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "while", "(", "!", "GobblinClusterManager", ".", "this", ".", "stopStatus", ".", "isStopInProgress", "(", ")", "&&", "!", "GobblinClusterManager", ".", "this", ".", "stopIdleProcessThread", ")", "{", "try", "{", "Thread", ".", "sleep", "(", "300", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "break", ";", "}", "}", "}", "}", ")", ";", "this", ".", "idleProcessThread", ".", "start", "(", ")", ";", "// Need this in case a kill is issued to the process so that the idle thread does not keep the process up", "// since GobblinClusterManager.stop() is not called this case.", "Runtime", ".", "getRuntime", "(", ")", ".", "addShutdownHook", "(", "new", "Thread", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "GobblinClusterManager", ".", "this", ".", "stopIdleProcessThread", "=", "true", ";", "}", "}", ")", ";", "}", "else", "{", "startAppLauncherAndServices", "(", ")", ";", "}", "}" ]
Start the Gobblin Cluster Manager.
[ "Start", "the", "Gobblin", "Cluster", "Manager", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-cluster/src/main/java/org/apache/gobblin/cluster/GobblinClusterManager.java#L259-L297
26,129
apache/incubator-gobblin
gobblin-cluster/src/main/java/org/apache/gobblin/cluster/GobblinClusterManager.java
GobblinClusterManager.stop
@Override public synchronized void stop() { if (this.stopStatus.isStopInProgress()) { return; } this.stopStatus.setStopInprogress(true); LOGGER.info("Stopping the Gobblin Cluster Manager"); if (this.idleProcessThread != null) { try { this.idleProcessThread.join(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } // Send a shutdown request to all GobblinTaskRunners unless running in standalone mode. // In standalone mode a failing manager should not stop the whole cluster. if (!this.isStandaloneMode) { sendShutdownRequest(); } stopAppLauncherAndServices(); this.multiManager.disconnect(); }
java
@Override public synchronized void stop() { if (this.stopStatus.isStopInProgress()) { return; } this.stopStatus.setStopInprogress(true); LOGGER.info("Stopping the Gobblin Cluster Manager"); if (this.idleProcessThread != null) { try { this.idleProcessThread.join(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } // Send a shutdown request to all GobblinTaskRunners unless running in standalone mode. // In standalone mode a failing manager should not stop the whole cluster. if (!this.isStandaloneMode) { sendShutdownRequest(); } stopAppLauncherAndServices(); this.multiManager.disconnect(); }
[ "@", "Override", "public", "synchronized", "void", "stop", "(", ")", "{", "if", "(", "this", ".", "stopStatus", ".", "isStopInProgress", "(", ")", ")", "{", "return", ";", "}", "this", ".", "stopStatus", ".", "setStopInprogress", "(", "true", ")", ";", "LOGGER", ".", "info", "(", "\"Stopping the Gobblin Cluster Manager\"", ")", ";", "if", "(", "this", ".", "idleProcessThread", "!=", "null", ")", "{", "try", "{", "this", ".", "idleProcessThread", ".", "join", "(", ")", ";", "}", "catch", "(", "InterruptedException", "ie", ")", "{", "Thread", ".", "currentThread", "(", ")", ".", "interrupt", "(", ")", ";", "}", "}", "// Send a shutdown request to all GobblinTaskRunners unless running in standalone mode.", "// In standalone mode a failing manager should not stop the whole cluster.", "if", "(", "!", "this", ".", "isStandaloneMode", ")", "{", "sendShutdownRequest", "(", ")", ";", "}", "stopAppLauncherAndServices", "(", ")", ";", "this", ".", "multiManager", ".", "disconnect", "(", ")", ";", "}" ]
Stop the Gobblin Cluster Manager.
[ "Stop", "the", "Gobblin", "Cluster", "Manager", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-cluster/src/main/java/org/apache/gobblin/cluster/GobblinClusterManager.java#L302-L329
26,130
apache/incubator-gobblin
gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/kafka/schemareg/LiKafkaSchemaRegistry.java
LiKafkaSchemaRegistry.register
public synchronized MD5Digest register(Schema schema, PostMethod post) throws SchemaRegistryException { // Change namespace if override specified if (this.namespaceOverride.isPresent()) { schema = AvroUtils.switchNamespace(schema, this.namespaceOverride.get()); } LOG.info("Registering schema " + schema.toString()); post.addParameter("schema", schema.toString()); HttpClient httpClient = this.borrowClient(); try { LOG.debug("Loading: " + post.getURI()); int statusCode = httpClient.executeMethod(post); if (statusCode != HttpStatus.SC_CREATED) { throw new SchemaRegistryException("Error occurred while trying to register schema: " + statusCode); } String response; response = post.getResponseBodyAsString(); if (response != null) { LOG.info("Received response " + response); } String schemaKey; Header[] headers = post.getResponseHeaders(SCHEMA_ID_HEADER_NAME); if (headers.length != 1) { throw new SchemaRegistryException( "Error reading schema id returned by registerSchema call: headers.length = " + headers.length); } else if (!headers[0].getValue().startsWith(SCHEMA_ID_HEADER_PREFIX)) { throw new SchemaRegistryException( "Error parsing schema id returned by registerSchema call: header = " + headers[0].getValue()); } else { LOG.info("Registered schema successfully"); schemaKey = headers[0].getValue().substring(SCHEMA_ID_HEADER_PREFIX.length()); } MD5Digest schemaId = MD5Digest.fromString(schemaKey); return schemaId; } catch (Throwable t) { throw new SchemaRegistryException(t); } finally { post.releaseConnection(); this.httpClientPool.returnObject(httpClient); } }
java
public synchronized MD5Digest register(Schema schema, PostMethod post) throws SchemaRegistryException { // Change namespace if override specified if (this.namespaceOverride.isPresent()) { schema = AvroUtils.switchNamespace(schema, this.namespaceOverride.get()); } LOG.info("Registering schema " + schema.toString()); post.addParameter("schema", schema.toString()); HttpClient httpClient = this.borrowClient(); try { LOG.debug("Loading: " + post.getURI()); int statusCode = httpClient.executeMethod(post); if (statusCode != HttpStatus.SC_CREATED) { throw new SchemaRegistryException("Error occurred while trying to register schema: " + statusCode); } String response; response = post.getResponseBodyAsString(); if (response != null) { LOG.info("Received response " + response); } String schemaKey; Header[] headers = post.getResponseHeaders(SCHEMA_ID_HEADER_NAME); if (headers.length != 1) { throw new SchemaRegistryException( "Error reading schema id returned by registerSchema call: headers.length = " + headers.length); } else if (!headers[0].getValue().startsWith(SCHEMA_ID_HEADER_PREFIX)) { throw new SchemaRegistryException( "Error parsing schema id returned by registerSchema call: header = " + headers[0].getValue()); } else { LOG.info("Registered schema successfully"); schemaKey = headers[0].getValue().substring(SCHEMA_ID_HEADER_PREFIX.length()); } MD5Digest schemaId = MD5Digest.fromString(schemaKey); return schemaId; } catch (Throwable t) { throw new SchemaRegistryException(t); } finally { post.releaseConnection(); this.httpClientPool.returnObject(httpClient); } }
[ "public", "synchronized", "MD5Digest", "register", "(", "Schema", "schema", ",", "PostMethod", "post", ")", "throws", "SchemaRegistryException", "{", "// Change namespace if override specified", "if", "(", "this", ".", "namespaceOverride", ".", "isPresent", "(", ")", ")", "{", "schema", "=", "AvroUtils", ".", "switchNamespace", "(", "schema", ",", "this", ".", "namespaceOverride", ".", "get", "(", ")", ")", ";", "}", "LOG", ".", "info", "(", "\"Registering schema \"", "+", "schema", ".", "toString", "(", ")", ")", ";", "post", ".", "addParameter", "(", "\"schema\"", ",", "schema", ".", "toString", "(", ")", ")", ";", "HttpClient", "httpClient", "=", "this", ".", "borrowClient", "(", ")", ";", "try", "{", "LOG", ".", "debug", "(", "\"Loading: \"", "+", "post", ".", "getURI", "(", ")", ")", ";", "int", "statusCode", "=", "httpClient", ".", "executeMethod", "(", "post", ")", ";", "if", "(", "statusCode", "!=", "HttpStatus", ".", "SC_CREATED", ")", "{", "throw", "new", "SchemaRegistryException", "(", "\"Error occurred while trying to register schema: \"", "+", "statusCode", ")", ";", "}", "String", "response", ";", "response", "=", "post", ".", "getResponseBodyAsString", "(", ")", ";", "if", "(", "response", "!=", "null", ")", "{", "LOG", ".", "info", "(", "\"Received response \"", "+", "response", ")", ";", "}", "String", "schemaKey", ";", "Header", "[", "]", "headers", "=", "post", ".", "getResponseHeaders", "(", "SCHEMA_ID_HEADER_NAME", ")", ";", "if", "(", "headers", ".", "length", "!=", "1", ")", "{", "throw", "new", "SchemaRegistryException", "(", "\"Error reading schema id returned by registerSchema call: headers.length = \"", "+", "headers", ".", "length", ")", ";", "}", "else", "if", "(", "!", "headers", "[", "0", "]", ".", "getValue", "(", ")", ".", "startsWith", "(", "SCHEMA_ID_HEADER_PREFIX", ")", ")", "{", "throw", "new", "SchemaRegistryException", "(", "\"Error parsing schema id returned by registerSchema call: header = \"", "+", "headers", "[", "0", "]", ".", "getValue", "(", ")", ")", ";", "}", "else", "{", "LOG", ".", "info", "(", "\"Registered schema successfully\"", ")", ";", "schemaKey", "=", "headers", "[", "0", "]", ".", "getValue", "(", ")", ".", "substring", "(", "SCHEMA_ID_HEADER_PREFIX", ".", "length", "(", ")", ")", ";", "}", "MD5Digest", "schemaId", "=", "MD5Digest", ".", "fromString", "(", "schemaKey", ")", ";", "return", "schemaId", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "throw", "new", "SchemaRegistryException", "(", "t", ")", ";", "}", "finally", "{", "post", ".", "releaseConnection", "(", ")", ";", "this", ".", "httpClientPool", ".", "returnObject", "(", "httpClient", ")", ";", "}", "}" ]
Register a schema to the Kafka schema registry @param schema @param post @return schema ID of the registered schema @throws SchemaRegistryException if registration failed
[ "Register", "a", "schema", "to", "the", "Kafka", "schema", "registry" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/kafka/schemareg/LiKafkaSchemaRegistry.java#L190-L235
26,131
apache/incubator-gobblin
gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-client/src/main/java/org/apache/gobblin/service/FlowConfigClient.java
FlowConfigClient.createFlowConfig
public void createFlowConfig(FlowConfig flowConfig) throws RemoteInvocationException { LOG.debug("createFlowConfig with groupName " + flowConfig.getId().getFlowGroup() + " flowName " + flowConfig.getId().getFlowName()); CreateIdRequest<ComplexResourceKey<FlowId, EmptyRecord>, FlowConfig> request = _flowconfigsRequestBuilders.create().input(flowConfig).build(); ResponseFuture<IdResponse<ComplexResourceKey<FlowId, EmptyRecord>>> flowConfigResponseFuture = _restClient.get().sendRequest(request); flowConfigResponseFuture.getResponse(); }
java
public void createFlowConfig(FlowConfig flowConfig) throws RemoteInvocationException { LOG.debug("createFlowConfig with groupName " + flowConfig.getId().getFlowGroup() + " flowName " + flowConfig.getId().getFlowName()); CreateIdRequest<ComplexResourceKey<FlowId, EmptyRecord>, FlowConfig> request = _flowconfigsRequestBuilders.create().input(flowConfig).build(); ResponseFuture<IdResponse<ComplexResourceKey<FlowId, EmptyRecord>>> flowConfigResponseFuture = _restClient.get().sendRequest(request); flowConfigResponseFuture.getResponse(); }
[ "public", "void", "createFlowConfig", "(", "FlowConfig", "flowConfig", ")", "throws", "RemoteInvocationException", "{", "LOG", ".", "debug", "(", "\"createFlowConfig with groupName \"", "+", "flowConfig", ".", "getId", "(", ")", ".", "getFlowGroup", "(", ")", "+", "\" flowName \"", "+", "flowConfig", ".", "getId", "(", ")", ".", "getFlowName", "(", ")", ")", ";", "CreateIdRequest", "<", "ComplexResourceKey", "<", "FlowId", ",", "EmptyRecord", ">", ",", "FlowConfig", ">", "request", "=", "_flowconfigsRequestBuilders", ".", "create", "(", ")", ".", "input", "(", "flowConfig", ")", ".", "build", "(", ")", ";", "ResponseFuture", "<", "IdResponse", "<", "ComplexResourceKey", "<", "FlowId", ",", "EmptyRecord", ">", ">", ">", "flowConfigResponseFuture", "=", "_restClient", ".", "get", "(", ")", ".", "sendRequest", "(", "request", ")", ";", "flowConfigResponseFuture", ".", "getResponse", "(", ")", ";", "}" ]
Create a flow configuration @param flowConfig flow configuration attributes @throws RemoteInvocationException
[ "Create", "a", "flow", "configuration" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-client/src/main/java/org/apache/gobblin/service/FlowConfigClient.java#L89-L100
26,132
apache/incubator-gobblin
gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-client/src/main/java/org/apache/gobblin/service/FlowConfigClient.java
FlowConfigClient.updateFlowConfig
public void updateFlowConfig(FlowConfig flowConfig) throws RemoteInvocationException { LOG.debug("updateFlowConfig with groupName " + flowConfig.getId().getFlowGroup() + " flowName " + flowConfig.getId().getFlowName()); FlowId flowId = new FlowId().setFlowGroup(flowConfig.getId().getFlowGroup()) .setFlowName(flowConfig.getId().getFlowName()); UpdateRequest<FlowConfig> updateRequest = _flowconfigsRequestBuilders.update().id(new ComplexResourceKey<>(flowId, new EmptyRecord())) .input(flowConfig).build(); ResponseFuture<EmptyRecord> response = _restClient.get().sendRequest(updateRequest); response.getResponse(); }
java
public void updateFlowConfig(FlowConfig flowConfig) throws RemoteInvocationException { LOG.debug("updateFlowConfig with groupName " + flowConfig.getId().getFlowGroup() + " flowName " + flowConfig.getId().getFlowName()); FlowId flowId = new FlowId().setFlowGroup(flowConfig.getId().getFlowGroup()) .setFlowName(flowConfig.getId().getFlowName()); UpdateRequest<FlowConfig> updateRequest = _flowconfigsRequestBuilders.update().id(new ComplexResourceKey<>(flowId, new EmptyRecord())) .input(flowConfig).build(); ResponseFuture<EmptyRecord> response = _restClient.get().sendRequest(updateRequest); response.getResponse(); }
[ "public", "void", "updateFlowConfig", "(", "FlowConfig", "flowConfig", ")", "throws", "RemoteInvocationException", "{", "LOG", ".", "debug", "(", "\"updateFlowConfig with groupName \"", "+", "flowConfig", ".", "getId", "(", ")", ".", "getFlowGroup", "(", ")", "+", "\" flowName \"", "+", "flowConfig", ".", "getId", "(", ")", ".", "getFlowName", "(", ")", ")", ";", "FlowId", "flowId", "=", "new", "FlowId", "(", ")", ".", "setFlowGroup", "(", "flowConfig", ".", "getId", "(", ")", ".", "getFlowGroup", "(", ")", ")", ".", "setFlowName", "(", "flowConfig", ".", "getId", "(", ")", ".", "getFlowName", "(", ")", ")", ";", "UpdateRequest", "<", "FlowConfig", ">", "updateRequest", "=", "_flowconfigsRequestBuilders", ".", "update", "(", ")", ".", "id", "(", "new", "ComplexResourceKey", "<>", "(", "flowId", ",", "new", "EmptyRecord", "(", ")", ")", ")", ".", "input", "(", "flowConfig", ")", ".", "build", "(", ")", ";", "ResponseFuture", "<", "EmptyRecord", ">", "response", "=", "_restClient", ".", "get", "(", ")", ".", "sendRequest", "(", "updateRequest", ")", ";", "response", ".", "getResponse", "(", ")", ";", "}" ]
Update a flow configuration @param flowConfig flow configuration attributes @throws RemoteInvocationException
[ "Update", "a", "flow", "configuration" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-client/src/main/java/org/apache/gobblin/service/FlowConfigClient.java#L107-L122
26,133
apache/incubator-gobblin
gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-client/src/main/java/org/apache/gobblin/service/FlowConfigClient.java
FlowConfigClient.getFlowConfig
public FlowConfig getFlowConfig(FlowId flowId) throws RemoteInvocationException { LOG.debug("getFlowConfig with groupName " + flowId.getFlowGroup() + " flowName " + flowId.getFlowName()); GetRequest<FlowConfig> getRequest = _flowconfigsRequestBuilders.get() .id(new ComplexResourceKey<>(flowId, new EmptyRecord())).build(); Response<FlowConfig> response = _restClient.get().sendRequest(getRequest).getResponse(); return response.getEntity(); }
java
public FlowConfig getFlowConfig(FlowId flowId) throws RemoteInvocationException { LOG.debug("getFlowConfig with groupName " + flowId.getFlowGroup() + " flowName " + flowId.getFlowName()); GetRequest<FlowConfig> getRequest = _flowconfigsRequestBuilders.get() .id(new ComplexResourceKey<>(flowId, new EmptyRecord())).build(); Response<FlowConfig> response = _restClient.get().sendRequest(getRequest).getResponse(); return response.getEntity(); }
[ "public", "FlowConfig", "getFlowConfig", "(", "FlowId", "flowId", ")", "throws", "RemoteInvocationException", "{", "LOG", ".", "debug", "(", "\"getFlowConfig with groupName \"", "+", "flowId", ".", "getFlowGroup", "(", ")", "+", "\" flowName \"", "+", "flowId", ".", "getFlowName", "(", ")", ")", ";", "GetRequest", "<", "FlowConfig", ">", "getRequest", "=", "_flowconfigsRequestBuilders", ".", "get", "(", ")", ".", "id", "(", "new", "ComplexResourceKey", "<>", "(", "flowId", ",", "new", "EmptyRecord", "(", ")", ")", ")", ".", "build", "(", ")", ";", "Response", "<", "FlowConfig", ">", "response", "=", "_restClient", ".", "get", "(", ")", ".", "sendRequest", "(", "getRequest", ")", ".", "getResponse", "(", ")", ";", "return", "response", ".", "getEntity", "(", ")", ";", "}" ]
Get a flow configuration @param flowId identifier of flow configuration to get @return a {@link FlowConfig} with the flow configuration @throws RemoteInvocationException
[ "Get", "a", "flow", "configuration" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-restli/gobblin-flow-config-service/gobblin-flow-config-service-client/src/main/java/org/apache/gobblin/service/FlowConfigClient.java#L130-L141
26,134
apache/incubator-gobblin
gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GitFlowGraphMonitor.java
GitFlowGraphMonitor.checkFileLevelRelativeToRoot
private boolean checkFileLevelRelativeToRoot(Path filePath, int depth) { if (filePath == null) { return false; } Path path = filePath; for (int i = 0; i < depth - 1; i++) { path = path.getParent(); } if (!path.getName().equals(folderName)) { return false; } return true; }
java
private boolean checkFileLevelRelativeToRoot(Path filePath, int depth) { if (filePath == null) { return false; } Path path = filePath; for (int i = 0; i < depth - 1; i++) { path = path.getParent(); } if (!path.getName().equals(folderName)) { return false; } return true; }
[ "private", "boolean", "checkFileLevelRelativeToRoot", "(", "Path", "filePath", ",", "int", "depth", ")", "{", "if", "(", "filePath", "==", "null", ")", "{", "return", "false", ";", "}", "Path", "path", "=", "filePath", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "depth", "-", "1", ";", "i", "++", ")", "{", "path", "=", "path", ".", "getParent", "(", ")", ";", "}", "if", "(", "!", "path", ".", "getName", "(", ")", ".", "equals", "(", "folderName", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Helper to check if a file has proper hierarchy. @param filePath path of the node/edge file @param depth expected depth of the file @return true if the file conforms to the expected hierarchy
[ "Helper", "to", "check", "if", "a", "file", "has", "proper", "hierarchy", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GitFlowGraphMonitor.java#L293-L305
26,135
apache/incubator-gobblin
gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GitFlowGraphMonitor.java
GitFlowGraphMonitor.getNodeConfigWithOverrides
private Config getNodeConfigWithOverrides(Config nodeConfig, Path nodeFilePath) { String nodeId = nodeFilePath.getParent().getName(); return nodeConfig.withValue(FlowGraphConfigurationKeys.DATA_NODE_ID_KEY, ConfigValueFactory.fromAnyRef(nodeId)); }
java
private Config getNodeConfigWithOverrides(Config nodeConfig, Path nodeFilePath) { String nodeId = nodeFilePath.getParent().getName(); return nodeConfig.withValue(FlowGraphConfigurationKeys.DATA_NODE_ID_KEY, ConfigValueFactory.fromAnyRef(nodeId)); }
[ "private", "Config", "getNodeConfigWithOverrides", "(", "Config", "nodeConfig", ",", "Path", "nodeFilePath", ")", "{", "String", "nodeId", "=", "nodeFilePath", ".", "getParent", "(", ")", ".", "getName", "(", ")", ";", "return", "nodeConfig", ".", "withValue", "(", "FlowGraphConfigurationKeys", ".", "DATA_NODE_ID_KEY", ",", "ConfigValueFactory", ".", "fromAnyRef", "(", "nodeId", ")", ")", ";", "}" ]
Helper that overrides the data.node.id property with name derived from the node file path @param nodeConfig node config @param nodeFilePath path of the node file @return config with overridden data.node.id
[ "Helper", "that", "overrides", "the", "data", ".", "node", ".", "id", "property", "with", "name", "derived", "from", "the", "node", "file", "path" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GitFlowGraphMonitor.java#L313-L316
26,136
apache/incubator-gobblin
gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GitFlowGraphMonitor.java
GitFlowGraphMonitor.getEdgeConfigWithOverrides
private Config getEdgeConfigWithOverrides(Config edgeConfig, Path edgeFilePath) { String source = edgeFilePath.getParent().getParent().getName(); String destination = edgeFilePath.getParent().getName(); String edgeName = Files.getNameWithoutExtension(edgeFilePath.getName()); return edgeConfig.withValue(FlowGraphConfigurationKeys.FLOW_EDGE_SOURCE_KEY, ConfigValueFactory.fromAnyRef(source)) .withValue(FlowGraphConfigurationKeys.FLOW_EDGE_DESTINATION_KEY, ConfigValueFactory.fromAnyRef(destination)) .withValue(FlowGraphConfigurationKeys.FLOW_EDGE_ID_KEY, ConfigValueFactory.fromAnyRef(getEdgeId(source, destination, edgeName))); }
java
private Config getEdgeConfigWithOverrides(Config edgeConfig, Path edgeFilePath) { String source = edgeFilePath.getParent().getParent().getName(); String destination = edgeFilePath.getParent().getName(); String edgeName = Files.getNameWithoutExtension(edgeFilePath.getName()); return edgeConfig.withValue(FlowGraphConfigurationKeys.FLOW_EDGE_SOURCE_KEY, ConfigValueFactory.fromAnyRef(source)) .withValue(FlowGraphConfigurationKeys.FLOW_EDGE_DESTINATION_KEY, ConfigValueFactory.fromAnyRef(destination)) .withValue(FlowGraphConfigurationKeys.FLOW_EDGE_ID_KEY, ConfigValueFactory.fromAnyRef(getEdgeId(source, destination, edgeName))); }
[ "private", "Config", "getEdgeConfigWithOverrides", "(", "Config", "edgeConfig", ",", "Path", "edgeFilePath", ")", "{", "String", "source", "=", "edgeFilePath", ".", "getParent", "(", ")", ".", "getParent", "(", ")", ".", "getName", "(", ")", ";", "String", "destination", "=", "edgeFilePath", ".", "getParent", "(", ")", ".", "getName", "(", ")", ";", "String", "edgeName", "=", "Files", ".", "getNameWithoutExtension", "(", "edgeFilePath", ".", "getName", "(", ")", ")", ";", "return", "edgeConfig", ".", "withValue", "(", "FlowGraphConfigurationKeys", ".", "FLOW_EDGE_SOURCE_KEY", ",", "ConfigValueFactory", ".", "fromAnyRef", "(", "source", ")", ")", ".", "withValue", "(", "FlowGraphConfigurationKeys", ".", "FLOW_EDGE_DESTINATION_KEY", ",", "ConfigValueFactory", ".", "fromAnyRef", "(", "destination", ")", ")", ".", "withValue", "(", "FlowGraphConfigurationKeys", ".", "FLOW_EDGE_ID_KEY", ",", "ConfigValueFactory", ".", "fromAnyRef", "(", "getEdgeId", "(", "source", ",", "destination", ",", "edgeName", ")", ")", ")", ";", "}" ]
Helper that overrides the flow edge properties with name derived from the edge file path @param edgeConfig edge config @param edgeFilePath path of the edge file @return config with overridden edge properties
[ "Helper", "that", "overrides", "the", "flow", "edge", "properties", "with", "name", "derived", "from", "the", "edge", "file", "path" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GitFlowGraphMonitor.java#L324-L332
26,137
apache/incubator-gobblin
gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GitFlowGraphMonitor.java
GitFlowGraphMonitor.loadNodeFileWithOverrides
private Config loadNodeFileWithOverrides(Path filePath) throws IOException { Config nodeConfig = this.pullFileLoader.loadPullFile(filePath, emptyConfig, false); return getNodeConfigWithOverrides(nodeConfig, filePath); }
java
private Config loadNodeFileWithOverrides(Path filePath) throws IOException { Config nodeConfig = this.pullFileLoader.loadPullFile(filePath, emptyConfig, false); return getNodeConfigWithOverrides(nodeConfig, filePath); }
[ "private", "Config", "loadNodeFileWithOverrides", "(", "Path", "filePath", ")", "throws", "IOException", "{", "Config", "nodeConfig", "=", "this", ".", "pullFileLoader", ".", "loadPullFile", "(", "filePath", ",", "emptyConfig", ",", "false", ")", ";", "return", "getNodeConfigWithOverrides", "(", "nodeConfig", ",", "filePath", ")", ";", "}" ]
Load the node file. @param filePath path of the node file relative to the repository root @return the configuration object @throws IOException
[ "Load", "the", "node", "file", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GitFlowGraphMonitor.java#L359-L362
26,138
apache/incubator-gobblin
gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GitFlowGraphMonitor.java
GitFlowGraphMonitor.loadEdgeFileWithOverrides
private Config loadEdgeFileWithOverrides(Path filePath) throws IOException { Config edgeConfig = this.pullFileLoader.loadPullFile(filePath, emptyConfig, false); return getEdgeConfigWithOverrides(edgeConfig, filePath); }
java
private Config loadEdgeFileWithOverrides(Path filePath) throws IOException { Config edgeConfig = this.pullFileLoader.loadPullFile(filePath, emptyConfig, false); return getEdgeConfigWithOverrides(edgeConfig, filePath); }
[ "private", "Config", "loadEdgeFileWithOverrides", "(", "Path", "filePath", ")", "throws", "IOException", "{", "Config", "edgeConfig", "=", "this", ".", "pullFileLoader", ".", "loadPullFile", "(", "filePath", ",", "emptyConfig", ",", "false", ")", ";", "return", "getEdgeConfigWithOverrides", "(", "edgeConfig", ",", "filePath", ")", ";", "}" ]
Load the edge file. @param filePath path of the edge file relative to the repository root @return the configuration object @throws IOException
[ "Load", "the", "edge", "file", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GitFlowGraphMonitor.java#L370-L373
26,139
apache/incubator-gobblin
gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GitFlowGraphMonitor.java
GitFlowGraphMonitor.getEdgeId
private String getEdgeId(String source, String destination, String edgeName) { return Joiner.on(FLOW_EDGE_LABEL_JOINER_CHAR).join(source, destination, edgeName); }
java
private String getEdgeId(String source, String destination, String edgeName) { return Joiner.on(FLOW_EDGE_LABEL_JOINER_CHAR).join(source, destination, edgeName); }
[ "private", "String", "getEdgeId", "(", "String", "source", ",", "String", "destination", ",", "String", "edgeName", ")", "{", "return", "Joiner", ".", "on", "(", "FLOW_EDGE_LABEL_JOINER_CHAR", ")", ".", "join", "(", "source", ",", "destination", ",", "edgeName", ")", ";", "}" ]
Get an edge label from the edge properties @param source source data node id @param destination destination data node id @param edgeName simple name of the edge (e.g. file name without extension of the edge file) @return a string label identifying the edge
[ "Get", "an", "edge", "label", "from", "the", "edge", "properties" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GitFlowGraphMonitor.java#L382-L384
26,140
apache/incubator-gobblin
gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/writer/commands/BaseJdbcBufferedInserter.java
BaseJdbcBufferedInserter.initializeBatch
protected void initializeBatch(String databaseName, String table) throws SQLException { this.insertStmtPrefix = createInsertStatementStr(databaseName, table); this.insertPstmtForFixedBatch = this.conn.prepareStatement(createPrepareStatementStr(this.batchSize)); LOG.info(String.format("Initialized for %s insert " + this, (this.batchSize > 1) ? "batch" : "")); }
java
protected void initializeBatch(String databaseName, String table) throws SQLException { this.insertStmtPrefix = createInsertStatementStr(databaseName, table); this.insertPstmtForFixedBatch = this.conn.prepareStatement(createPrepareStatementStr(this.batchSize)); LOG.info(String.format("Initialized for %s insert " + this, (this.batchSize > 1) ? "batch" : "")); }
[ "protected", "void", "initializeBatch", "(", "String", "databaseName", ",", "String", "table", ")", "throws", "SQLException", "{", "this", ".", "insertStmtPrefix", "=", "createInsertStatementStr", "(", "databaseName", ",", "table", ")", ";", "this", ".", "insertPstmtForFixedBatch", "=", "this", ".", "conn", ".", "prepareStatement", "(", "createPrepareStatementStr", "(", "this", ".", "batchSize", ")", ")", ";", "LOG", ".", "info", "(", "String", ".", "format", "(", "\"Initialized for %s insert \"", "+", "this", ",", "(", "this", ".", "batchSize", ">", "1", ")", "?", "\"batch\"", ":", "\"\"", ")", ")", ";", "}" ]
Initializes variables for batch insert and pre-compute PreparedStatement based on requested batch size and parameter size. @param databaseName @param table @throws SQLException
[ "Initializes", "variables", "for", "batch", "insert", "and", "pre", "-", "compute", "PreparedStatement", "based", "on", "requested", "batch", "size", "and", "parameter", "size", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/writer/commands/BaseJdbcBufferedInserter.java#L132-L138
26,141
apache/incubator-gobblin
gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/writer/commands/BaseJdbcBufferedInserter.java
BaseJdbcBufferedInserter.createInsertStatementStr
protected String createInsertStatementStr(String databaseName, String table) { return String.format(INSERT_STATEMENT_PREFIX_FORMAT, databaseName, table, JOINER_ON_COMMA.join(this.columnNames)); }
java
protected String createInsertStatementStr(String databaseName, String table) { return String.format(INSERT_STATEMENT_PREFIX_FORMAT, databaseName, table, JOINER_ON_COMMA.join(this.columnNames)); }
[ "protected", "String", "createInsertStatementStr", "(", "String", "databaseName", ",", "String", "table", ")", "{", "return", "String", ".", "format", "(", "INSERT_STATEMENT_PREFIX_FORMAT", ",", "databaseName", ",", "table", ",", "JOINER_ON_COMMA", ".", "join", "(", "this", ".", "columnNames", ")", ")", ";", "}" ]
Populates the placeholders and constructs the prefix of batch insert statement @param databaseName name of the database @param table name of the table @return {@link #INSERT_STATEMENT_PREFIX_FORMAT} with all its resolved placeholders
[ "Populates", "the", "placeholders", "and", "constructs", "the", "prefix", "of", "batch", "insert", "statement" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/writer/commands/BaseJdbcBufferedInserter.java#L175-L177
26,142
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/PullFileLoader.java
PullFileLoader.loadPullFile
public Config loadPullFile(Path path, Config sysProps, boolean loadGlobalProperties) throws IOException { Config fallback = loadGlobalProperties ? loadAncestorGlobalConfigs(path, sysProps) : sysProps; if (this.javaPropsPullFileFilter.accept(path)) { return loadJavaPropsWithFallback(path, fallback).resolve(); } else if (this.hoconPullFileFilter.accept(path)) { return loadHoconConfigAtPath(path).withFallback(fallback).resolve(); } else { throw new IOException(String.format("Cannot load pull file %s due to unrecognized extension.", path)); } }
java
public Config loadPullFile(Path path, Config sysProps, boolean loadGlobalProperties) throws IOException { Config fallback = loadGlobalProperties ? loadAncestorGlobalConfigs(path, sysProps) : sysProps; if (this.javaPropsPullFileFilter.accept(path)) { return loadJavaPropsWithFallback(path, fallback).resolve(); } else if (this.hoconPullFileFilter.accept(path)) { return loadHoconConfigAtPath(path).withFallback(fallback).resolve(); } else { throw new IOException(String.format("Cannot load pull file %s due to unrecognized extension.", path)); } }
[ "public", "Config", "loadPullFile", "(", "Path", "path", ",", "Config", "sysProps", ",", "boolean", "loadGlobalProperties", ")", "throws", "IOException", "{", "Config", "fallback", "=", "loadGlobalProperties", "?", "loadAncestorGlobalConfigs", "(", "path", ",", "sysProps", ")", ":", "sysProps", ";", "if", "(", "this", ".", "javaPropsPullFileFilter", ".", "accept", "(", "path", ")", ")", "{", "return", "loadJavaPropsWithFallback", "(", "path", ",", "fallback", ")", ".", "resolve", "(", ")", ";", "}", "else", "if", "(", "this", ".", "hoconPullFileFilter", ".", "accept", "(", "path", ")", ")", "{", "return", "loadHoconConfigAtPath", "(", "path", ")", ".", "withFallback", "(", "fallback", ")", ".", "resolve", "(", ")", ";", "}", "else", "{", "throw", "new", "IOException", "(", "String", ".", "format", "(", "\"Cannot load pull file %s due to unrecognized extension.\"", ",", "path", ")", ")", ";", "}", "}" ]
Load a single pull file. @param path The {@link Path} to the pull file to load, full path @param sysProps A {@link Config} used as fallback. @param loadGlobalProperties if true, will also load at most one *.properties file per directory from the {@link #rootDirectory} to the pull file {@link Path}. @return The loaded {@link Config}. @throws IOException
[ "Load", "a", "single", "pull", "file", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/PullFileLoader.java#L140-L150
26,143
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/writer/http/AbstractHttpWriter.java
AbstractHttpWriter.waitForResponse
@Override public CloseableHttpResponse waitForResponse(ListenableFuture<CloseableHttpResponse> responseFuture) { try { return responseFuture.get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } }
java
@Override public CloseableHttpResponse waitForResponse(ListenableFuture<CloseableHttpResponse> responseFuture) { try { return responseFuture.get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } }
[ "@", "Override", "public", "CloseableHttpResponse", "waitForResponse", "(", "ListenableFuture", "<", "CloseableHttpResponse", ">", "responseFuture", ")", "{", "try", "{", "return", "responseFuture", ".", "get", "(", ")", ";", "}", "catch", "(", "InterruptedException", "|", "ExecutionException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Default implementation is to use HttpClients socket timeout which is waiting based on elapsed time between last packet sent from client till receive it from server. {@inheritDoc} @see org.apache.gobblin.writer.http.HttpWriterDecoration#waitForResponse(com.google.common.util.concurrent.ListenableFuture)
[ "Default", "implementation", "is", "to", "use", "HttpClients", "socket", "timeout", "which", "is", "waiting", "based", "on", "elapsed", "time", "between", "last", "packet", "sent", "from", "client", "till", "receive", "it", "from", "server", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/writer/http/AbstractHttpWriter.java#L204-L211
26,144
apache/incubator-gobblin
gobblin-modules/google-ingestion/src/main/java/org/apache/gobblin/source/extractor/extract/google/GoogleDriveSource.java
GoogleDriveSource.getcurrentFsSnapshot
@Override public List<String> getcurrentFsSnapshot(State state) { List<String> results = new ArrayList<>(); String folderId = state.getProp(SOURCE_FILEBASED_DATA_DIRECTORY, ""); try { LOG.info("Running ls with folderId: " + folderId); List<String> fileIds = this.fsHelper.ls(folderId); for (String fileId : fileIds) { results.add(fileId + splitPattern + this.fsHelper.getFileMTime(fileId)); } } catch (FileBasedHelperException e) { throw new RuntimeException("Failed to retrieve list of file IDs for folderID: " + folderId, e); } return results; }
java
@Override public List<String> getcurrentFsSnapshot(State state) { List<String> results = new ArrayList<>(); String folderId = state.getProp(SOURCE_FILEBASED_DATA_DIRECTORY, ""); try { LOG.info("Running ls with folderId: " + folderId); List<String> fileIds = this.fsHelper.ls(folderId); for (String fileId : fileIds) { results.add(fileId + splitPattern + this.fsHelper.getFileMTime(fileId)); } } catch (FileBasedHelperException e) { throw new RuntimeException("Failed to retrieve list of file IDs for folderID: " + folderId, e); } return results; }
[ "@", "Override", "public", "List", "<", "String", ">", "getcurrentFsSnapshot", "(", "State", "state", ")", "{", "List", "<", "String", ">", "results", "=", "new", "ArrayList", "<>", "(", ")", ";", "String", "folderId", "=", "state", ".", "getProp", "(", "SOURCE_FILEBASED_DATA_DIRECTORY", ",", "\"\"", ")", ";", "try", "{", "LOG", ".", "info", "(", "\"Running ls with folderId: \"", "+", "folderId", ")", ";", "List", "<", "String", ">", "fileIds", "=", "this", ".", "fsHelper", ".", "ls", "(", "folderId", ")", ";", "for", "(", "String", "fileId", ":", "fileIds", ")", "{", "results", ".", "add", "(", "fileId", "+", "splitPattern", "+", "this", ".", "fsHelper", ".", "getFileMTime", "(", "fileId", ")", ")", ";", "}", "}", "catch", "(", "FileBasedHelperException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Failed to retrieve list of file IDs for folderID: \"", "+", "folderId", ",", "e", ")", ";", "}", "return", "results", ";", "}" ]
Provide list of files snapshot where snap shot is consist of list of file ID with modified time. Folder ID and file ID are all optional where missing folder id represent search from root folder where missing file ID represents all files will be included on current and subfolder. {@inheritDoc} @see org.apache.gobblin.source.extractor.filebased.FileBasedSource#getcurrentFsSnapshot(org.apache.gobblin.configuration.State)
[ "Provide", "list", "of", "files", "snapshot", "where", "snap", "shot", "is", "consist", "of", "list", "of", "file", "ID", "with", "modified", "time", ".", "Folder", "ID", "and", "file", "ID", "are", "all", "optional", "where", "missing", "folder", "id", "represent", "search", "from", "root", "folder", "where", "missing", "file", "ID", "represents", "all", "files", "will", "be", "included", "on", "current", "and", "subfolder", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/google-ingestion/src/main/java/org/apache/gobblin/source/extractor/extract/google/GoogleDriveSource.java#L104-L120
26,145
apache/incubator-gobblin
gobblin-core-base/src/main/java/org/apache/gobblin/writer/Batch.java
Batch.onSuccess
public void onSuccess (final WriteResponse response) { for (final Thunk thunk: this.thunks) { thunk.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
public void onSuccess (final WriteResponse response) { for (final Thunk thunk: this.thunks) { thunk.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; } }); } }
[ "public", "void", "onSuccess", "(", "final", "WriteResponse", "response", ")", "{", "for", "(", "final", "Thunk", "thunk", ":", "this", ".", "thunks", ")", "{", "thunk", ".", "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", ";", "}", "}", ")", ";", "}", "}" ]
After batch is sent and get acknowledged successfully, this method will be invoked
[ "After", "batch", "is", "sent", "and", "get", "acknowledged", "successfully", "this", "method", "will", "be", "invoked" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core-base/src/main/java/org/apache/gobblin/writer/Batch.java#L87-L106
26,146
apache/incubator-gobblin
gobblin-core-base/src/main/java/org/apache/gobblin/writer/Batch.java
Batch.onFailure
public void onFailure (Throwable throwable) { for (Thunk thunk: this.thunks) { thunk.callback.onFailure(throwable); } }
java
public void onFailure (Throwable throwable) { for (Thunk thunk: this.thunks) { thunk.callback.onFailure(throwable); } }
[ "public", "void", "onFailure", "(", "Throwable", "throwable", ")", "{", "for", "(", "Thunk", "thunk", ":", "this", ".", "thunks", ")", "{", "thunk", ".", "callback", ".", "onFailure", "(", "throwable", ")", ";", "}", "}" ]
When batch is sent with an error return, this method will be invoked
[ "When", "batch", "is", "sent", "with", "an", "error", "return", "this", "method", "will", "be", "invoked" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core-base/src/main/java/org/apache/gobblin/writer/Batch.java#L111-L115
26,147
apache/incubator-gobblin
gobblin-core-base/src/main/java/org/apache/gobblin/writer/BatchAccumulator.java
BatchAccumulator.close
public void close () { closed = true; while (appendsInProgress.get() > 0) { LOG.info("Append is still going on, wait for a while"); try { Thread.sleep(100); } catch (InterruptedException e) { LOG.error("close is interrupted while appending data is in progress"); } } this.closeComplete.countDown(); }
java
public void close () { closed = true; while (appendsInProgress.get() > 0) { LOG.info("Append is still going on, wait for a while"); try { Thread.sleep(100); } catch (InterruptedException e) { LOG.error("close is interrupted while appending data is in progress"); } } this.closeComplete.countDown(); }
[ "public", "void", "close", "(", ")", "{", "closed", "=", "true", ";", "while", "(", "appendsInProgress", ".", "get", "(", ")", ">", "0", ")", "{", "LOG", ".", "info", "(", "\"Append is still going on, wait for a while\"", ")", ";", "try", "{", "Thread", ".", "sleep", "(", "100", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "LOG", ".", "error", "(", "\"close is interrupted while appending data is in progress\"", ")", ";", "}", "}", "this", ".", "closeComplete", ".", "countDown", "(", ")", ";", "}" ]
When close is invoked, all new coming records will be rejected Add a busy loop here to ensure all the ongoing appends are completed
[ "When", "close", "is", "invoked", "all", "new", "coming", "records", "will", "be", "rejected", "Add", "a", "busy", "loop", "here", "to", "ensure", "all", "the", "ongoing", "appends", "are", "completed" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core-base/src/main/java/org/apache/gobblin/writer/BatchAccumulator.java#L111-L122
26,148
apache/incubator-gobblin
gobblin-compaction/src/main/java/org/apache/gobblin/compaction/mapreduce/MRCompactor.java
MRCompactor.copyDependencyJarsToHdfs
private void copyDependencyJarsToHdfs() throws IOException { if (!this.state.contains(ConfigurationKeys.JOB_JAR_FILES_KEY)) { return; } LocalFileSystem lfs = FileSystem.getLocal(this.conf); Path tmpJarFileDir = new Path(this.tmpOutputDir, "_gobblin_compaction_jars"); this.state.setProp(COMPACTION_JARS, tmpJarFileDir.toString()); this.fs.delete(tmpJarFileDir, true); for (String jarFile : this.state.getPropAsList(ConfigurationKeys.JOB_JAR_FILES_KEY)) { for (FileStatus status : lfs.globStatus(new Path(jarFile))) { Path tmpJarFile = new Path(this.fs.makeQualified(tmpJarFileDir), status.getPath().getName()); this.fs.copyFromLocalFile(status.getPath(), tmpJarFile); LOG.info(String.format("%s will be added to classpath", tmpJarFile)); } } }
java
private void copyDependencyJarsToHdfs() throws IOException { if (!this.state.contains(ConfigurationKeys.JOB_JAR_FILES_KEY)) { return; } LocalFileSystem lfs = FileSystem.getLocal(this.conf); Path tmpJarFileDir = new Path(this.tmpOutputDir, "_gobblin_compaction_jars"); this.state.setProp(COMPACTION_JARS, tmpJarFileDir.toString()); this.fs.delete(tmpJarFileDir, true); for (String jarFile : this.state.getPropAsList(ConfigurationKeys.JOB_JAR_FILES_KEY)) { for (FileStatus status : lfs.globStatus(new Path(jarFile))) { Path tmpJarFile = new Path(this.fs.makeQualified(tmpJarFileDir), status.getPath().getName()); this.fs.copyFromLocalFile(status.getPath(), tmpJarFile); LOG.info(String.format("%s will be added to classpath", tmpJarFile)); } } }
[ "private", "void", "copyDependencyJarsToHdfs", "(", ")", "throws", "IOException", "{", "if", "(", "!", "this", ".", "state", ".", "contains", "(", "ConfigurationKeys", ".", "JOB_JAR_FILES_KEY", ")", ")", "{", "return", ";", "}", "LocalFileSystem", "lfs", "=", "FileSystem", ".", "getLocal", "(", "this", ".", "conf", ")", ";", "Path", "tmpJarFileDir", "=", "new", "Path", "(", "this", ".", "tmpOutputDir", ",", "\"_gobblin_compaction_jars\"", ")", ";", "this", ".", "state", ".", "setProp", "(", "COMPACTION_JARS", ",", "tmpJarFileDir", ".", "toString", "(", ")", ")", ";", "this", ".", "fs", ".", "delete", "(", "tmpJarFileDir", ",", "true", ")", ";", "for", "(", "String", "jarFile", ":", "this", ".", "state", ".", "getPropAsList", "(", "ConfigurationKeys", ".", "JOB_JAR_FILES_KEY", ")", ")", "{", "for", "(", "FileStatus", "status", ":", "lfs", ".", "globStatus", "(", "new", "Path", "(", "jarFile", ")", ")", ")", "{", "Path", "tmpJarFile", "=", "new", "Path", "(", "this", ".", "fs", ".", "makeQualified", "(", "tmpJarFileDir", ")", ",", "status", ".", "getPath", "(", ")", ".", "getName", "(", ")", ")", ";", "this", ".", "fs", ".", "copyFromLocalFile", "(", "status", ".", "getPath", "(", ")", ",", "tmpJarFile", ")", ";", "LOG", ".", "info", "(", "String", ".", "format", "(", "\"%s will be added to classpath\"", ",", "tmpJarFile", ")", ")", ";", "}", "}", "}" ]
Copy dependency jars from local fs to HDFS.
[ "Copy", "dependency", "jars", "from", "local", "fs", "to", "HDFS", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-compaction/src/main/java/org/apache/gobblin/compaction/mapreduce/MRCompactor.java#L416-L431
26,149
apache/incubator-gobblin
gobblin-compaction/src/main/java/org/apache/gobblin/compaction/mapreduce/MRCompactor.java
MRCompactor.deleteDependencyJars
private void deleteDependencyJars() throws IllegalArgumentException, IOException { if (this.state.contains(COMPACTION_JARS)) { this.fs.delete(new Path(this.state.getProp(COMPACTION_JARS)), true); } }
java
private void deleteDependencyJars() throws IllegalArgumentException, IOException { if (this.state.contains(COMPACTION_JARS)) { this.fs.delete(new Path(this.state.getProp(COMPACTION_JARS)), true); } }
[ "private", "void", "deleteDependencyJars", "(", ")", "throws", "IllegalArgumentException", ",", "IOException", "{", "if", "(", "this", ".", "state", ".", "contains", "(", "COMPACTION_JARS", ")", ")", "{", "this", ".", "fs", ".", "delete", "(", "new", "Path", "(", "this", ".", "state", ".", "getProp", "(", "COMPACTION_JARS", ")", ")", ",", "true", ")", ";", "}", "}" ]
Delete dependency jars from HDFS when job is done.
[ "Delete", "dependency", "jars", "from", "HDFS", "when", "job", "is", "done", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-compaction/src/main/java/org/apache/gobblin/compaction/mapreduce/MRCompactor.java#L436-L440
26,150
apache/incubator-gobblin
gobblin-compaction/src/main/java/org/apache/gobblin/compaction/mapreduce/MRCompactor.java
MRCompactor.renameSourceDirAsCompactionComplete
public static void renameSourceDirAsCompactionComplete (FileSystem fs, Dataset dataset) { try { for (Path path: dataset.getRenamePaths()) { Path newPath = new Path (path.getParent(), path.getName() + MRCompactor.COMPACTION_RENAME_SOURCE_DIR_SUFFIX); LOG.info("[{}] Renaming {} to {}", dataset.getDatasetName(), path, newPath); fs.rename(path, newPath); } } catch (Exception e) { LOG.error ("Rename input path failed", e); } }
java
public static void renameSourceDirAsCompactionComplete (FileSystem fs, Dataset dataset) { try { for (Path path: dataset.getRenamePaths()) { Path newPath = new Path (path.getParent(), path.getName() + MRCompactor.COMPACTION_RENAME_SOURCE_DIR_SUFFIX); LOG.info("[{}] Renaming {} to {}", dataset.getDatasetName(), path, newPath); fs.rename(path, newPath); } } catch (Exception e) { LOG.error ("Rename input path failed", e); } }
[ "public", "static", "void", "renameSourceDirAsCompactionComplete", "(", "FileSystem", "fs", ",", "Dataset", "dataset", ")", "{", "try", "{", "for", "(", "Path", "path", ":", "dataset", ".", "getRenamePaths", "(", ")", ")", "{", "Path", "newPath", "=", "new", "Path", "(", "path", ".", "getParent", "(", ")", ",", "path", ".", "getName", "(", ")", "+", "MRCompactor", ".", "COMPACTION_RENAME_SOURCE_DIR_SUFFIX", ")", ";", "LOG", ".", "info", "(", "\"[{}] Renaming {} to {}\"", ",", "dataset", ".", "getDatasetName", "(", ")", ",", "path", ",", "newPath", ")", ";", "fs", ".", "rename", "(", "path", ",", "newPath", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "error", "(", "\"Rename input path failed\"", ",", "e", ")", ";", "}", "}" ]
Rename all the source directories for a specific dataset
[ "Rename", "all", "the", "source", "directories", "for", "a", "specific", "dataset" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-compaction/src/main/java/org/apache/gobblin/compaction/mapreduce/MRCompactor.java#L587-L597
26,151
apache/incubator-gobblin
gobblin-compaction/src/main/java/org/apache/gobblin/compaction/mapreduce/MRCompactor.java
MRCompactor.addRunningHadoopJob
public static void addRunningHadoopJob(Dataset dataset, Job job) { MRCompactor.RUNNING_MR_JOBS.put(dataset, job); }
java
public static void addRunningHadoopJob(Dataset dataset, Job job) { MRCompactor.RUNNING_MR_JOBS.put(dataset, job); }
[ "public", "static", "void", "addRunningHadoopJob", "(", "Dataset", "dataset", ",", "Job", "job", ")", "{", "MRCompactor", ".", "RUNNING_MR_JOBS", ".", "put", "(", "dataset", ",", "job", ")", ";", "}" ]
Keep track of running MR jobs, so if the compaction is cancelled, the MR jobs can be killed.
[ "Keep", "track", "of", "running", "MR", "jobs", "so", "if", "the", "compaction", "is", "cancelled", "the", "MR", "jobs", "can", "be", "killed", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-compaction/src/main/java/org/apache/gobblin/compaction/mapreduce/MRCompactor.java#L839-L841
26,152
apache/incubator-gobblin
gobblin-compaction/src/main/java/org/apache/gobblin/compaction/mapreduce/MRCompactor.java
MRCompactor.submitVerificationSuccessSlaEvent
private void submitVerificationSuccessSlaEvent(Results.Result result) { try { CompactionSlaEventHelper.getEventSubmitterBuilder(result.dataset(), Optional.<Job> absent(), this.fs) .eventSubmitter(this.eventSubmitter).eventName(CompactionSlaEventHelper.COMPLETION_VERIFICATION_SUCCESS_EVENT_NAME) .additionalMetadata(Maps.transformValues(result.verificationContext(), Functions.toStringFunction())).build() .submit(); } catch (Throwable t) { LOG.warn("Failed to submit verification success event:" + t, t); } }
java
private void submitVerificationSuccessSlaEvent(Results.Result result) { try { CompactionSlaEventHelper.getEventSubmitterBuilder(result.dataset(), Optional.<Job> absent(), this.fs) .eventSubmitter(this.eventSubmitter).eventName(CompactionSlaEventHelper.COMPLETION_VERIFICATION_SUCCESS_EVENT_NAME) .additionalMetadata(Maps.transformValues(result.verificationContext(), Functions.toStringFunction())).build() .submit(); } catch (Throwable t) { LOG.warn("Failed to submit verification success event:" + t, t); } }
[ "private", "void", "submitVerificationSuccessSlaEvent", "(", "Results", ".", "Result", "result", ")", "{", "try", "{", "CompactionSlaEventHelper", ".", "getEventSubmitterBuilder", "(", "result", ".", "dataset", "(", ")", ",", "Optional", ".", "<", "Job", ">", "absent", "(", ")", ",", "this", ".", "fs", ")", ".", "eventSubmitter", "(", "this", ".", "eventSubmitter", ")", ".", "eventName", "(", "CompactionSlaEventHelper", ".", "COMPLETION_VERIFICATION_SUCCESS_EVENT_NAME", ")", ".", "additionalMetadata", "(", "Maps", ".", "transformValues", "(", "result", ".", "verificationContext", "(", ")", ",", "Functions", ".", "toStringFunction", "(", ")", ")", ")", ".", "build", "(", ")", ".", "submit", "(", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "LOG", ".", "warn", "(", "\"Failed to submit verification success event:\"", "+", "t", ",", "t", ")", ";", "}", "}" ]
Submit an event when completeness verification is successful
[ "Submit", "an", "event", "when", "completeness", "verification", "is", "successful" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-compaction/src/main/java/org/apache/gobblin/compaction/mapreduce/MRCompactor.java#L986-L995
26,153
apache/incubator-gobblin
gobblin-compaction/src/main/java/org/apache/gobblin/compaction/mapreduce/MRCompactor.java
MRCompactor.submitFailureSlaEvent
private void submitFailureSlaEvent(Dataset dataset, String eventName) { try { CompactionSlaEventHelper.getEventSubmitterBuilder(dataset, Optional.<Job> absent(), this.fs) .eventSubmitter(this.eventSubmitter).eventName(eventName).build().submit(); } catch (Throwable t) { LOG.warn("Failed to submit failure sla event:" + t, t); } }
java
private void submitFailureSlaEvent(Dataset dataset, String eventName) { try { CompactionSlaEventHelper.getEventSubmitterBuilder(dataset, Optional.<Job> absent(), this.fs) .eventSubmitter(this.eventSubmitter).eventName(eventName).build().submit(); } catch (Throwable t) { LOG.warn("Failed to submit failure sla event:" + t, t); } }
[ "private", "void", "submitFailureSlaEvent", "(", "Dataset", "dataset", ",", "String", "eventName", ")", "{", "try", "{", "CompactionSlaEventHelper", ".", "getEventSubmitterBuilder", "(", "dataset", ",", "Optional", ".", "<", "Job", ">", "absent", "(", ")", ",", "this", ".", "fs", ")", ".", "eventSubmitter", "(", "this", ".", "eventSubmitter", ")", ".", "eventName", "(", "eventName", ")", ".", "build", "(", ")", ".", "submit", "(", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "LOG", ".", "warn", "(", "\"Failed to submit failure sla event:\"", "+", "t", ",", "t", ")", ";", "}", "}" ]
Submit a failure sla event
[ "Submit", "a", "failure", "sla", "event" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-compaction/src/main/java/org/apache/gobblin/compaction/mapreduce/MRCompactor.java#L1000-L1007
26,154
apache/incubator-gobblin
gobblin-core-base/src/main/java/org/apache/gobblin/writer/BufferedAsyncDataWriter.java
BufferedAsyncDataWriter.close
public void close() throws IOException { try { this.running = false; this.accumulator.close(); if (!this.service.awaitTermination(60, TimeUnit.SECONDS)) { forceClose(); } else { LOG.info ("Closed properly: elapsed " + (System.currentTimeMillis() - startTime) + " milliseconds"); } } catch (InterruptedException e) { LOG.error ("Interruption happened during close " + e.toString()); } finally { this.processor.close(); } }
java
public void close() throws IOException { try { this.running = false; this.accumulator.close(); if (!this.service.awaitTermination(60, TimeUnit.SECONDS)) { forceClose(); } else { LOG.info ("Closed properly: elapsed " + (System.currentTimeMillis() - startTime) + " milliseconds"); } } catch (InterruptedException e) { LOG.error ("Interruption happened during close " + e.toString()); } finally { this.processor.close(); } }
[ "public", "void", "close", "(", ")", "throws", "IOException", "{", "try", "{", "this", ".", "running", "=", "false", ";", "this", ".", "accumulator", ".", "close", "(", ")", ";", "if", "(", "!", "this", ".", "service", ".", "awaitTermination", "(", "60", ",", "TimeUnit", ".", "SECONDS", ")", ")", "{", "forceClose", "(", ")", ";", "}", "else", "{", "LOG", ".", "info", "(", "\"Closed properly: elapsed \"", "+", "(", "System", ".", "currentTimeMillis", "(", ")", "-", "startTime", ")", "+", "\" milliseconds\"", ")", ";", "}", "}", "catch", "(", "InterruptedException", "e", ")", "{", "LOG", ".", "error", "(", "\"Interruption happened during close \"", "+", "e", ".", "toString", "(", ")", ")", ";", "}", "finally", "{", "this", ".", "processor", ".", "close", "(", ")", ";", "}", "}" ]
Close all the resources, this will be blocked until all the request are sent and gets acknowledged
[ "Close", "all", "the", "resources", "this", "will", "be", "blocked", "until", "all", "the", "request", "are", "sent", "and", "gets", "acknowledged" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core-base/src/main/java/org/apache/gobblin/writer/BufferedAsyncDataWriter.java#L185-L199
26,155
apache/incubator-gobblin
gobblin-restli/gobblin-throttling-service/gobblin-throttling-service-server/src/main/java/org/apache/gobblin/restli/throttling/TokenBucket.java
TokenBucket.getTokens
public boolean getTokens(long tokens, long timeout, TimeUnit timeoutUnit) throws InterruptedException { long timeoutMillis = timeoutUnit.toMillis(timeout); long wait = tryReserveTokens(tokens, timeoutMillis); if (wait < 0) { return false; } if (wait == 0) { return true; } Thread.sleep(wait); return true; }
java
public boolean getTokens(long tokens, long timeout, TimeUnit timeoutUnit) throws InterruptedException { long timeoutMillis = timeoutUnit.toMillis(timeout); long wait = tryReserveTokens(tokens, timeoutMillis); if (wait < 0) { return false; } if (wait == 0) { return true; } Thread.sleep(wait); return true; }
[ "public", "boolean", "getTokens", "(", "long", "tokens", ",", "long", "timeout", ",", "TimeUnit", "timeoutUnit", ")", "throws", "InterruptedException", "{", "long", "timeoutMillis", "=", "timeoutUnit", ".", "toMillis", "(", "timeout", ")", ";", "long", "wait", "=", "tryReserveTokens", "(", "tokens", ",", "timeoutMillis", ")", ";", "if", "(", "wait", "<", "0", ")", "{", "return", "false", ";", "}", "if", "(", "wait", "==", "0", ")", "{", "return", "true", ";", "}", "Thread", ".", "sleep", "(", "wait", ")", ";", "return", "true", ";", "}" ]
Attempt to get the specified amount of tokens within the specified timeout. If the tokens cannot be retrieved in the specified timeout, the call will return false immediately, otherwise, the call will block until the tokens are available. @return true if the tokens are granted. @throws InterruptedException
[ "Attempt", "to", "get", "the", "specified", "amount", "of", "tokens", "within", "the", "specified", "timeout", ".", "If", "the", "tokens", "cannot", "be", "retrieved", "in", "the", "specified", "timeout", "the", "call", "will", "return", "false", "immediately", "otherwise", "the", "call", "will", "block", "until", "the", "tokens", "are", "available", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-restli/gobblin-throttling-service/gobblin-throttling-service-server/src/main/java/org/apache/gobblin/restli/throttling/TokenBucket.java#L69-L82
26,156
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/source/extractor/filebased/FileBasedSource.java
FileBasedSource.addLineageSourceInfo
protected void addLineageSourceInfo(WorkUnit workUnit, State state) { if (!lineageInfo.isPresent()) { log.info("Lineage is not enabled"); return; } String platform = state.getProp(ConfigurationKeys.SOURCE_FILEBASED_PLATFORM, DatasetConstants.PLATFORM_HDFS); Path dataDir = new Path(state.getProp(ConfigurationKeys.SOURCE_FILEBASED_DATA_DIRECTORY)); String dataset = Path.getPathWithoutSchemeAndAuthority(dataDir).toString(); DatasetDescriptor source = new DatasetDescriptor(platform, dataset); lineageInfo.get().setSource(source, workUnit); }
java
protected void addLineageSourceInfo(WorkUnit workUnit, State state) { if (!lineageInfo.isPresent()) { log.info("Lineage is not enabled"); return; } String platform = state.getProp(ConfigurationKeys.SOURCE_FILEBASED_PLATFORM, DatasetConstants.PLATFORM_HDFS); Path dataDir = new Path(state.getProp(ConfigurationKeys.SOURCE_FILEBASED_DATA_DIRECTORY)); String dataset = Path.getPathWithoutSchemeAndAuthority(dataDir).toString(); DatasetDescriptor source = new DatasetDescriptor(platform, dataset); lineageInfo.get().setSource(source, workUnit); }
[ "protected", "void", "addLineageSourceInfo", "(", "WorkUnit", "workUnit", ",", "State", "state", ")", "{", "if", "(", "!", "lineageInfo", ".", "isPresent", "(", ")", ")", "{", "log", ".", "info", "(", "\"Lineage is not enabled\"", ")", ";", "return", ";", "}", "String", "platform", "=", "state", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_FILEBASED_PLATFORM", ",", "DatasetConstants", ".", "PLATFORM_HDFS", ")", ";", "Path", "dataDir", "=", "new", "Path", "(", "state", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_FILEBASED_DATA_DIRECTORY", ")", ")", ";", "String", "dataset", "=", "Path", ".", "getPathWithoutSchemeAndAuthority", "(", "dataDir", ")", ".", "toString", "(", ")", ";", "DatasetDescriptor", "source", "=", "new", "DatasetDescriptor", "(", "platform", ",", "dataset", ")", ";", "lineageInfo", ".", "get", "(", ")", ".", "setSource", "(", "source", ",", "workUnit", ")", ";", "}" ]
Add lineage source info to a single work unit @param workUnit a single work unit, not an instance of {@link org.apache.gobblin.source.workunit.MultiWorkUnit} @param state configurations
[ "Add", "lineage", "source", "info", "to", "a", "single", "work", "unit" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/source/extractor/filebased/FileBasedSource.java#L236-L247
26,157
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/source/extractor/filebased/FileBasedSource.java
FileBasedSource.getcurrentFsSnapshot
public List<String> getcurrentFsSnapshot(State state) { List<String> results = new ArrayList<>(); String path = getLsPattern(state); try { log.info("Running ls command with input " + path); results = this.fsHelper.ls(path); for (int i = 0; i < results.size(); i++) { URI uri = new URI(results.get(i)); String filePath = uri.toString(); if (!uri.isAbsolute()) { File file = new File(state.getProp(ConfigurationKeys.SOURCE_FILEBASED_DATA_DIRECTORY), uri.toString()); filePath = file.getAbsolutePath(); } results.set(i, filePath + this.splitPattern + this.fsHelper.getFileMTime(filePath)); } } catch (FileBasedHelperException | URISyntaxException e) { log.error("Not able to fetch the filename/file modified time to " + e.getMessage() + " will not pull any files", e); } return results; }
java
public List<String> getcurrentFsSnapshot(State state) { List<String> results = new ArrayList<>(); String path = getLsPattern(state); try { log.info("Running ls command with input " + path); results = this.fsHelper.ls(path); for (int i = 0; i < results.size(); i++) { URI uri = new URI(results.get(i)); String filePath = uri.toString(); if (!uri.isAbsolute()) { File file = new File(state.getProp(ConfigurationKeys.SOURCE_FILEBASED_DATA_DIRECTORY), uri.toString()); filePath = file.getAbsolutePath(); } results.set(i, filePath + this.splitPattern + this.fsHelper.getFileMTime(filePath)); } } catch (FileBasedHelperException | URISyntaxException e) { log.error("Not able to fetch the filename/file modified time to " + e.getMessage() + " will not pull any files", e); } return results; }
[ "public", "List", "<", "String", ">", "getcurrentFsSnapshot", "(", "State", "state", ")", "{", "List", "<", "String", ">", "results", "=", "new", "ArrayList", "<>", "(", ")", ";", "String", "path", "=", "getLsPattern", "(", "state", ")", ";", "try", "{", "log", ".", "info", "(", "\"Running ls command with input \"", "+", "path", ")", ";", "results", "=", "this", ".", "fsHelper", ".", "ls", "(", "path", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "results", ".", "size", "(", ")", ";", "i", "++", ")", "{", "URI", "uri", "=", "new", "URI", "(", "results", ".", "get", "(", "i", ")", ")", ";", "String", "filePath", "=", "uri", ".", "toString", "(", ")", ";", "if", "(", "!", "uri", ".", "isAbsolute", "(", ")", ")", "{", "File", "file", "=", "new", "File", "(", "state", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_FILEBASED_DATA_DIRECTORY", ")", ",", "uri", ".", "toString", "(", ")", ")", ";", "filePath", "=", "file", ".", "getAbsolutePath", "(", ")", ";", "}", "results", ".", "set", "(", "i", ",", "filePath", "+", "this", ".", "splitPattern", "+", "this", ".", "fsHelper", ".", "getFileMTime", "(", "filePath", ")", ")", ";", "}", "}", "catch", "(", "FileBasedHelperException", "|", "URISyntaxException", "e", ")", "{", "log", ".", "error", "(", "\"Not able to fetch the filename/file modified time to \"", "+", "e", ".", "getMessage", "(", ")", "+", "\" will not pull any files\"", ",", "e", ")", ";", "}", "return", "results", ";", "}" ]
This method is responsible for connecting to the source and taking a snapshot of the folder where the data is present, it then returns a list of the files in String format @param state is used to connect to the source @return a list of file name or paths present on the external data directory
[ "This", "method", "is", "responsible", "for", "connecting", "to", "the", "source", "and", "taking", "a", "snapshot", "of", "the", "folder", "where", "the", "data", "is", "present", "it", "then", "returns", "a", "list", "of", "the", "files", "in", "String", "format" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/source/extractor/filebased/FileBasedSource.java#L257-L278
26,158
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/fork/Fork.java
Fork.checkDataQuality
private boolean checkDataQuality(Optional<Object> schema) throws Exception { if (this.branches > 1) { this.forkTaskState.setProp(ConfigurationKeys.EXTRACTOR_ROWS_EXPECTED, this.taskState.getProp(ConfigurationKeys.EXTRACTOR_ROWS_EXPECTED)); this.forkTaskState.setProp(ConfigurationKeys.EXTRACTOR_ROWS_EXTRACTED, this.taskState.getProp(ConfigurationKeys.EXTRACTOR_ROWS_EXTRACTED)); } String writerRecordsWrittenKey = ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_RECORDS_WRITTEN, this.branches, this.index); if (this.writer.isPresent()) { this.forkTaskState.setProp(ConfigurationKeys.WRITER_ROWS_WRITTEN, this.writer.get().recordsWritten()); this.taskState.setProp(writerRecordsWrittenKey, this.writer.get().recordsWritten()); } else { this.forkTaskState.setProp(ConfigurationKeys.WRITER_ROWS_WRITTEN, 0L); this.taskState.setProp(writerRecordsWrittenKey, 0L); } if (schema.isPresent()) { this.forkTaskState.setProp(ConfigurationKeys.EXTRACT_SCHEMA, schema.get().toString()); } try { // Do task-level quality checking TaskLevelPolicyCheckResults taskResults = this.taskContext.getTaskLevelPolicyChecker(this.forkTaskState, this.branches > 1 ? this.index : -1) .executePolicies(); TaskPublisher publisher = this.taskContext.getTaskPublisher(this.forkTaskState, taskResults); switch (publisher.canPublish()) { case SUCCESS: return true; case CLEANUP_FAIL: this.logger.error("Cleanup failed for task " + this.taskId); break; case POLICY_TESTS_FAIL: this.logger.error("Not all quality checking passed for task " + this.taskId); break; case COMPONENTS_NOT_FINISHED: this.logger.error("Not all components completed for task " + this.taskId); break; default: break; } return false; } catch (Throwable t) { this.logger.error("Failed to check task-level data quality", t); return false; } }
java
private boolean checkDataQuality(Optional<Object> schema) throws Exception { if (this.branches > 1) { this.forkTaskState.setProp(ConfigurationKeys.EXTRACTOR_ROWS_EXPECTED, this.taskState.getProp(ConfigurationKeys.EXTRACTOR_ROWS_EXPECTED)); this.forkTaskState.setProp(ConfigurationKeys.EXTRACTOR_ROWS_EXTRACTED, this.taskState.getProp(ConfigurationKeys.EXTRACTOR_ROWS_EXTRACTED)); } String writerRecordsWrittenKey = ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_RECORDS_WRITTEN, this.branches, this.index); if (this.writer.isPresent()) { this.forkTaskState.setProp(ConfigurationKeys.WRITER_ROWS_WRITTEN, this.writer.get().recordsWritten()); this.taskState.setProp(writerRecordsWrittenKey, this.writer.get().recordsWritten()); } else { this.forkTaskState.setProp(ConfigurationKeys.WRITER_ROWS_WRITTEN, 0L); this.taskState.setProp(writerRecordsWrittenKey, 0L); } if (schema.isPresent()) { this.forkTaskState.setProp(ConfigurationKeys.EXTRACT_SCHEMA, schema.get().toString()); } try { // Do task-level quality checking TaskLevelPolicyCheckResults taskResults = this.taskContext.getTaskLevelPolicyChecker(this.forkTaskState, this.branches > 1 ? this.index : -1) .executePolicies(); TaskPublisher publisher = this.taskContext.getTaskPublisher(this.forkTaskState, taskResults); switch (publisher.canPublish()) { case SUCCESS: return true; case CLEANUP_FAIL: this.logger.error("Cleanup failed for task " + this.taskId); break; case POLICY_TESTS_FAIL: this.logger.error("Not all quality checking passed for task " + this.taskId); break; case COMPONENTS_NOT_FINISHED: this.logger.error("Not all components completed for task " + this.taskId); break; default: break; } return false; } catch (Throwable t) { this.logger.error("Failed to check task-level data quality", t); return false; } }
[ "private", "boolean", "checkDataQuality", "(", "Optional", "<", "Object", ">", "schema", ")", "throws", "Exception", "{", "if", "(", "this", ".", "branches", ">", "1", ")", "{", "this", ".", "forkTaskState", ".", "setProp", "(", "ConfigurationKeys", ".", "EXTRACTOR_ROWS_EXPECTED", ",", "this", ".", "taskState", ".", "getProp", "(", "ConfigurationKeys", ".", "EXTRACTOR_ROWS_EXPECTED", ")", ")", ";", "this", ".", "forkTaskState", ".", "setProp", "(", "ConfigurationKeys", ".", "EXTRACTOR_ROWS_EXTRACTED", ",", "this", ".", "taskState", ".", "getProp", "(", "ConfigurationKeys", ".", "EXTRACTOR_ROWS_EXTRACTED", ")", ")", ";", "}", "String", "writerRecordsWrittenKey", "=", "ForkOperatorUtils", ".", "getPropertyNameForBranch", "(", "ConfigurationKeys", ".", "WRITER_RECORDS_WRITTEN", ",", "this", ".", "branches", ",", "this", ".", "index", ")", ";", "if", "(", "this", ".", "writer", ".", "isPresent", "(", ")", ")", "{", "this", ".", "forkTaskState", ".", "setProp", "(", "ConfigurationKeys", ".", "WRITER_ROWS_WRITTEN", ",", "this", ".", "writer", ".", "get", "(", ")", ".", "recordsWritten", "(", ")", ")", ";", "this", ".", "taskState", ".", "setProp", "(", "writerRecordsWrittenKey", ",", "this", ".", "writer", ".", "get", "(", ")", ".", "recordsWritten", "(", ")", ")", ";", "}", "else", "{", "this", ".", "forkTaskState", ".", "setProp", "(", "ConfigurationKeys", ".", "WRITER_ROWS_WRITTEN", ",", "0L", ")", ";", "this", ".", "taskState", ".", "setProp", "(", "writerRecordsWrittenKey", ",", "0L", ")", ";", "}", "if", "(", "schema", ".", "isPresent", "(", ")", ")", "{", "this", ".", "forkTaskState", ".", "setProp", "(", "ConfigurationKeys", ".", "EXTRACT_SCHEMA", ",", "schema", ".", "get", "(", ")", ".", "toString", "(", ")", ")", ";", "}", "try", "{", "// Do task-level quality checking", "TaskLevelPolicyCheckResults", "taskResults", "=", "this", ".", "taskContext", ".", "getTaskLevelPolicyChecker", "(", "this", ".", "forkTaskState", ",", "this", ".", "branches", ">", "1", "?", "this", ".", "index", ":", "-", "1", ")", ".", "executePolicies", "(", ")", ";", "TaskPublisher", "publisher", "=", "this", ".", "taskContext", ".", "getTaskPublisher", "(", "this", ".", "forkTaskState", ",", "taskResults", ")", ";", "switch", "(", "publisher", ".", "canPublish", "(", ")", ")", "{", "case", "SUCCESS", ":", "return", "true", ";", "case", "CLEANUP_FAIL", ":", "this", ".", "logger", ".", "error", "(", "\"Cleanup failed for task \"", "+", "this", ".", "taskId", ")", ";", "break", ";", "case", "POLICY_TESTS_FAIL", ":", "this", ".", "logger", ".", "error", "(", "\"Not all quality checking passed for task \"", "+", "this", ".", "taskId", ")", ";", "break", ";", "case", "COMPONENTS_NOT_FINISHED", ":", "this", ".", "logger", ".", "error", "(", "\"Not all components completed for task \"", "+", "this", ".", "taskId", ")", ";", "break", ";", "default", ":", "break", ";", "}", "return", "false", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "this", ".", "logger", ".", "error", "(", "\"Failed to check task-level data quality\"", ",", "t", ")", ";", "return", "false", ";", "}", "}" ]
Check data quality. @return whether data publishing is successful and data should be committed
[ "Check", "data", "quality", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/fork/Fork.java#L549-L599
26,159
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/fork/Fork.java
Fork.commitData
private void commitData() throws IOException { if (this.writer.isPresent()) { // Not to catch the exception this may throw so it gets propagated this.writer.get().commit(); } try { if (GobblinMetrics.isEnabled(this.taskState.getWorkunit())) { // Update record-level and byte-level metrics after the writer commits updateRecordMetrics(); updateByteMetrics(); } } catch (IOException ioe) { // Trap the exception as failing to update metrics should not cause the task to fail this.logger.error("Failed to update byte-level metrics of task " + this.taskId); } }
java
private void commitData() throws IOException { if (this.writer.isPresent()) { // Not to catch the exception this may throw so it gets propagated this.writer.get().commit(); } try { if (GobblinMetrics.isEnabled(this.taskState.getWorkunit())) { // Update record-level and byte-level metrics after the writer commits updateRecordMetrics(); updateByteMetrics(); } } catch (IOException ioe) { // Trap the exception as failing to update metrics should not cause the task to fail this.logger.error("Failed to update byte-level metrics of task " + this.taskId); } }
[ "private", "void", "commitData", "(", ")", "throws", "IOException", "{", "if", "(", "this", ".", "writer", ".", "isPresent", "(", ")", ")", "{", "// Not to catch the exception this may throw so it gets propagated", "this", ".", "writer", ".", "get", "(", ")", ".", "commit", "(", ")", ";", "}", "try", "{", "if", "(", "GobblinMetrics", ".", "isEnabled", "(", "this", ".", "taskState", ".", "getWorkunit", "(", ")", ")", ")", "{", "// Update record-level and byte-level metrics after the writer commits", "updateRecordMetrics", "(", ")", ";", "updateByteMetrics", "(", ")", ";", "}", "}", "catch", "(", "IOException", "ioe", ")", "{", "// Trap the exception as failing to update metrics should not cause the task to fail", "this", ".", "logger", ".", "error", "(", "\"Failed to update byte-level metrics of task \"", "+", "this", ".", "taskId", ")", ";", "}", "}" ]
Commit task data.
[ "Commit", "task", "data", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/fork/Fork.java#L604-L621
26,160
apache/incubator-gobblin
gobblin-config-management/gobblin-config-core/src/main/java/org/apache/gobblin/config/common/impl/ImportTraverser.java
ImportTraverser.computeRecursiveTraversal
private LinkedList<T> computeRecursiveTraversal(T node, NodePath<T> nodePath) { try { LinkedList<T> imports = new LinkedList<>(); Set<T> alreadyIncludedImports = new HashSet<>(); for (T neighbor : this.traversalFunction.apply(node)) { nodePath.appendNode(neighbor); addSubtraversal(neighbor, imports, alreadyIncludedImports, nodePath); nodePath.popTail(); } return imports; } catch (ExecutionException ee) { throw new RuntimeException(ee); } }
java
private LinkedList<T> computeRecursiveTraversal(T node, NodePath<T> nodePath) { try { LinkedList<T> imports = new LinkedList<>(); Set<T> alreadyIncludedImports = new HashSet<>(); for (T neighbor : this.traversalFunction.apply(node)) { nodePath.appendNode(neighbor); addSubtraversal(neighbor, imports, alreadyIncludedImports, nodePath); nodePath.popTail(); } return imports; } catch (ExecutionException ee) { throw new RuntimeException(ee); } }
[ "private", "LinkedList", "<", "T", ">", "computeRecursiveTraversal", "(", "T", "node", ",", "NodePath", "<", "T", ">", "nodePath", ")", "{", "try", "{", "LinkedList", "<", "T", ">", "imports", "=", "new", "LinkedList", "<>", "(", ")", ";", "Set", "<", "T", ">", "alreadyIncludedImports", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "T", "neighbor", ":", "this", ".", "traversalFunction", ".", "apply", "(", "node", ")", ")", "{", "nodePath", ".", "appendNode", "(", "neighbor", ")", ";", "addSubtraversal", "(", "neighbor", ",", "imports", ",", "alreadyIncludedImports", ",", "nodePath", ")", ";", "nodePath", ".", "popTail", "(", ")", ";", "}", "return", "imports", ";", "}", "catch", "(", "ExecutionException", "ee", ")", "{", "throw", "new", "RuntimeException", "(", "ee", ")", ";", "}", "}" ]
Actually compute the traversal if it is not in the cache.
[ "Actually", "compute", "the", "traversal", "if", "it", "is", "not", "in", "the", "cache", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-config-management/gobblin-config-core/src/main/java/org/apache/gobblin/config/common/impl/ImportTraverser.java#L70-L87
26,161
apache/incubator-gobblin
gobblin-config-management/gobblin-config-core/src/main/java/org/apache/gobblin/config/common/impl/ImportTraverser.java
ImportTraverser.addSubtraversal
private void addSubtraversal(T node, LinkedList<T> imports, Set<T> alreadyIncludedImports, NodePath<T> nodePath) throws ExecutionException { if (addNodeIfNotAlreadyIncluded(node, imports, alreadyIncludedImports)) { for (T inheritedFromParent : doTraverseGraphRecursively(node, nodePath)) { addNodeIfNotAlreadyIncluded(inheritedFromParent, imports, alreadyIncludedImports); } } }
java
private void addSubtraversal(T node, LinkedList<T> imports, Set<T> alreadyIncludedImports, NodePath<T> nodePath) throws ExecutionException { if (addNodeIfNotAlreadyIncluded(node, imports, alreadyIncludedImports)) { for (T inheritedFromParent : doTraverseGraphRecursively(node, nodePath)) { addNodeIfNotAlreadyIncluded(inheritedFromParent, imports, alreadyIncludedImports); } } }
[ "private", "void", "addSubtraversal", "(", "T", "node", ",", "LinkedList", "<", "T", ">", "imports", ",", "Set", "<", "T", ">", "alreadyIncludedImports", ",", "NodePath", "<", "T", ">", "nodePath", ")", "throws", "ExecutionException", "{", "if", "(", "addNodeIfNotAlreadyIncluded", "(", "node", ",", "imports", ",", "alreadyIncludedImports", ")", ")", "{", "for", "(", "T", "inheritedFromParent", ":", "doTraverseGraphRecursively", "(", "node", ",", "nodePath", ")", ")", "{", "addNodeIfNotAlreadyIncluded", "(", "inheritedFromParent", ",", "imports", ",", "alreadyIncludedImports", ")", ";", "}", "}", "}" ]
Add a sub-traversal for a neighboring node.
[ "Add", "a", "sub", "-", "traversal", "for", "a", "neighboring", "node", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-config-management/gobblin-config-core/src/main/java/org/apache/gobblin/config/common/impl/ImportTraverser.java#L92-L100
26,162
apache/incubator-gobblin
gobblin-config-management/gobblin-config-core/src/main/java/org/apache/gobblin/config/common/impl/ImportTraverser.java
ImportTraverser.addNodeIfNotAlreadyIncluded
private boolean addNodeIfNotAlreadyIncluded(T thisImport, LinkedList<T> imports, Set<T> alreadyIncludedImports) { if (alreadyIncludedImports.contains(thisImport)) { return false; } imports.add(thisImport); alreadyIncludedImports.add(thisImport); return true; }
java
private boolean addNodeIfNotAlreadyIncluded(T thisImport, LinkedList<T> imports, Set<T> alreadyIncludedImports) { if (alreadyIncludedImports.contains(thisImport)) { return false; } imports.add(thisImport); alreadyIncludedImports.add(thisImport); return true; }
[ "private", "boolean", "addNodeIfNotAlreadyIncluded", "(", "T", "thisImport", ",", "LinkedList", "<", "T", ">", "imports", ",", "Set", "<", "T", ">", "alreadyIncludedImports", ")", "{", "if", "(", "alreadyIncludedImports", ".", "contains", "(", "thisImport", ")", ")", "{", "return", "false", ";", "}", "imports", ".", "add", "(", "thisImport", ")", ";", "alreadyIncludedImports", ".", "add", "(", "thisImport", ")", ";", "return", "true", ";", "}" ]
Only add node to traversal if it is not already included in it.
[ "Only", "add", "node", "to", "traversal", "if", "it", "is", "not", "already", "included", "in", "it", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-config-management/gobblin-config-core/src/main/java/org/apache/gobblin/config/common/impl/ImportTraverser.java#L105-L113
26,163
apache/incubator-gobblin
gobblin-config-management/gobblin-config-core/src/main/java/org/apache/gobblin/config/common/impl/ImportTraverser.java
ImportTraverser.unpackExecutionException
private RuntimeException unpackExecutionException(Throwable exc) { while (exc instanceof ExecutionException || exc instanceof UncheckedExecutionException) { exc = exc.getCause(); } return Throwables.propagate(exc); }
java
private RuntimeException unpackExecutionException(Throwable exc) { while (exc instanceof ExecutionException || exc instanceof UncheckedExecutionException) { exc = exc.getCause(); } return Throwables.propagate(exc); }
[ "private", "RuntimeException", "unpackExecutionException", "(", "Throwable", "exc", ")", "{", "while", "(", "exc", "instanceof", "ExecutionException", "||", "exc", "instanceof", "UncheckedExecutionException", ")", "{", "exc", "=", "exc", ".", "getCause", "(", ")", ";", "}", "return", "Throwables", ".", "propagate", "(", "exc", ")", ";", "}" ]
Due to recursive nature of algorithm, we may end up with multiple layers of exceptions. Unpack them.
[ "Due", "to", "recursive", "nature", "of", "algorithm", "we", "may", "end", "up", "with", "multiple", "layers", "of", "exceptions", ".", "Unpack", "them", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-config-management/gobblin-config-core/src/main/java/org/apache/gobblin/config/common/impl/ImportTraverser.java#L118-L123
26,164
apache/incubator-gobblin
gobblin-restli/gobblin-restli-utils/src/main/java/org/apache/gobblin/restli/EmbeddedRestliServer.java
EmbeddedRestliServer.getListeningURI
public URI getListeningURI() { try { return new URI(this.serverUri.getScheme(), this.serverUri.getUserInfo(), this.serverUri.getHost(), this.port, null, null, null); } catch (URISyntaxException use) { throw new RuntimeException("Invalid URI. This is an error in code.", use); } }
java
public URI getListeningURI() { try { return new URI(this.serverUri.getScheme(), this.serverUri.getUserInfo(), this.serverUri.getHost(), this.port, null, null, null); } catch (URISyntaxException use) { throw new RuntimeException("Invalid URI. This is an error in code.", use); } }
[ "public", "URI", "getListeningURI", "(", ")", "{", "try", "{", "return", "new", "URI", "(", "this", ".", "serverUri", ".", "getScheme", "(", ")", ",", "this", ".", "serverUri", ".", "getUserInfo", "(", ")", ",", "this", ".", "serverUri", ".", "getHost", "(", ")", ",", "this", ".", "port", ",", "null", ",", "null", ",", "null", ")", ";", "}", "catch", "(", "URISyntaxException", "use", ")", "{", "throw", "new", "RuntimeException", "(", "\"Invalid URI. This is an error in code.\"", ",", "use", ")", ";", "}", "}" ]
Get the scheme and authority at which this server is listening.
[ "Get", "the", "scheme", "and", "authority", "at", "which", "this", "server", "is", "listening", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-restli/gobblin-restli-utils/src/main/java/org/apache/gobblin/restli/EmbeddedRestliServer.java#L162-L169
26,165
apache/incubator-gobblin
gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/publisher/JdbcPublisher.java
JdbcPublisher.publishData
@Override public void publishData(Collection<? extends WorkUnitState> states) throws IOException { LOG.info("Start publishing data"); int branches = this.state.getPropAsInt(ConfigurationKeys.FORK_BRANCHES_KEY, 1); Set<String> emptiedDestTables = Sets.newHashSet(); final Connection conn = createConnection(); final JdbcWriterCommands commands = this.jdbcWriterCommandsFactory.newInstance(this.state, conn); try { conn.setAutoCommit(false); for (int i = 0; i < branches; i++) { final String destinationTable = this.state .getProp(ForkOperatorUtils.getPropertyNameForBranch(JDBC_PUBLISHER_FINAL_TABLE_NAME, branches, i)); final String databaseName = this.state.getProp(ForkOperatorUtils.getPropertyNameForBranch(JDBC_PUBLISHER_DATABASE_NAME, branches, i)); Preconditions.checkNotNull(destinationTable); if (this.state.getPropAsBoolean( ForkOperatorUtils.getPropertyNameForBranch(JDBC_PUBLISHER_REPLACE_FINAL_TABLE, branches, i), false) && !emptiedDestTables.contains(destinationTable)) { LOG.info("Deleting table " + destinationTable); commands.deleteAll(databaseName, destinationTable); emptiedDestTables.add(destinationTable); } Map<String, List<WorkUnitState>> stagingTables = getStagingTables(states, branches, i); for (Map.Entry<String, List<WorkUnitState>> entry : stagingTables.entrySet()) { String stagingTable = entry.getKey(); LOG.info("Copying data from staging table " + stagingTable + " into destination table " + destinationTable); commands.copyTable(databaseName, stagingTable, destinationTable); for (WorkUnitState workUnitState : entry.getValue()) { workUnitState.setWorkingState(WorkUnitState.WorkingState.COMMITTED); } } } LOG.info("Commit publish data"); conn.commit(); } catch (Exception e) { try { LOG.error("Failed publishing. Rolling back."); conn.rollback(); } catch (SQLException se) { LOG.error("Failed rolling back.", se); } throw new RuntimeException("Failed publishing", e); } finally { try { conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } } }
java
@Override public void publishData(Collection<? extends WorkUnitState> states) throws IOException { LOG.info("Start publishing data"); int branches = this.state.getPropAsInt(ConfigurationKeys.FORK_BRANCHES_KEY, 1); Set<String> emptiedDestTables = Sets.newHashSet(); final Connection conn = createConnection(); final JdbcWriterCommands commands = this.jdbcWriterCommandsFactory.newInstance(this.state, conn); try { conn.setAutoCommit(false); for (int i = 0; i < branches; i++) { final String destinationTable = this.state .getProp(ForkOperatorUtils.getPropertyNameForBranch(JDBC_PUBLISHER_FINAL_TABLE_NAME, branches, i)); final String databaseName = this.state.getProp(ForkOperatorUtils.getPropertyNameForBranch(JDBC_PUBLISHER_DATABASE_NAME, branches, i)); Preconditions.checkNotNull(destinationTable); if (this.state.getPropAsBoolean( ForkOperatorUtils.getPropertyNameForBranch(JDBC_PUBLISHER_REPLACE_FINAL_TABLE, branches, i), false) && !emptiedDestTables.contains(destinationTable)) { LOG.info("Deleting table " + destinationTable); commands.deleteAll(databaseName, destinationTable); emptiedDestTables.add(destinationTable); } Map<String, List<WorkUnitState>> stagingTables = getStagingTables(states, branches, i); for (Map.Entry<String, List<WorkUnitState>> entry : stagingTables.entrySet()) { String stagingTable = entry.getKey(); LOG.info("Copying data from staging table " + stagingTable + " into destination table " + destinationTable); commands.copyTable(databaseName, stagingTable, destinationTable); for (WorkUnitState workUnitState : entry.getValue()) { workUnitState.setWorkingState(WorkUnitState.WorkingState.COMMITTED); } } } LOG.info("Commit publish data"); conn.commit(); } catch (Exception e) { try { LOG.error("Failed publishing. Rolling back."); conn.rollback(); } catch (SQLException se) { LOG.error("Failed rolling back.", se); } throw new RuntimeException("Failed publishing", e); } finally { try { conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } } }
[ "@", "Override", "public", "void", "publishData", "(", "Collection", "<", "?", "extends", "WorkUnitState", ">", "states", ")", "throws", "IOException", "{", "LOG", ".", "info", "(", "\"Start publishing data\"", ")", ";", "int", "branches", "=", "this", ".", "state", ".", "getPropAsInt", "(", "ConfigurationKeys", ".", "FORK_BRANCHES_KEY", ",", "1", ")", ";", "Set", "<", "String", ">", "emptiedDestTables", "=", "Sets", ".", "newHashSet", "(", ")", ";", "final", "Connection", "conn", "=", "createConnection", "(", ")", ";", "final", "JdbcWriterCommands", "commands", "=", "this", ".", "jdbcWriterCommandsFactory", ".", "newInstance", "(", "this", ".", "state", ",", "conn", ")", ";", "try", "{", "conn", ".", "setAutoCommit", "(", "false", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "branches", ";", "i", "++", ")", "{", "final", "String", "destinationTable", "=", "this", ".", "state", ".", "getProp", "(", "ForkOperatorUtils", ".", "getPropertyNameForBranch", "(", "JDBC_PUBLISHER_FINAL_TABLE_NAME", ",", "branches", ",", "i", ")", ")", ";", "final", "String", "databaseName", "=", "this", ".", "state", ".", "getProp", "(", "ForkOperatorUtils", ".", "getPropertyNameForBranch", "(", "JDBC_PUBLISHER_DATABASE_NAME", ",", "branches", ",", "i", ")", ")", ";", "Preconditions", ".", "checkNotNull", "(", "destinationTable", ")", ";", "if", "(", "this", ".", "state", ".", "getPropAsBoolean", "(", "ForkOperatorUtils", ".", "getPropertyNameForBranch", "(", "JDBC_PUBLISHER_REPLACE_FINAL_TABLE", ",", "branches", ",", "i", ")", ",", "false", ")", "&&", "!", "emptiedDestTables", ".", "contains", "(", "destinationTable", ")", ")", "{", "LOG", ".", "info", "(", "\"Deleting table \"", "+", "destinationTable", ")", ";", "commands", ".", "deleteAll", "(", "databaseName", ",", "destinationTable", ")", ";", "emptiedDestTables", ".", "add", "(", "destinationTable", ")", ";", "}", "Map", "<", "String", ",", "List", "<", "WorkUnitState", ">", ">", "stagingTables", "=", "getStagingTables", "(", "states", ",", "branches", ",", "i", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "List", "<", "WorkUnitState", ">", ">", "entry", ":", "stagingTables", ".", "entrySet", "(", ")", ")", "{", "String", "stagingTable", "=", "entry", ".", "getKey", "(", ")", ";", "LOG", ".", "info", "(", "\"Copying data from staging table \"", "+", "stagingTable", "+", "\" into destination table \"", "+", "destinationTable", ")", ";", "commands", ".", "copyTable", "(", "databaseName", ",", "stagingTable", ",", "destinationTable", ")", ";", "for", "(", "WorkUnitState", "workUnitState", ":", "entry", ".", "getValue", "(", ")", ")", "{", "workUnitState", ".", "setWorkingState", "(", "WorkUnitState", ".", "WorkingState", ".", "COMMITTED", ")", ";", "}", "}", "}", "LOG", ".", "info", "(", "\"Commit publish data\"", ")", ";", "conn", ".", "commit", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "try", "{", "LOG", ".", "error", "(", "\"Failed publishing. Rolling back.\"", ")", ";", "conn", ".", "rollback", "(", ")", ";", "}", "catch", "(", "SQLException", "se", ")", "{", "LOG", ".", "error", "(", "\"Failed rolling back.\"", ",", "se", ")", ";", "}", "throw", "new", "RuntimeException", "(", "\"Failed publishing\"", ",", "e", ")", ";", "}", "finally", "{", "try", "{", "conn", ".", "close", "(", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}", "}" ]
1. Truncate destination table if requested 2. Move data from staging to destination 3. Update Workunit state TODO: Research on running this in parallel. While testing publishing it in parallel, it turns out delete all from the table locks the table so that copying table threads wait until transaction lock times out and throwing exception(MySQL). Is there a way to avoid this? {@inheritDoc} @see org.apache.gobblin.publisher.DataPublisher#publishData(java.util.Collection)
[ "1", ".", "Truncate", "destination", "table", "if", "requested", "2", ".", "Move", "data", "from", "staging", "to", "destination", "3", ".", "Update", "Workunit", "state" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/publisher/JdbcPublisher.java#L134-L187
26,166
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/writer/FileAwareInputStreamDataWriterBuilder.java
FileAwareInputStreamDataWriterBuilder.setJobSpecificOutputPaths
public synchronized static void setJobSpecificOutputPaths(State state) { // Other tasks may have set this already if (!StringUtils.containsIgnoreCase(state.getProp(ConfigurationKeys.WRITER_STAGING_DIR), state.getProp(ConfigurationKeys.JOB_ID_KEY))) { state.setProp(ConfigurationKeys.WRITER_STAGING_DIR, new Path(state.getProp(ConfigurationKeys.WRITER_STAGING_DIR), state.getProp(ConfigurationKeys.JOB_ID_KEY))); state.setProp(ConfigurationKeys.WRITER_OUTPUT_DIR, new Path(state.getProp(ConfigurationKeys.WRITER_OUTPUT_DIR), state.getProp(ConfigurationKeys.JOB_ID_KEY))); } }
java
public synchronized static void setJobSpecificOutputPaths(State state) { // Other tasks may have set this already if (!StringUtils.containsIgnoreCase(state.getProp(ConfigurationKeys.WRITER_STAGING_DIR), state.getProp(ConfigurationKeys.JOB_ID_KEY))) { state.setProp(ConfigurationKeys.WRITER_STAGING_DIR, new Path(state.getProp(ConfigurationKeys.WRITER_STAGING_DIR), state.getProp(ConfigurationKeys.JOB_ID_KEY))); state.setProp(ConfigurationKeys.WRITER_OUTPUT_DIR, new Path(state.getProp(ConfigurationKeys.WRITER_OUTPUT_DIR), state.getProp(ConfigurationKeys.JOB_ID_KEY))); } }
[ "public", "synchronized", "static", "void", "setJobSpecificOutputPaths", "(", "State", "state", ")", "{", "// Other tasks may have set this already", "if", "(", "!", "StringUtils", ".", "containsIgnoreCase", "(", "state", ".", "getProp", "(", "ConfigurationKeys", ".", "WRITER_STAGING_DIR", ")", ",", "state", ".", "getProp", "(", "ConfigurationKeys", ".", "JOB_ID_KEY", ")", ")", ")", "{", "state", ".", "setProp", "(", "ConfigurationKeys", ".", "WRITER_STAGING_DIR", ",", "new", "Path", "(", "state", ".", "getProp", "(", "ConfigurationKeys", ".", "WRITER_STAGING_DIR", ")", ",", "state", ".", "getProp", "(", "ConfigurationKeys", ".", "JOB_ID_KEY", ")", ")", ")", ";", "state", ".", "setProp", "(", "ConfigurationKeys", ".", "WRITER_OUTPUT_DIR", ",", "new", "Path", "(", "state", ".", "getProp", "(", "ConfigurationKeys", ".", "WRITER_OUTPUT_DIR", ")", ",", "state", ".", "getProp", "(", "ConfigurationKeys", ".", "JOB_ID_KEY", ")", ")", ")", ";", "}", "}" ]
Each job gets its own task-staging and task-output directory. Update the staging and output directories to contain job_id. This is to make sure uncleaned data from previous execution does not corrupt final published data produced by this execution.
[ "Each", "job", "gets", "its", "own", "task", "-", "staging", "and", "task", "-", "output", "directory", ".", "Update", "the", "staging", "and", "output", "directories", "to", "contain", "job_id", ".", "This", "is", "to", "make", "sure", "uncleaned", "data", "from", "previous", "execution", "does", "not", "corrupt", "final", "published", "data", "produced", "by", "this", "execution", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/writer/FileAwareInputStreamDataWriterBuilder.java#L52-L65
26,167
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/scheduler/PathAlterationListenerAdaptorForMonitor.java
PathAlterationListenerAdaptorForMonitor.onFileChange
@Override public void onFileChange(Path path) { String fileExtension = path.getName().substring(path.getName().lastIndexOf('.') + 1); if (fileExtension.equalsIgnoreCase(SchedulerUtils.JOB_PROPS_FILE_EXTENSION)) { LOG.info("Detected change to common properties file " + path.toString()); loadNewCommonConfigAndHandleNewJob(path, JobScheduler.Action.RESCHEDULE); return; } if (!jobScheduler.jobConfigFileExtensions.contains(fileExtension)) { // Not a job configuration file, ignore. return; } LOG.info("Detected change to job configuration file " + path.toString()); loadNewJobConfigAndHandleNewJob(path, JobScheduler.Action.RESCHEDULE); }
java
@Override public void onFileChange(Path path) { String fileExtension = path.getName().substring(path.getName().lastIndexOf('.') + 1); if (fileExtension.equalsIgnoreCase(SchedulerUtils.JOB_PROPS_FILE_EXTENSION)) { LOG.info("Detected change to common properties file " + path.toString()); loadNewCommonConfigAndHandleNewJob(path, JobScheduler.Action.RESCHEDULE); return; } if (!jobScheduler.jobConfigFileExtensions.contains(fileExtension)) { // Not a job configuration file, ignore. return; } LOG.info("Detected change to job configuration file " + path.toString()); loadNewJobConfigAndHandleNewJob(path, JobScheduler.Action.RESCHEDULE); }
[ "@", "Override", "public", "void", "onFileChange", "(", "Path", "path", ")", "{", "String", "fileExtension", "=", "path", ".", "getName", "(", ")", ".", "substring", "(", "path", ".", "getName", "(", ")", ".", "lastIndexOf", "(", "'", "'", ")", "+", "1", ")", ";", "if", "(", "fileExtension", ".", "equalsIgnoreCase", "(", "SchedulerUtils", ".", "JOB_PROPS_FILE_EXTENSION", ")", ")", "{", "LOG", ".", "info", "(", "\"Detected change to common properties file \"", "+", "path", ".", "toString", "(", ")", ")", ";", "loadNewCommonConfigAndHandleNewJob", "(", "path", ",", "JobScheduler", ".", "Action", ".", "RESCHEDULE", ")", ";", "return", ";", "}", "if", "(", "!", "jobScheduler", ".", "jobConfigFileExtensions", ".", "contains", "(", "fileExtension", ")", ")", "{", "// Not a job configuration file, ignore.", "return", ";", "}", "LOG", ".", "info", "(", "\"Detected change to job configuration file \"", "+", "path", ".", "toString", "(", ")", ")", ";", "loadNewJobConfigAndHandleNewJob", "(", "path", ",", "JobScheduler", ".", "Action", ".", "RESCHEDULE", ")", ";", "}" ]
Called when a job configuration file is changed.
[ "Called", "when", "a", "job", "configuration", "file", "is", "changed", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/scheduler/PathAlterationListenerAdaptorForMonitor.java#L168-L184
26,168
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/scheduler/PathAlterationListenerAdaptorForMonitor.java
PathAlterationListenerAdaptorForMonitor.checkCommonPropExistance
private boolean checkCommonPropExistance(Path rootPath, String noExtFileName) throws IOException { Configuration conf = new Configuration(); FileStatus[] children = rootPath.getFileSystem(conf).listStatus(rootPath); for (FileStatus aChild : children) { if (aChild.getPath().getName().contains(noExtFileName)) { return false; } } return true; }
java
private boolean checkCommonPropExistance(Path rootPath, String noExtFileName) throws IOException { Configuration conf = new Configuration(); FileStatus[] children = rootPath.getFileSystem(conf).listStatus(rootPath); for (FileStatus aChild : children) { if (aChild.getPath().getName().contains(noExtFileName)) { return false; } } return true; }
[ "private", "boolean", "checkCommonPropExistance", "(", "Path", "rootPath", ",", "String", "noExtFileName", ")", "throws", "IOException", "{", "Configuration", "conf", "=", "new", "Configuration", "(", ")", ";", "FileStatus", "[", "]", "children", "=", "rootPath", ".", "getFileSystem", "(", "conf", ")", ".", "listStatus", "(", "rootPath", ")", ";", "for", "(", "FileStatus", "aChild", ":", "children", ")", "{", "if", "(", "aChild", ".", "getPath", "(", ")", ".", "getName", "(", ")", ".", "contains", "(", "noExtFileName", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Given the target rootPath, check if there's common properties existed. Return false if so. @param rootPath @return
[ "Given", "the", "target", "rootPath", "check", "if", "there", "s", "common", "properties", "existed", ".", "Return", "false", "if", "so", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/scheduler/PathAlterationListenerAdaptorForMonitor.java#L246-L257
26,169
apache/incubator-gobblin
gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/metrics/kafka/KafkaAvroSchemaRegistry.java
KafkaAvroSchemaRegistry.getSchemaByKey
@Override public Schema getSchemaByKey(String key) throws SchemaRegistryException { try { return cachedSchemasByKeys.get(key); } catch (ExecutionException e) { throw new SchemaRegistryException(String.format("Schema with key %s cannot be retrieved", key), e); } }
java
@Override public Schema getSchemaByKey(String key) throws SchemaRegistryException { try { return cachedSchemasByKeys.get(key); } catch (ExecutionException e) { throw new SchemaRegistryException(String.format("Schema with key %s cannot be retrieved", key), e); } }
[ "@", "Override", "public", "Schema", "getSchemaByKey", "(", "String", "key", ")", "throws", "SchemaRegistryException", "{", "try", "{", "return", "cachedSchemasByKeys", ".", "get", "(", "key", ")", ";", "}", "catch", "(", "ExecutionException", "e", ")", "{", "throw", "new", "SchemaRegistryException", "(", "String", ".", "format", "(", "\"Schema with key %s cannot be retrieved\"", ",", "key", ")", ",", "e", ")", ";", "}", "}" ]
Get schema from schema registry by key @param key Schema key @return Schema with the corresponding key @throws SchemaRegistryException if failed to retrieve schema.
[ "Get", "schema", "from", "schema", "registry", "by", "key" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/metrics/kafka/KafkaAvroSchemaRegistry.java#L121-L128
26,170
apache/incubator-gobblin
gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/metrics/kafka/KafkaAvroSchemaRegistry.java
KafkaAvroSchemaRegistry.fetchSchemaByKey
@Override protected Schema fetchSchemaByKey(String key) throws SchemaRegistryException { String schemaUrl = KafkaAvroSchemaRegistry.this.url + GET_RESOURCE_BY_ID + key; GetMethod get = new GetMethod(schemaUrl); int statusCode; String schemaString; HttpClient httpClient = this.borrowClient(); try { statusCode = httpClient.executeMethod(get); schemaString = get.getResponseBodyAsString(); } catch (IOException e) { throw new SchemaRegistryException(e); } finally { get.releaseConnection(); this.httpClientPool.returnObject(httpClient); } if (statusCode != HttpStatus.SC_OK) { throw new SchemaRegistryException( String.format("Schema with key %s cannot be retrieved, statusCode = %d", key, statusCode)); } Schema schema; try { schema = new Schema.Parser().parse(schemaString); } catch (Throwable t) { throw new SchemaRegistryException(String.format("Schema with ID = %s cannot be parsed", key), t); } return schema; }
java
@Override protected Schema fetchSchemaByKey(String key) throws SchemaRegistryException { String schemaUrl = KafkaAvroSchemaRegistry.this.url + GET_RESOURCE_BY_ID + key; GetMethod get = new GetMethod(schemaUrl); int statusCode; String schemaString; HttpClient httpClient = this.borrowClient(); try { statusCode = httpClient.executeMethod(get); schemaString = get.getResponseBodyAsString(); } catch (IOException e) { throw new SchemaRegistryException(e); } finally { get.releaseConnection(); this.httpClientPool.returnObject(httpClient); } if (statusCode != HttpStatus.SC_OK) { throw new SchemaRegistryException( String.format("Schema with key %s cannot be retrieved, statusCode = %d", key, statusCode)); } Schema schema; try { schema = new Schema.Parser().parse(schemaString); } catch (Throwable t) { throw new SchemaRegistryException(String.format("Schema with ID = %s cannot be parsed", key), t); } return schema; }
[ "@", "Override", "protected", "Schema", "fetchSchemaByKey", "(", "String", "key", ")", "throws", "SchemaRegistryException", "{", "String", "schemaUrl", "=", "KafkaAvroSchemaRegistry", ".", "this", ".", "url", "+", "GET_RESOURCE_BY_ID", "+", "key", ";", "GetMethod", "get", "=", "new", "GetMethod", "(", "schemaUrl", ")", ";", "int", "statusCode", ";", "String", "schemaString", ";", "HttpClient", "httpClient", "=", "this", ".", "borrowClient", "(", ")", ";", "try", "{", "statusCode", "=", "httpClient", ".", "executeMethod", "(", "get", ")", ";", "schemaString", "=", "get", ".", "getResponseBodyAsString", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "SchemaRegistryException", "(", "e", ")", ";", "}", "finally", "{", "get", ".", "releaseConnection", "(", ")", ";", "this", ".", "httpClientPool", ".", "returnObject", "(", "httpClient", ")", ";", "}", "if", "(", "statusCode", "!=", "HttpStatus", ".", "SC_OK", ")", "{", "throw", "new", "SchemaRegistryException", "(", "String", ".", "format", "(", "\"Schema with key %s cannot be retrieved, statusCode = %d\"", ",", "key", ",", "statusCode", ")", ")", ";", "}", "Schema", "schema", ";", "try", "{", "schema", "=", "new", "Schema", ".", "Parser", "(", ")", ".", "parse", "(", "schemaString", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "throw", "new", "SchemaRegistryException", "(", "String", ".", "format", "(", "\"Schema with ID = %s cannot be parsed\"", ",", "key", ")", ",", "t", ")", ";", "}", "return", "schema", ";", "}" ]
Fetch schema by key.
[ "Fetch", "schema", "by", "key", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/metrics/kafka/KafkaAvroSchemaRegistry.java#L277-L309
26,171
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/hive/HiveConfigClientUtils.java
HiveConfigClientUtils.getDatasetUri
public static String getDatasetUri(Table table) { return HIVE_DATASETS_CONFIG_PREFIX + table.getDbName() + Path.SEPARATOR + table.getTableName(); }
java
public static String getDatasetUri(Table table) { return HIVE_DATASETS_CONFIG_PREFIX + table.getDbName() + Path.SEPARATOR + table.getTableName(); }
[ "public", "static", "String", "getDatasetUri", "(", "Table", "table", ")", "{", "return", "HIVE_DATASETS_CONFIG_PREFIX", "+", "table", ".", "getDbName", "(", ")", "+", "Path", ".", "SEPARATOR", "+", "table", ".", "getTableName", "(", ")", ";", "}" ]
Get the dataset uri for a hive db and table. The uri is relative to the store uri . @param table the hive table for which a config client uri needs to be built
[ "Get", "the", "dataset", "uri", "for", "a", "hive", "db", "and", "table", ".", "The", "uri", "is", "relative", "to", "the", "store", "uri", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/hive/HiveConfigClientUtils.java#L36-L38
26,172
apache/incubator-gobblin
gobblin-core-base/src/main/java/org/apache/gobblin/writer/SequentialBasedBatchAccumulator.java
SequentialBasedBatchAccumulator.enqueue
public final Future<RecordMetadata> enqueue (D record, WriteCallback callback) throws InterruptedException { final ReentrantLock lock = this.dqLock; lock.lock(); try { BytesBoundedBatch last = dq.peekLast(); if (last != null) { Future<RecordMetadata> future = null; try { future = last.tryAppend(record, callback, this.largeMessagePolicy); } catch (RecordTooLargeException e) { // Ok if the record was too large for the current batch } if (future != null) { return future; } } // Create a new batch because previous one has no space BytesBoundedBatch batch = new BytesBoundedBatch(this.memSizeLimit, this.expireInMilliSecond); LOG.debug("Batch " + batch.getId() + " is generated"); Future<RecordMetadata> future = null; try { future = batch.tryAppend(record, callback, this.largeMessagePolicy); } catch (RecordTooLargeException e) { // If a new batch also wasn't able to accomodate the new message throw new RuntimeException("Failed due to a message that was too large", e); } // The future might be null, since the largeMessagePolicy might be set to DROP if (future == null) { assert largeMessagePolicy.equals(LargeMessagePolicy.DROP); LOG.error("Batch " + batch.getId() + " is silently marked as complete, dropping a huge record: " + record); future = Futures.immediateFuture(new RecordMetadata(0)); callback.onSuccess(WriteResponse.EMPTY); return future; } // if queue is full, we should not add more while (dq.size() >= this.capacity) { LOG.debug("Accumulator size {} is greater than capacity {}, waiting", dq.size(), this.capacity); this.notFull.await(); } dq.addLast(batch); incomplete.add(batch); this.notEmpty.signal(); return future; } finally { lock.unlock(); } }
java
public final Future<RecordMetadata> enqueue (D record, WriteCallback callback) throws InterruptedException { final ReentrantLock lock = this.dqLock; lock.lock(); try { BytesBoundedBatch last = dq.peekLast(); if (last != null) { Future<RecordMetadata> future = null; try { future = last.tryAppend(record, callback, this.largeMessagePolicy); } catch (RecordTooLargeException e) { // Ok if the record was too large for the current batch } if (future != null) { return future; } } // Create a new batch because previous one has no space BytesBoundedBatch batch = new BytesBoundedBatch(this.memSizeLimit, this.expireInMilliSecond); LOG.debug("Batch " + batch.getId() + " is generated"); Future<RecordMetadata> future = null; try { future = batch.tryAppend(record, callback, this.largeMessagePolicy); } catch (RecordTooLargeException e) { // If a new batch also wasn't able to accomodate the new message throw new RuntimeException("Failed due to a message that was too large", e); } // The future might be null, since the largeMessagePolicy might be set to DROP if (future == null) { assert largeMessagePolicy.equals(LargeMessagePolicy.DROP); LOG.error("Batch " + batch.getId() + " is silently marked as complete, dropping a huge record: " + record); future = Futures.immediateFuture(new RecordMetadata(0)); callback.onSuccess(WriteResponse.EMPTY); return future; } // if queue is full, we should not add more while (dq.size() >= this.capacity) { LOG.debug("Accumulator size {} is greater than capacity {}, waiting", dq.size(), this.capacity); this.notFull.await(); } dq.addLast(batch); incomplete.add(batch); this.notEmpty.signal(); return future; } finally { lock.unlock(); } }
[ "public", "final", "Future", "<", "RecordMetadata", ">", "enqueue", "(", "D", "record", ",", "WriteCallback", "callback", ")", "throws", "InterruptedException", "{", "final", "ReentrantLock", "lock", "=", "this", ".", "dqLock", ";", "lock", ".", "lock", "(", ")", ";", "try", "{", "BytesBoundedBatch", "last", "=", "dq", ".", "peekLast", "(", ")", ";", "if", "(", "last", "!=", "null", ")", "{", "Future", "<", "RecordMetadata", ">", "future", "=", "null", ";", "try", "{", "future", "=", "last", ".", "tryAppend", "(", "record", ",", "callback", ",", "this", ".", "largeMessagePolicy", ")", ";", "}", "catch", "(", "RecordTooLargeException", "e", ")", "{", "// Ok if the record was too large for the current batch", "}", "if", "(", "future", "!=", "null", ")", "{", "return", "future", ";", "}", "}", "// Create a new batch because previous one has no space", "BytesBoundedBatch", "batch", "=", "new", "BytesBoundedBatch", "(", "this", ".", "memSizeLimit", ",", "this", ".", "expireInMilliSecond", ")", ";", "LOG", ".", "debug", "(", "\"Batch \"", "+", "batch", ".", "getId", "(", ")", "+", "\" is generated\"", ")", ";", "Future", "<", "RecordMetadata", ">", "future", "=", "null", ";", "try", "{", "future", "=", "batch", ".", "tryAppend", "(", "record", ",", "callback", ",", "this", ".", "largeMessagePolicy", ")", ";", "}", "catch", "(", "RecordTooLargeException", "e", ")", "{", "// If a new batch also wasn't able to accomodate the new message", "throw", "new", "RuntimeException", "(", "\"Failed due to a message that was too large\"", ",", "e", ")", ";", "}", "// The future might be null, since the largeMessagePolicy might be set to DROP", "if", "(", "future", "==", "null", ")", "{", "assert", "largeMessagePolicy", ".", "equals", "(", "LargeMessagePolicy", ".", "DROP", ")", ";", "LOG", ".", "error", "(", "\"Batch \"", "+", "batch", ".", "getId", "(", ")", "+", "\" is silently marked as complete, dropping a huge record: \"", "+", "record", ")", ";", "future", "=", "Futures", ".", "immediateFuture", "(", "new", "RecordMetadata", "(", "0", ")", ")", ";", "callback", ".", "onSuccess", "(", "WriteResponse", ".", "EMPTY", ")", ";", "return", "future", ";", "}", "// if queue is full, we should not add more", "while", "(", "dq", ".", "size", "(", ")", ">=", "this", ".", "capacity", ")", "{", "LOG", ".", "debug", "(", "\"Accumulator size {} is greater than capacity {}, waiting\"", ",", "dq", ".", "size", "(", ")", ",", "this", ".", "capacity", ")", ";", "this", ".", "notFull", ".", "await", "(", ")", ";", "}", "dq", ".", "addLast", "(", "batch", ")", ";", "incomplete", ".", "add", "(", "batch", ")", ";", "this", ".", "notEmpty", ".", "signal", "(", ")", ";", "return", "future", ";", "}", "finally", "{", "lock", ".", "unlock", "(", ")", ";", "}", "}" ]
Add a data to internal deque data structure
[ "Add", "a", "data", "to", "internal", "deque", "data", "structure" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core-base/src/main/java/org/apache/gobblin/writer/SequentialBasedBatchAccumulator.java#L107-L158
26,173
apache/incubator-gobblin
gobblin-core-base/src/main/java/org/apache/gobblin/writer/SequentialBasedBatchAccumulator.java
SequentialBasedBatchAccumulator.flush
public void flush() { try { ArrayList<Batch> batches = this.incomplete.all(); int numOutstandingRecords = 0; for (Batch batch: batches) { numOutstandingRecords += batch.getRecords().size(); } LOG.debug ("Flush called on {} batches with {} records total", batches.size(), numOutstandingRecords); for (Batch batch: batches) { batch.await(); } } catch (Exception e) { LOG.error ("Error happened while flushing batches"); } }
java
public void flush() { try { ArrayList<Batch> batches = this.incomplete.all(); int numOutstandingRecords = 0; for (Batch batch: batches) { numOutstandingRecords += batch.getRecords().size(); } LOG.debug ("Flush called on {} batches with {} records total", batches.size(), numOutstandingRecords); for (Batch batch: batches) { batch.await(); } } catch (Exception e) { LOG.error ("Error happened while flushing batches"); } }
[ "public", "void", "flush", "(", ")", "{", "try", "{", "ArrayList", "<", "Batch", ">", "batches", "=", "this", ".", "incomplete", ".", "all", "(", ")", ";", "int", "numOutstandingRecords", "=", "0", ";", "for", "(", "Batch", "batch", ":", "batches", ")", "{", "numOutstandingRecords", "+=", "batch", ".", "getRecords", "(", ")", ".", "size", "(", ")", ";", "}", "LOG", ".", "debug", "(", "\"Flush called on {} batches with {} records total\"", ",", "batches", ".", "size", "(", ")", ",", "numOutstandingRecords", ")", ";", "for", "(", "Batch", "batch", ":", "batches", ")", "{", "batch", ".", "await", "(", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "error", "(", "\"Error happened while flushing batches\"", ")", ";", "}", "}" ]
This will block until all the incomplete batches are acknowledged
[ "This", "will", "block", "until", "all", "the", "incomplete", "batches", "are", "acknowledged" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core-base/src/main/java/org/apache/gobblin/writer/SequentialBasedBatchAccumulator.java#L261-L275
26,174
apache/incubator-gobblin
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/api/TopologySpec.java
TopologySpec.builder
public static TopologySpec.Builder builder(URI catalogURI, Properties topologyProps) { String name = topologyProps.getProperty(ConfigurationKeys.TOPOLOGY_NAME_KEY); String group = topologyProps.getProperty(ConfigurationKeys.TOPOLOGY_GROUP_KEY, "default"); try { URI topologyURI = new URI(catalogURI.getScheme(), catalogURI.getAuthority(), "/" + group + "/" + name, null); TopologySpec.Builder builder = new TopologySpec.Builder(topologyURI).withConfigAsProperties(topologyProps); String descr = topologyProps.getProperty(ConfigurationKeys.TOPOLOGY_DESCRIPTION_KEY, null); if (null != descr) { builder = builder.withDescription(descr); } return builder; } catch (URISyntaxException e) { throw new RuntimeException("Unable to create a TopologySpec URI: " + e, e); } }
java
public static TopologySpec.Builder builder(URI catalogURI, Properties topologyProps) { String name = topologyProps.getProperty(ConfigurationKeys.TOPOLOGY_NAME_KEY); String group = topologyProps.getProperty(ConfigurationKeys.TOPOLOGY_GROUP_KEY, "default"); try { URI topologyURI = new URI(catalogURI.getScheme(), catalogURI.getAuthority(), "/" + group + "/" + name, null); TopologySpec.Builder builder = new TopologySpec.Builder(topologyURI).withConfigAsProperties(topologyProps); String descr = topologyProps.getProperty(ConfigurationKeys.TOPOLOGY_DESCRIPTION_KEY, null); if (null != descr) { builder = builder.withDescription(descr); } return builder; } catch (URISyntaxException e) { throw new RuntimeException("Unable to create a TopologySpec URI: " + e, e); } }
[ "public", "static", "TopologySpec", ".", "Builder", "builder", "(", "URI", "catalogURI", ",", "Properties", "topologyProps", ")", "{", "String", "name", "=", "topologyProps", ".", "getProperty", "(", "ConfigurationKeys", ".", "TOPOLOGY_NAME_KEY", ")", ";", "String", "group", "=", "topologyProps", ".", "getProperty", "(", "ConfigurationKeys", ".", "TOPOLOGY_GROUP_KEY", ",", "\"default\"", ")", ";", "try", "{", "URI", "topologyURI", "=", "new", "URI", "(", "catalogURI", ".", "getScheme", "(", ")", ",", "catalogURI", ".", "getAuthority", "(", ")", ",", "\"/\"", "+", "group", "+", "\"/\"", "+", "name", ",", "null", ")", ";", "TopologySpec", ".", "Builder", "builder", "=", "new", "TopologySpec", ".", "Builder", "(", "topologyURI", ")", ".", "withConfigAsProperties", "(", "topologyProps", ")", ";", "String", "descr", "=", "topologyProps", ".", "getProperty", "(", "ConfigurationKeys", ".", "TOPOLOGY_DESCRIPTION_KEY", ",", "null", ")", ";", "if", "(", "null", "!=", "descr", ")", "{", "builder", "=", "builder", ".", "withDescription", "(", "descr", ")", ";", "}", "return", "builder", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Unable to create a TopologySpec URI: \"", "+", "e", ",", "e", ")", ";", "}", "}" ]
Creates a builder for the TopologySpec based on values in a topology properties config.
[ "Creates", "a", "builder", "for", "the", "TopologySpec", "based", "on", "values", "in", "a", "topology", "properties", "config", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/api/TopologySpec.java#L118-L135
26,175
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/converter/json/JsonSchema.java
JsonSchema.getValuesWithinDataType
public JsonSchema getValuesWithinDataType() { JsonElement element = this.getDataType().get(MAP_ITEMS_KEY); if (element.isJsonObject()) { return new JsonSchema(element.getAsJsonObject()); } if (element.isJsonArray()) { return new JsonSchema(element.getAsJsonArray()); } if (element.isJsonPrimitive()) { return buildBaseSchema(Type.valueOf(element.getAsString().toUpperCase())); } throw new UnsupportedOperationException( "Map values can only be defined using JsonObject, JsonArray or JsonPrimitive."); }
java
public JsonSchema getValuesWithinDataType() { JsonElement element = this.getDataType().get(MAP_ITEMS_KEY); if (element.isJsonObject()) { return new JsonSchema(element.getAsJsonObject()); } if (element.isJsonArray()) { return new JsonSchema(element.getAsJsonArray()); } if (element.isJsonPrimitive()) { return buildBaseSchema(Type.valueOf(element.getAsString().toUpperCase())); } throw new UnsupportedOperationException( "Map values can only be defined using JsonObject, JsonArray or JsonPrimitive."); }
[ "public", "JsonSchema", "getValuesWithinDataType", "(", ")", "{", "JsonElement", "element", "=", "this", ".", "getDataType", "(", ")", ".", "get", "(", "MAP_ITEMS_KEY", ")", ";", "if", "(", "element", ".", "isJsonObject", "(", ")", ")", "{", "return", "new", "JsonSchema", "(", "element", ".", "getAsJsonObject", "(", ")", ")", ";", "}", "if", "(", "element", ".", "isJsonArray", "(", ")", ")", "{", "return", "new", "JsonSchema", "(", "element", ".", "getAsJsonArray", "(", ")", ")", ";", "}", "if", "(", "element", ".", "isJsonPrimitive", "(", ")", ")", "{", "return", "buildBaseSchema", "(", "Type", ".", "valueOf", "(", "element", ".", "getAsString", "(", ")", ".", "toUpperCase", "(", ")", ")", ")", ";", "}", "throw", "new", "UnsupportedOperationException", "(", "\"Map values can only be defined using JsonObject, JsonArray or JsonPrimitive.\"", ")", ";", "}" ]
Fetches dataType.values from the JsonObject @return
[ "Fetches", "dataType", ".", "values", "from", "the", "JsonObject" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/converter/json/JsonSchema.java#L197-L210
26,176
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/converter/json/JsonSchema.java
JsonSchema.getTypeOfArrayItems
public Type getTypeOfArrayItems() throws DataConversionException { JsonSchema arrayValues = getItemsWithinDataType(); if (arrayValues == null) { throw new DataConversionException("Array types only allow values as primitive, null or JsonObject"); } return arrayValues.getType(); }
java
public Type getTypeOfArrayItems() throws DataConversionException { JsonSchema arrayValues = getItemsWithinDataType(); if (arrayValues == null) { throw new DataConversionException("Array types only allow values as primitive, null or JsonObject"); } return arrayValues.getType(); }
[ "public", "Type", "getTypeOfArrayItems", "(", ")", "throws", "DataConversionException", "{", "JsonSchema", "arrayValues", "=", "getItemsWithinDataType", "(", ")", ";", "if", "(", "arrayValues", "==", "null", ")", "{", "throw", "new", "DataConversionException", "(", "\"Array types only allow values as primitive, null or JsonObject\"", ")", ";", "}", "return", "arrayValues", ".", "getType", "(", ")", ";", "}" ]
Fetches the nested or primitive array items type from schema. @return @throws DataConversionException
[ "Fetches", "the", "nested", "or", "primitive", "array", "items", "type", "from", "schema", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/converter/json/JsonSchema.java#L232-L239
26,177
apache/incubator-gobblin
gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java
JdbcExtractor.getTargetColumnName
private String getTargetColumnName(String sourceColumnName, String alias) { String targetColumnName = alias; Schema obj = this.getMetadataColumnMap().get(sourceColumnName.toLowerCase()); if (obj == null) { targetColumnName = (targetColumnName == null ? "unknown" + this.unknownColumnCounter : targetColumnName); this.unknownColumnCounter++; } else { targetColumnName = (StringUtils.isNotBlank(targetColumnName) ? targetColumnName : sourceColumnName); } targetColumnName = this.toCase(targetColumnName); return Utils.escapeSpecialCharacters(targetColumnName, ConfigurationKeys.ESCAPE_CHARS_IN_COLUMN_NAME, "_"); }
java
private String getTargetColumnName(String sourceColumnName, String alias) { String targetColumnName = alias; Schema obj = this.getMetadataColumnMap().get(sourceColumnName.toLowerCase()); if (obj == null) { targetColumnName = (targetColumnName == null ? "unknown" + this.unknownColumnCounter : targetColumnName); this.unknownColumnCounter++; } else { targetColumnName = (StringUtils.isNotBlank(targetColumnName) ? targetColumnName : sourceColumnName); } targetColumnName = this.toCase(targetColumnName); return Utils.escapeSpecialCharacters(targetColumnName, ConfigurationKeys.ESCAPE_CHARS_IN_COLUMN_NAME, "_"); }
[ "private", "String", "getTargetColumnName", "(", "String", "sourceColumnName", ",", "String", "alias", ")", "{", "String", "targetColumnName", "=", "alias", ";", "Schema", "obj", "=", "this", ".", "getMetadataColumnMap", "(", ")", ".", "get", "(", "sourceColumnName", ".", "toLowerCase", "(", ")", ")", ";", "if", "(", "obj", "==", "null", ")", "{", "targetColumnName", "=", "(", "targetColumnName", "==", "null", "?", "\"unknown\"", "+", "this", ".", "unknownColumnCounter", ":", "targetColumnName", ")", ";", "this", ".", "unknownColumnCounter", "++", ";", "}", "else", "{", "targetColumnName", "=", "(", "StringUtils", ".", "isNotBlank", "(", "targetColumnName", ")", "?", "targetColumnName", ":", "sourceColumnName", ")", ";", "}", "targetColumnName", "=", "this", ".", "toCase", "(", "targetColumnName", ")", ";", "return", "Utils", ".", "escapeSpecialCharacters", "(", "targetColumnName", ",", "ConfigurationKeys", ".", "ESCAPE_CHARS_IN_COLUMN_NAME", ",", "\"_\"", ")", ";", "}" ]
Get target column name if column is not found in metadata, then name it as unknown column If alias is not found, target column is nothing but source column @param sourceColumnName @param alias @return targetColumnName
[ "Get", "target", "column", "name", "if", "column", "is", "not", "found", "in", "metadata", "then", "name", "it", "as", "unknown", "column", "If", "alias", "is", "not", "found", "target", "column", "is", "nothing", "but", "source", "column" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java#L473-L484
26,178
apache/incubator-gobblin
gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java
JdbcExtractor.buildMetadataColumnMap
private void buildMetadataColumnMap(JsonArray array) { if (array != null) { for (JsonElement columnElement : array) { Schema schemaObj = gson.fromJson(columnElement, Schema.class); String columnName = schemaObj.getColumnName(); this.metadataColumnMap.put(columnName.toLowerCase(), schemaObj); this.metadataColumnList.add(columnName.toLowerCase()); } } }
java
private void buildMetadataColumnMap(JsonArray array) { if (array != null) { for (JsonElement columnElement : array) { Schema schemaObj = gson.fromJson(columnElement, Schema.class); String columnName = schemaObj.getColumnName(); this.metadataColumnMap.put(columnName.toLowerCase(), schemaObj); this.metadataColumnList.add(columnName.toLowerCase()); } } }
[ "private", "void", "buildMetadataColumnMap", "(", "JsonArray", "array", ")", "{", "if", "(", "array", "!=", "null", ")", "{", "for", "(", "JsonElement", "columnElement", ":", "array", ")", "{", "Schema", "schemaObj", "=", "gson", ".", "fromJson", "(", "columnElement", ",", "Schema", ".", "class", ")", ";", "String", "columnName", "=", "schemaObj", ".", "getColumnName", "(", ")", ";", "this", ".", "metadataColumnMap", ".", "put", "(", "columnName", ".", "toLowerCase", "(", ")", ",", "schemaObj", ")", ";", "this", ".", "metadataColumnList", ".", "add", "(", "columnName", ".", "toLowerCase", "(", ")", ")", ";", "}", "}", "}" ]
Build metadata column map with column name and column schema object. Build metadata column list with list columns in metadata @param array Schema of all columns
[ "Build", "metadata", "column", "map", "with", "column", "name", "and", "column", "schema", "object", ".", "Build", "metadata", "column", "list", "with", "list", "columns", "in", "metadata" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java#L492-L501
26,179
apache/incubator-gobblin
gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java
JdbcExtractor.updateDeltaFieldConfig
private void updateDeltaFieldConfig(String srcColumnName, String tgtColumnName) { if (this.workUnitState.contains(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY)) { String watermarkCol = this.workUnitState.getProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY); this.workUnitState.setProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY, watermarkCol.replaceAll(srcColumnName, tgtColumnName)); } }
java
private void updateDeltaFieldConfig(String srcColumnName, String tgtColumnName) { if (this.workUnitState.contains(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY)) { String watermarkCol = this.workUnitState.getProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY); this.workUnitState.setProp(ConfigurationKeys.EXTRACT_DELTA_FIELDS_KEY, watermarkCol.replaceAll(srcColumnName, tgtColumnName)); } }
[ "private", "void", "updateDeltaFieldConfig", "(", "String", "srcColumnName", ",", "String", "tgtColumnName", ")", "{", "if", "(", "this", ".", "workUnitState", ".", "contains", "(", "ConfigurationKeys", ".", "EXTRACT_DELTA_FIELDS_KEY", ")", ")", "{", "String", "watermarkCol", "=", "this", ".", "workUnitState", ".", "getProp", "(", "ConfigurationKeys", ".", "EXTRACT_DELTA_FIELDS_KEY", ")", ";", "this", ".", "workUnitState", ".", "setProp", "(", "ConfigurationKeys", ".", "EXTRACT_DELTA_FIELDS_KEY", ",", "watermarkCol", ".", "replaceAll", "(", "srcColumnName", ",", "tgtColumnName", ")", ")", ";", "}", "}" ]
Update water mark column property if there is an alias defined in query @param srcColumnName source column name @param tgtColumnName target column name
[ "Update", "water", "mark", "column", "property", "if", "there", "is", "an", "alias", "defined", "in", "query" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java#L509-L515
26,180
apache/incubator-gobblin
gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java
JdbcExtractor.updatePrimaryKeyConfig
private void updatePrimaryKeyConfig(String srcColumnName, String tgtColumnName) { if (this.workUnitState.contains(ConfigurationKeys.EXTRACT_PRIMARY_KEY_FIELDS_KEY)) { String primarykey = this.workUnitState.getProp(ConfigurationKeys.EXTRACT_PRIMARY_KEY_FIELDS_KEY); this.workUnitState.setProp(ConfigurationKeys.EXTRACT_PRIMARY_KEY_FIELDS_KEY, primarykey.replaceAll(srcColumnName, tgtColumnName)); } }
java
private void updatePrimaryKeyConfig(String srcColumnName, String tgtColumnName) { if (this.workUnitState.contains(ConfigurationKeys.EXTRACT_PRIMARY_KEY_FIELDS_KEY)) { String primarykey = this.workUnitState.getProp(ConfigurationKeys.EXTRACT_PRIMARY_KEY_FIELDS_KEY); this.workUnitState.setProp(ConfigurationKeys.EXTRACT_PRIMARY_KEY_FIELDS_KEY, primarykey.replaceAll(srcColumnName, tgtColumnName)); } }
[ "private", "void", "updatePrimaryKeyConfig", "(", "String", "srcColumnName", ",", "String", "tgtColumnName", ")", "{", "if", "(", "this", ".", "workUnitState", ".", "contains", "(", "ConfigurationKeys", ".", "EXTRACT_PRIMARY_KEY_FIELDS_KEY", ")", ")", "{", "String", "primarykey", "=", "this", ".", "workUnitState", ".", "getProp", "(", "ConfigurationKeys", ".", "EXTRACT_PRIMARY_KEY_FIELDS_KEY", ")", ";", "this", ".", "workUnitState", ".", "setProp", "(", "ConfigurationKeys", ".", "EXTRACT_PRIMARY_KEY_FIELDS_KEY", ",", "primarykey", ".", "replaceAll", "(", "srcColumnName", ",", "tgtColumnName", ")", ")", ";", "}", "}" ]
Update primary key column property if there is an alias defined in query @param srcColumnName source column name @param tgtColumnName target column name
[ "Update", "primary", "key", "column", "property", "if", "there", "is", "an", "alias", "defined", "in", "query" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java#L523-L529
26,181
apache/incubator-gobblin
gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java
JdbcExtractor.parseInputQuery
private void parseInputQuery(String query) { List<String> projectedColumns = new ArrayList<>(); if (StringUtils.isNotBlank(query)) { String queryLowerCase = query.toLowerCase(); int startIndex = queryLowerCase.indexOf("select ") + 7; int endIndex = queryLowerCase.indexOf(" from "); if (startIndex >= 0 && endIndex >= 0) { String columnProjection = query.substring(startIndex, endIndex); this.setInputColumnProjection(columnProjection); // parse the select list StringBuffer sb = new StringBuffer(); int bracketCount = 0; for (int i = 0; i < columnProjection.length(); i++) { char c = columnProjection.charAt(i); if (c == '(') { bracketCount++; } if (c == ')') { bracketCount--; } if (bracketCount != 0) { sb.append(c); } else { if (c != ',') { sb.append(c); } else { projectedColumns.add(sb.toString()); sb = new StringBuffer(); } } } projectedColumns.add(sb.toString()); } } if (this.isSelectAllColumns()) { List<String> columnList = this.getMetadataColumnList(); for (String columnName : columnList) { ColumnAttributes col = new ColumnAttributes(); col.setColumnName(columnName); col.setAliasName(columnName); col.setSourceColumnName(columnName); this.addToColumnAliasMap(col); } } else { for (String projectedColumn : projectedColumns) { String column = projectedColumn.trim(); String alias = null; String sourceColumn = column; int spaceOccurences = StringUtils.countMatches(column.trim(), " "); if (spaceOccurences > 0) { // separate column and alias if they are separated by "as" // or space int lastSpaceIndex = column.toLowerCase().lastIndexOf(" as "); sourceColumn = column.substring(0, lastSpaceIndex); alias = column.substring(lastSpaceIndex + 4); } // extract column name if projection has table name in it String columnName = sourceColumn; if (sourceColumn.contains(".")) { columnName = sourceColumn.substring(sourceColumn.indexOf(".") + 1); } ColumnAttributes col = new ColumnAttributes(); col.setColumnName(columnName); col.setAliasName(alias); col.setSourceColumnName(sourceColumn); this.addToColumnAliasMap(col); } } }
java
private void parseInputQuery(String query) { List<String> projectedColumns = new ArrayList<>(); if (StringUtils.isNotBlank(query)) { String queryLowerCase = query.toLowerCase(); int startIndex = queryLowerCase.indexOf("select ") + 7; int endIndex = queryLowerCase.indexOf(" from "); if (startIndex >= 0 && endIndex >= 0) { String columnProjection = query.substring(startIndex, endIndex); this.setInputColumnProjection(columnProjection); // parse the select list StringBuffer sb = new StringBuffer(); int bracketCount = 0; for (int i = 0; i < columnProjection.length(); i++) { char c = columnProjection.charAt(i); if (c == '(') { bracketCount++; } if (c == ')') { bracketCount--; } if (bracketCount != 0) { sb.append(c); } else { if (c != ',') { sb.append(c); } else { projectedColumns.add(sb.toString()); sb = new StringBuffer(); } } } projectedColumns.add(sb.toString()); } } if (this.isSelectAllColumns()) { List<String> columnList = this.getMetadataColumnList(); for (String columnName : columnList) { ColumnAttributes col = new ColumnAttributes(); col.setColumnName(columnName); col.setAliasName(columnName); col.setSourceColumnName(columnName); this.addToColumnAliasMap(col); } } else { for (String projectedColumn : projectedColumns) { String column = projectedColumn.trim(); String alias = null; String sourceColumn = column; int spaceOccurences = StringUtils.countMatches(column.trim(), " "); if (spaceOccurences > 0) { // separate column and alias if they are separated by "as" // or space int lastSpaceIndex = column.toLowerCase().lastIndexOf(" as "); sourceColumn = column.substring(0, lastSpaceIndex); alias = column.substring(lastSpaceIndex + 4); } // extract column name if projection has table name in it String columnName = sourceColumn; if (sourceColumn.contains(".")) { columnName = sourceColumn.substring(sourceColumn.indexOf(".") + 1); } ColumnAttributes col = new ColumnAttributes(); col.setColumnName(columnName); col.setAliasName(alias); col.setSourceColumnName(sourceColumn); this.addToColumnAliasMap(col); } } }
[ "private", "void", "parseInputQuery", "(", "String", "query", ")", "{", "List", "<", "String", ">", "projectedColumns", "=", "new", "ArrayList", "<>", "(", ")", ";", "if", "(", "StringUtils", ".", "isNotBlank", "(", "query", ")", ")", "{", "String", "queryLowerCase", "=", "query", ".", "toLowerCase", "(", ")", ";", "int", "startIndex", "=", "queryLowerCase", ".", "indexOf", "(", "\"select \"", ")", "+", "7", ";", "int", "endIndex", "=", "queryLowerCase", ".", "indexOf", "(", "\" from \"", ")", ";", "if", "(", "startIndex", ">=", "0", "&&", "endIndex", ">=", "0", ")", "{", "String", "columnProjection", "=", "query", ".", "substring", "(", "startIndex", ",", "endIndex", ")", ";", "this", ".", "setInputColumnProjection", "(", "columnProjection", ")", ";", "// parse the select list", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", ")", ";", "int", "bracketCount", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "columnProjection", ".", "length", "(", ")", ";", "i", "++", ")", "{", "char", "c", "=", "columnProjection", ".", "charAt", "(", "i", ")", ";", "if", "(", "c", "==", "'", "'", ")", "{", "bracketCount", "++", ";", "}", "if", "(", "c", "==", "'", "'", ")", "{", "bracketCount", "--", ";", "}", "if", "(", "bracketCount", "!=", "0", ")", "{", "sb", ".", "append", "(", "c", ")", ";", "}", "else", "{", "if", "(", "c", "!=", "'", "'", ")", "{", "sb", ".", "append", "(", "c", ")", ";", "}", "else", "{", "projectedColumns", ".", "add", "(", "sb", ".", "toString", "(", ")", ")", ";", "sb", "=", "new", "StringBuffer", "(", ")", ";", "}", "}", "}", "projectedColumns", ".", "add", "(", "sb", ".", "toString", "(", ")", ")", ";", "}", "}", "if", "(", "this", ".", "isSelectAllColumns", "(", ")", ")", "{", "List", "<", "String", ">", "columnList", "=", "this", ".", "getMetadataColumnList", "(", ")", ";", "for", "(", "String", "columnName", ":", "columnList", ")", "{", "ColumnAttributes", "col", "=", "new", "ColumnAttributes", "(", ")", ";", "col", ".", "setColumnName", "(", "columnName", ")", ";", "col", ".", "setAliasName", "(", "columnName", ")", ";", "col", ".", "setSourceColumnName", "(", "columnName", ")", ";", "this", ".", "addToColumnAliasMap", "(", "col", ")", ";", "}", "}", "else", "{", "for", "(", "String", "projectedColumn", ":", "projectedColumns", ")", "{", "String", "column", "=", "projectedColumn", ".", "trim", "(", ")", ";", "String", "alias", "=", "null", ";", "String", "sourceColumn", "=", "column", ";", "int", "spaceOccurences", "=", "StringUtils", ".", "countMatches", "(", "column", ".", "trim", "(", ")", ",", "\" \"", ")", ";", "if", "(", "spaceOccurences", ">", "0", ")", "{", "// separate column and alias if they are separated by \"as\"", "// or space", "int", "lastSpaceIndex", "=", "column", ".", "toLowerCase", "(", ")", ".", "lastIndexOf", "(", "\" as \"", ")", ";", "sourceColumn", "=", "column", ".", "substring", "(", "0", ",", "lastSpaceIndex", ")", ";", "alias", "=", "column", ".", "substring", "(", "lastSpaceIndex", "+", "4", ")", ";", "}", "// extract column name if projection has table name in it", "String", "columnName", "=", "sourceColumn", ";", "if", "(", "sourceColumn", ".", "contains", "(", "\".\"", ")", ")", "{", "columnName", "=", "sourceColumn", ".", "substring", "(", "sourceColumn", ".", "indexOf", "(", "\".\"", ")", "+", "1", ")", ";", "}", "ColumnAttributes", "col", "=", "new", "ColumnAttributes", "(", ")", ";", "col", ".", "setColumnName", "(", "columnName", ")", ";", "col", ".", "setAliasName", "(", "alias", ")", ";", "col", ".", "setSourceColumnName", "(", "sourceColumn", ")", ";", "this", ".", "addToColumnAliasMap", "(", "col", ")", ";", "}", "}", "}" ]
Parse query provided in pull file Set input column projection - column projection in the input query Set columnAlias map - column and its alias mentioned in input query @param query input query
[ "Parse", "query", "provided", "in", "pull", "file", "Set", "input", "column", "projection", "-", "column", "projection", "in", "the", "input", "query", "Set", "columnAlias", "map", "-", "column", "and", "its", "alias", "mentioned", "in", "input", "query" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java#L551-L624
26,182
apache/incubator-gobblin
gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java
JdbcExtractor.executeSql
private CommandOutput<?, ?> executeSql(List<Command> cmds) { String query = null; int fetchSize = 0; for (Command cmd : cmds) { if (cmd instanceof JdbcCommand) { JdbcCommandType type = (JdbcCommandType) cmd.getCommandType(); switch (type) { case QUERY: query = cmd.getParams().get(0); break; case FETCHSIZE: fetchSize = Integer.parseInt(cmd.getParams().get(0)); break; default: this.log.error("Command " + type.toString() + " not recognized"); break; } } } this.log.info("Executing query:" + query); ResultSet resultSet = null; try { this.jdbcSource = createJdbcSource(); if (this.dataConnection == null) { this.dataConnection = this.jdbcSource.getConnection(); } Statement statement = this.dataConnection.createStatement(); if (fetchSize != 0 && this.getExpectedRecordCount() > 2000) { statement.setFetchSize(fetchSize); } final boolean status = statement.execute(query); if (status == false) { this.log.error("Failed to execute sql:" + query); } resultSet = statement.getResultSet(); } catch (Exception e) { this.log.error("Failed to execute sql:" + query + " ;error-" + e.getMessage(), e); } CommandOutput<JdbcCommand, ResultSet> output = new JdbcCommandOutput(); output.put((JdbcCommand) cmds.get(0), resultSet); return output; }
java
private CommandOutput<?, ?> executeSql(List<Command> cmds) { String query = null; int fetchSize = 0; for (Command cmd : cmds) { if (cmd instanceof JdbcCommand) { JdbcCommandType type = (JdbcCommandType) cmd.getCommandType(); switch (type) { case QUERY: query = cmd.getParams().get(0); break; case FETCHSIZE: fetchSize = Integer.parseInt(cmd.getParams().get(0)); break; default: this.log.error("Command " + type.toString() + " not recognized"); break; } } } this.log.info("Executing query:" + query); ResultSet resultSet = null; try { this.jdbcSource = createJdbcSource(); if (this.dataConnection == null) { this.dataConnection = this.jdbcSource.getConnection(); } Statement statement = this.dataConnection.createStatement(); if (fetchSize != 0 && this.getExpectedRecordCount() > 2000) { statement.setFetchSize(fetchSize); } final boolean status = statement.execute(query); if (status == false) { this.log.error("Failed to execute sql:" + query); } resultSet = statement.getResultSet(); } catch (Exception e) { this.log.error("Failed to execute sql:" + query + " ;error-" + e.getMessage(), e); } CommandOutput<JdbcCommand, ResultSet> output = new JdbcCommandOutput(); output.put((JdbcCommand) cmds.get(0), resultSet); return output; }
[ "private", "CommandOutput", "<", "?", ",", "?", ">", "executeSql", "(", "List", "<", "Command", ">", "cmds", ")", "{", "String", "query", "=", "null", ";", "int", "fetchSize", "=", "0", ";", "for", "(", "Command", "cmd", ":", "cmds", ")", "{", "if", "(", "cmd", "instanceof", "JdbcCommand", ")", "{", "JdbcCommandType", "type", "=", "(", "JdbcCommandType", ")", "cmd", ".", "getCommandType", "(", ")", ";", "switch", "(", "type", ")", "{", "case", "QUERY", ":", "query", "=", "cmd", ".", "getParams", "(", ")", ".", "get", "(", "0", ")", ";", "break", ";", "case", "FETCHSIZE", ":", "fetchSize", "=", "Integer", ".", "parseInt", "(", "cmd", ".", "getParams", "(", ")", ".", "get", "(", "0", ")", ")", ";", "break", ";", "default", ":", "this", ".", "log", ".", "error", "(", "\"Command \"", "+", "type", ".", "toString", "(", ")", "+", "\" not recognized\"", ")", ";", "break", ";", "}", "}", "}", "this", ".", "log", ".", "info", "(", "\"Executing query:\"", "+", "query", ")", ";", "ResultSet", "resultSet", "=", "null", ";", "try", "{", "this", ".", "jdbcSource", "=", "createJdbcSource", "(", ")", ";", "if", "(", "this", ".", "dataConnection", "==", "null", ")", "{", "this", ".", "dataConnection", "=", "this", ".", "jdbcSource", ".", "getConnection", "(", ")", ";", "}", "Statement", "statement", "=", "this", ".", "dataConnection", ".", "createStatement", "(", ")", ";", "if", "(", "fetchSize", "!=", "0", "&&", "this", ".", "getExpectedRecordCount", "(", ")", ">", "2000", ")", "{", "statement", ".", "setFetchSize", "(", "fetchSize", ")", ";", "}", "final", "boolean", "status", "=", "statement", ".", "execute", "(", "query", ")", ";", "if", "(", "status", "==", "false", ")", "{", "this", ".", "log", ".", "error", "(", "\"Failed to execute sql:\"", "+", "query", ")", ";", "}", "resultSet", "=", "statement", ".", "getResultSet", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "this", ".", "log", ".", "error", "(", "\"Failed to execute sql:\"", "+", "query", "+", "\" ;error-\"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "CommandOutput", "<", "JdbcCommand", ",", "ResultSet", ">", "output", "=", "new", "JdbcCommandOutput", "(", ")", ";", "output", ".", "put", "(", "(", "JdbcCommand", ")", "cmds", ".", "get", "(", "0", ")", ",", "resultSet", ")", ";", "return", "output", ";", "}" ]
Execute query using JDBC simple Statement Set fetch size @param cmds commands - query, fetch size @return JDBC ResultSet @throws Exception
[ "Execute", "query", "using", "JDBC", "simple", "Statement", "Set", "fetch", "size" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java#L633-L678
26,183
apache/incubator-gobblin
gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java
JdbcExtractor.executePreparedSql
private CommandOutput<?, ?> executePreparedSql(List<Command> cmds) { String query = null; List<String> queryParameters = null; int fetchSize = 0; for (Command cmd : cmds) { if (cmd instanceof JdbcCommand) { JdbcCommandType type = (JdbcCommandType) cmd.getCommandType(); switch (type) { case QUERY: query = cmd.getParams().get(0); break; case QUERYPARAMS: queryParameters = cmd.getParams(); break; case FETCHSIZE: fetchSize = Integer.parseInt(cmd.getParams().get(0)); break; default: this.log.error("Command " + type.toString() + " not recognized"); break; } } } this.log.info("Executing query:" + query); ResultSet resultSet = null; try { this.jdbcSource = createJdbcSource(); if (this.dataConnection == null) { this.dataConnection = this.jdbcSource.getConnection(); } PreparedStatement statement = this.dataConnection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); int parameterPosition = 1; if (queryParameters != null && queryParameters.size() > 0) { for (String parameter : queryParameters) { statement.setString(parameterPosition, parameter); parameterPosition++; } } if (fetchSize != 0) { statement.setFetchSize(fetchSize); } final boolean status = statement.execute(); if (status == false) { this.log.error("Failed to execute sql:" + query); } resultSet = statement.getResultSet(); } catch (Exception e) { this.log.error("Failed to execute sql:" + query + " ;error-" + e.getMessage(), e); } CommandOutput<JdbcCommand, ResultSet> output = new JdbcCommandOutput(); output.put((JdbcCommand) cmds.get(0), resultSet); return output; }
java
private CommandOutput<?, ?> executePreparedSql(List<Command> cmds) { String query = null; List<String> queryParameters = null; int fetchSize = 0; for (Command cmd : cmds) { if (cmd instanceof JdbcCommand) { JdbcCommandType type = (JdbcCommandType) cmd.getCommandType(); switch (type) { case QUERY: query = cmd.getParams().get(0); break; case QUERYPARAMS: queryParameters = cmd.getParams(); break; case FETCHSIZE: fetchSize = Integer.parseInt(cmd.getParams().get(0)); break; default: this.log.error("Command " + type.toString() + " not recognized"); break; } } } this.log.info("Executing query:" + query); ResultSet resultSet = null; try { this.jdbcSource = createJdbcSource(); if (this.dataConnection == null) { this.dataConnection = this.jdbcSource.getConnection(); } PreparedStatement statement = this.dataConnection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); int parameterPosition = 1; if (queryParameters != null && queryParameters.size() > 0) { for (String parameter : queryParameters) { statement.setString(parameterPosition, parameter); parameterPosition++; } } if (fetchSize != 0) { statement.setFetchSize(fetchSize); } final boolean status = statement.execute(); if (status == false) { this.log.error("Failed to execute sql:" + query); } resultSet = statement.getResultSet(); } catch (Exception e) { this.log.error("Failed to execute sql:" + query + " ;error-" + e.getMessage(), e); } CommandOutput<JdbcCommand, ResultSet> output = new JdbcCommandOutput(); output.put((JdbcCommand) cmds.get(0), resultSet); return output; }
[ "private", "CommandOutput", "<", "?", ",", "?", ">", "executePreparedSql", "(", "List", "<", "Command", ">", "cmds", ")", "{", "String", "query", "=", "null", ";", "List", "<", "String", ">", "queryParameters", "=", "null", ";", "int", "fetchSize", "=", "0", ";", "for", "(", "Command", "cmd", ":", "cmds", ")", "{", "if", "(", "cmd", "instanceof", "JdbcCommand", ")", "{", "JdbcCommandType", "type", "=", "(", "JdbcCommandType", ")", "cmd", ".", "getCommandType", "(", ")", ";", "switch", "(", "type", ")", "{", "case", "QUERY", ":", "query", "=", "cmd", ".", "getParams", "(", ")", ".", "get", "(", "0", ")", ";", "break", ";", "case", "QUERYPARAMS", ":", "queryParameters", "=", "cmd", ".", "getParams", "(", ")", ";", "break", ";", "case", "FETCHSIZE", ":", "fetchSize", "=", "Integer", ".", "parseInt", "(", "cmd", ".", "getParams", "(", ")", ".", "get", "(", "0", ")", ")", ";", "break", ";", "default", ":", "this", ".", "log", ".", "error", "(", "\"Command \"", "+", "type", ".", "toString", "(", ")", "+", "\" not recognized\"", ")", ";", "break", ";", "}", "}", "}", "this", ".", "log", ".", "info", "(", "\"Executing query:\"", "+", "query", ")", ";", "ResultSet", "resultSet", "=", "null", ";", "try", "{", "this", ".", "jdbcSource", "=", "createJdbcSource", "(", ")", ";", "if", "(", "this", ".", "dataConnection", "==", "null", ")", "{", "this", ".", "dataConnection", "=", "this", ".", "jdbcSource", ".", "getConnection", "(", ")", ";", "}", "PreparedStatement", "statement", "=", "this", ".", "dataConnection", ".", "prepareStatement", "(", "query", ",", "ResultSet", ".", "TYPE_FORWARD_ONLY", ",", "ResultSet", ".", "CONCUR_READ_ONLY", ")", ";", "int", "parameterPosition", "=", "1", ";", "if", "(", "queryParameters", "!=", "null", "&&", "queryParameters", ".", "size", "(", ")", ">", "0", ")", "{", "for", "(", "String", "parameter", ":", "queryParameters", ")", "{", "statement", ".", "setString", "(", "parameterPosition", ",", "parameter", ")", ";", "parameterPosition", "++", ";", "}", "}", "if", "(", "fetchSize", "!=", "0", ")", "{", "statement", ".", "setFetchSize", "(", "fetchSize", ")", ";", "}", "final", "boolean", "status", "=", "statement", ".", "execute", "(", ")", ";", "if", "(", "status", "==", "false", ")", "{", "this", ".", "log", ".", "error", "(", "\"Failed to execute sql:\"", "+", "query", ")", ";", "}", "resultSet", "=", "statement", ".", "getResultSet", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "this", ".", "log", ".", "error", "(", "\"Failed to execute sql:\"", "+", "query", "+", "\" ;error-\"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "CommandOutput", "<", "JdbcCommand", ",", "ResultSet", ">", "output", "=", "new", "JdbcCommandOutput", "(", ")", ";", "output", ".", "put", "(", "(", "JdbcCommand", ")", "cmds", ".", "get", "(", "0", ")", ",", "resultSet", ")", ";", "return", "output", ";", "}" ]
Execute query using JDBC PreparedStatement to pass query parameters Set fetch size @param cmds commands - query, fetch size, query parameters @return JDBC ResultSet @throws Exception
[ "Execute", "query", "using", "JDBC", "PreparedStatement", "to", "pass", "query", "parameters", "Set", "fetch", "size" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java#L688-L747
26,184
apache/incubator-gobblin
gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java
JdbcExtractor.createJdbcSource
protected JdbcProvider createJdbcSource() { String driver = this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_DRIVER); String userName = this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_USERNAME); String password = PasswordManager.getInstance(this.workUnitState) .readPassword(this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_PASSWORD)); String connectionUrl = this.getConnectionUrl(); String proxyHost = this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_USE_PROXY_URL); int proxyPort = this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_USE_PROXY_PORT) != null ? this.workUnitState.getPropAsInt(ConfigurationKeys.SOURCE_CONN_USE_PROXY_PORT) : -1; if (this.jdbcSource == null || this.jdbcSource.isClosed()) { this.jdbcSource = new JdbcProvider(driver, connectionUrl, userName, password, 1, this.getTimeOut(), "DEFAULT", proxyHost, proxyPort); return this.jdbcSource; } else { return this.jdbcSource; } }
java
protected JdbcProvider createJdbcSource() { String driver = this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_DRIVER); String userName = this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_USERNAME); String password = PasswordManager.getInstance(this.workUnitState) .readPassword(this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_PASSWORD)); String connectionUrl = this.getConnectionUrl(); String proxyHost = this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_USE_PROXY_URL); int proxyPort = this.workUnitState.getProp(ConfigurationKeys.SOURCE_CONN_USE_PROXY_PORT) != null ? this.workUnitState.getPropAsInt(ConfigurationKeys.SOURCE_CONN_USE_PROXY_PORT) : -1; if (this.jdbcSource == null || this.jdbcSource.isClosed()) { this.jdbcSource = new JdbcProvider(driver, connectionUrl, userName, password, 1, this.getTimeOut(), "DEFAULT", proxyHost, proxyPort); return this.jdbcSource; } else { return this.jdbcSource; } }
[ "protected", "JdbcProvider", "createJdbcSource", "(", ")", "{", "String", "driver", "=", "this", ".", "workUnitState", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_CONN_DRIVER", ")", ";", "String", "userName", "=", "this", ".", "workUnitState", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_CONN_USERNAME", ")", ";", "String", "password", "=", "PasswordManager", ".", "getInstance", "(", "this", ".", "workUnitState", ")", ".", "readPassword", "(", "this", ".", "workUnitState", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_CONN_PASSWORD", ")", ")", ";", "String", "connectionUrl", "=", "this", ".", "getConnectionUrl", "(", ")", ";", "String", "proxyHost", "=", "this", ".", "workUnitState", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_CONN_USE_PROXY_URL", ")", ";", "int", "proxyPort", "=", "this", ".", "workUnitState", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_CONN_USE_PROXY_PORT", ")", "!=", "null", "?", "this", ".", "workUnitState", ".", "getPropAsInt", "(", "ConfigurationKeys", ".", "SOURCE_CONN_USE_PROXY_PORT", ")", ":", "-", "1", ";", "if", "(", "this", ".", "jdbcSource", "==", "null", "||", "this", ".", "jdbcSource", ".", "isClosed", "(", ")", ")", "{", "this", ".", "jdbcSource", "=", "new", "JdbcProvider", "(", "driver", ",", "connectionUrl", ",", "userName", ",", "password", ",", "1", ",", "this", ".", "getTimeOut", "(", ")", ",", "\"DEFAULT\"", ",", "proxyHost", ",", "proxyPort", ")", ";", "return", "this", ".", "jdbcSource", ";", "}", "else", "{", "return", "this", ".", "jdbcSource", ";", "}", "}" ]
Create JDBC source to get connection @return JDBCSource
[ "Create", "JDBC", "source", "to", "get", "connection" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java#L754-L772
26,185
apache/incubator-gobblin
gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java
JdbcExtractor.concatPredicates
protected String concatPredicates(List<Predicate> predicateList) { List<String> conditions = new ArrayList<>(); for (Predicate predicate : predicateList) { conditions.add(predicate.getCondition()); } return Joiner.on(" and ").skipNulls().join(conditions); }
java
protected String concatPredicates(List<Predicate> predicateList) { List<String> conditions = new ArrayList<>(); for (Predicate predicate : predicateList) { conditions.add(predicate.getCondition()); } return Joiner.on(" and ").skipNulls().join(conditions); }
[ "protected", "String", "concatPredicates", "(", "List", "<", "Predicate", ">", "predicateList", ")", "{", "List", "<", "String", ">", "conditions", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "Predicate", "predicate", ":", "predicateList", ")", "{", "conditions", ".", "add", "(", "predicate", ".", "getCondition", "(", ")", ")", ";", "}", "return", "Joiner", ".", "on", "(", "\" and \"", ")", ".", "skipNulls", "(", ")", ".", "join", "(", "conditions", ")", ";", "}" ]
Concatenate all predicates with "and" clause @param predicateList list of predicate(filter) conditions @return predicate
[ "Concatenate", "all", "predicates", "with", "and", "clause" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java#L1087-L1093
26,186
apache/incubator-gobblin
gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java
JdbcExtractor.getDefaultWatermark
private JsonObject getDefaultWatermark() { Schema schema = new Schema(); String dataType; String columnName = "derivedwatermarkcolumn"; schema.setColumnName(columnName); WatermarkType wmType = WatermarkType.valueOf( this.workUnitState.getProp(ConfigurationKeys.SOURCE_QUERYBASED_WATERMARK_TYPE, "TIMESTAMP").toUpperCase()); switch (wmType) { case TIMESTAMP: dataType = "timestamp"; break; case DATE: dataType = "date"; break; default: dataType = "int"; break; } String elementDataType = "string"; List<String> mapSymbols = null; JsonObject newDataType = this.convertDataType(columnName, dataType, elementDataType, mapSymbols); schema.setDataType(newDataType); schema.setWaterMark(true); schema.setPrimaryKey(0); schema.setLength(0); schema.setPrecision(0); schema.setScale(0); schema.setNullable(false); schema.setFormat(null); schema.setComment("Default watermark column"); schema.setDefaultValue(null); schema.setUnique(false); String jsonStr = gson.toJson(schema); JsonObject obj = gson.fromJson(jsonStr, JsonObject.class).getAsJsonObject(); return obj; }
java
private JsonObject getDefaultWatermark() { Schema schema = new Schema(); String dataType; String columnName = "derivedwatermarkcolumn"; schema.setColumnName(columnName); WatermarkType wmType = WatermarkType.valueOf( this.workUnitState.getProp(ConfigurationKeys.SOURCE_QUERYBASED_WATERMARK_TYPE, "TIMESTAMP").toUpperCase()); switch (wmType) { case TIMESTAMP: dataType = "timestamp"; break; case DATE: dataType = "date"; break; default: dataType = "int"; break; } String elementDataType = "string"; List<String> mapSymbols = null; JsonObject newDataType = this.convertDataType(columnName, dataType, elementDataType, mapSymbols); schema.setDataType(newDataType); schema.setWaterMark(true); schema.setPrimaryKey(0); schema.setLength(0); schema.setPrecision(0); schema.setScale(0); schema.setNullable(false); schema.setFormat(null); schema.setComment("Default watermark column"); schema.setDefaultValue(null); schema.setUnique(false); String jsonStr = gson.toJson(schema); JsonObject obj = gson.fromJson(jsonStr, JsonObject.class).getAsJsonObject(); return obj; }
[ "private", "JsonObject", "getDefaultWatermark", "(", ")", "{", "Schema", "schema", "=", "new", "Schema", "(", ")", ";", "String", "dataType", ";", "String", "columnName", "=", "\"derivedwatermarkcolumn\"", ";", "schema", ".", "setColumnName", "(", "columnName", ")", ";", "WatermarkType", "wmType", "=", "WatermarkType", ".", "valueOf", "(", "this", ".", "workUnitState", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_QUERYBASED_WATERMARK_TYPE", ",", "\"TIMESTAMP\"", ")", ".", "toUpperCase", "(", ")", ")", ";", "switch", "(", "wmType", ")", "{", "case", "TIMESTAMP", ":", "dataType", "=", "\"timestamp\"", ";", "break", ";", "case", "DATE", ":", "dataType", "=", "\"date\"", ";", "break", ";", "default", ":", "dataType", "=", "\"int\"", ";", "break", ";", "}", "String", "elementDataType", "=", "\"string\"", ";", "List", "<", "String", ">", "mapSymbols", "=", "null", ";", "JsonObject", "newDataType", "=", "this", ".", "convertDataType", "(", "columnName", ",", "dataType", ",", "elementDataType", ",", "mapSymbols", ")", ";", "schema", ".", "setDataType", "(", "newDataType", ")", ";", "schema", ".", "setWaterMark", "(", "true", ")", ";", "schema", ".", "setPrimaryKey", "(", "0", ")", ";", "schema", ".", "setLength", "(", "0", ")", ";", "schema", ".", "setPrecision", "(", "0", ")", ";", "schema", ".", "setScale", "(", "0", ")", ";", "schema", ".", "setNullable", "(", "false", ")", ";", "schema", ".", "setFormat", "(", "null", ")", ";", "schema", ".", "setComment", "(", "\"Default watermark column\"", ")", ";", "schema", ".", "setDefaultValue", "(", "null", ")", ";", "schema", ".", "setUnique", "(", "false", ")", ";", "String", "jsonStr", "=", "gson", ".", "toJson", "(", "schema", ")", ";", "JsonObject", "obj", "=", "gson", ".", "fromJson", "(", "jsonStr", ",", "JsonObject", ".", "class", ")", ".", "getAsJsonObject", "(", ")", ";", "return", "obj", ";", "}" ]
Schema of default watermark column-required if there are multiple watermarks @return column schema
[ "Schema", "of", "default", "watermark", "column", "-", "required", "if", "there", "are", "multiple", "watermarks" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java#L1100-L1139
26,187
apache/incubator-gobblin
gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java
JdbcExtractor.getCustomColumnSchema
private Schema getCustomColumnSchema(String columnName) { Schema schema = new Schema(); String dataType = "string"; schema.setColumnName(columnName); String elementDataType = "string"; List<String> mapSymbols = null; JsonObject newDataType = this.convertDataType(columnName, dataType, elementDataType, mapSymbols); schema.setDataType(newDataType); schema.setWaterMark(false); schema.setPrimaryKey(0); schema.setLength(0); schema.setPrecision(0); schema.setScale(0); schema.setNullable(true); schema.setFormat(null); schema.setComment("Custom column"); schema.setDefaultValue(null); schema.setUnique(false); return schema; }
java
private Schema getCustomColumnSchema(String columnName) { Schema schema = new Schema(); String dataType = "string"; schema.setColumnName(columnName); String elementDataType = "string"; List<String> mapSymbols = null; JsonObject newDataType = this.convertDataType(columnName, dataType, elementDataType, mapSymbols); schema.setDataType(newDataType); schema.setWaterMark(false); schema.setPrimaryKey(0); schema.setLength(0); schema.setPrecision(0); schema.setScale(0); schema.setNullable(true); schema.setFormat(null); schema.setComment("Custom column"); schema.setDefaultValue(null); schema.setUnique(false); return schema; }
[ "private", "Schema", "getCustomColumnSchema", "(", "String", "columnName", ")", "{", "Schema", "schema", "=", "new", "Schema", "(", ")", ";", "String", "dataType", "=", "\"string\"", ";", "schema", ".", "setColumnName", "(", "columnName", ")", ";", "String", "elementDataType", "=", "\"string\"", ";", "List", "<", "String", ">", "mapSymbols", "=", "null", ";", "JsonObject", "newDataType", "=", "this", ".", "convertDataType", "(", "columnName", ",", "dataType", ",", "elementDataType", ",", "mapSymbols", ")", ";", "schema", ".", "setDataType", "(", "newDataType", ")", ";", "schema", ".", "setWaterMark", "(", "false", ")", ";", "schema", ".", "setPrimaryKey", "(", "0", ")", ";", "schema", ".", "setLength", "(", "0", ")", ";", "schema", ".", "setPrecision", "(", "0", ")", ";", "schema", ".", "setScale", "(", "0", ")", ";", "schema", ".", "setNullable", "(", "true", ")", ";", "schema", ".", "setFormat", "(", "null", ")", ";", "schema", ".", "setComment", "(", "\"Custom column\"", ")", ";", "schema", ".", "setDefaultValue", "(", "null", ")", ";", "schema", ".", "setUnique", "(", "false", ")", ";", "return", "schema", ";", "}" ]
Schema of a custom column - required if column not found in metadata @return column schema
[ "Schema", "of", "a", "custom", "column", "-", "required", "if", "column", "not", "found", "in", "metadata" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java#L1146-L1165
26,188
apache/incubator-gobblin
gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java
JdbcExtractor.hasJoinOperation
public static boolean hasJoinOperation(String selectQuery) { if (selectQuery == null || selectQuery.length() == 0) { return false; } SqlParser sqlParser = SqlParser.create(selectQuery); try { SqlNode all = sqlParser.parseQuery(); SqlSelect query; if (all instanceof SqlSelect) { query = (SqlSelect) all; } else if (all instanceof SqlOrderBy) { query = (SqlSelect) ((SqlOrderBy) all).query; } else { throw new UnsupportedOperationException("The select query is type of " + all.getClass() + " which is not supported here"); } return query.getFrom().getKind() == SqlKind.JOIN; } catch (SqlParseException e) { return false; } }
java
public static boolean hasJoinOperation(String selectQuery) { if (selectQuery == null || selectQuery.length() == 0) { return false; } SqlParser sqlParser = SqlParser.create(selectQuery); try { SqlNode all = sqlParser.parseQuery(); SqlSelect query; if (all instanceof SqlSelect) { query = (SqlSelect) all; } else if (all instanceof SqlOrderBy) { query = (SqlSelect) ((SqlOrderBy) all).query; } else { throw new UnsupportedOperationException("The select query is type of " + all.getClass() + " which is not supported here"); } return query.getFrom().getKind() == SqlKind.JOIN; } catch (SqlParseException e) { return false; } }
[ "public", "static", "boolean", "hasJoinOperation", "(", "String", "selectQuery", ")", "{", "if", "(", "selectQuery", "==", "null", "||", "selectQuery", ".", "length", "(", ")", "==", "0", ")", "{", "return", "false", ";", "}", "SqlParser", "sqlParser", "=", "SqlParser", ".", "create", "(", "selectQuery", ")", ";", "try", "{", "SqlNode", "all", "=", "sqlParser", ".", "parseQuery", "(", ")", ";", "SqlSelect", "query", ";", "if", "(", "all", "instanceof", "SqlSelect", ")", "{", "query", "=", "(", "SqlSelect", ")", "all", ";", "}", "else", "if", "(", "all", "instanceof", "SqlOrderBy", ")", "{", "query", "=", "(", "SqlSelect", ")", "(", "(", "SqlOrderBy", ")", "all", ")", ".", "query", ";", "}", "else", "{", "throw", "new", "UnsupportedOperationException", "(", "\"The select query is type of \"", "+", "all", ".", "getClass", "(", ")", "+", "\" which is not supported here\"", ")", ";", "}", "return", "query", ".", "getFrom", "(", ")", ".", "getKind", "(", ")", "==", "SqlKind", ".", "JOIN", ";", "}", "catch", "(", "SqlParseException", "e", ")", "{", "return", "false", ";", "}", "}" ]
Check if the SELECT query has join operation
[ "Check", "if", "the", "SELECT", "query", "has", "join", "operation" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java#L1170-L1191
26,189
apache/incubator-gobblin
gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java
JdbcExtractor.toCase
private String toCase(String targetColumnName) { String columnName = targetColumnName; ColumnNameCase caseType = ColumnNameCase.valueOf(this.workUnitState .getProp(ConfigurationKeys.SOURCE_COLUMN_NAME_CASE, ConfigurationKeys.DEFAULT_COLUMN_NAME_CASE).toUpperCase()); switch (caseType) { case TOUPPER: columnName = targetColumnName.toUpperCase(); break; case TOLOWER: columnName = targetColumnName.toLowerCase(); break; default: columnName = targetColumnName; break; } return columnName; }
java
private String toCase(String targetColumnName) { String columnName = targetColumnName; ColumnNameCase caseType = ColumnNameCase.valueOf(this.workUnitState .getProp(ConfigurationKeys.SOURCE_COLUMN_NAME_CASE, ConfigurationKeys.DEFAULT_COLUMN_NAME_CASE).toUpperCase()); switch (caseType) { case TOUPPER: columnName = targetColumnName.toUpperCase(); break; case TOLOWER: columnName = targetColumnName.toLowerCase(); break; default: columnName = targetColumnName; break; } return columnName; }
[ "private", "String", "toCase", "(", "String", "targetColumnName", ")", "{", "String", "columnName", "=", "targetColumnName", ";", "ColumnNameCase", "caseType", "=", "ColumnNameCase", ".", "valueOf", "(", "this", ".", "workUnitState", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_COLUMN_NAME_CASE", ",", "ConfigurationKeys", ".", "DEFAULT_COLUMN_NAME_CASE", ")", ".", "toUpperCase", "(", ")", ")", ";", "switch", "(", "caseType", ")", "{", "case", "TOUPPER", ":", "columnName", "=", "targetColumnName", ".", "toUpperCase", "(", ")", ";", "break", ";", "case", "TOLOWER", ":", "columnName", "=", "targetColumnName", ".", "toLowerCase", "(", ")", ";", "break", ";", "default", ":", "columnName", "=", "targetColumnName", ";", "break", ";", "}", "return", "columnName", ";", "}" ]
Change the column name case to upper, lower or nochange; Default nochange @return column name with the required case
[ "Change", "the", "column", "name", "case", "to", "upper", "lower", "or", "nochange", ";", "Default", "nochange" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java#L1207-L1223
26,190
apache/incubator-gobblin
gobblin-admin/src/main/java/org/apache/gobblin/cli/Cli.java
Cli.createGlobalOptions
private GlobalOptions createGlobalOptions(CommandLine parsedOpts) { String host = parsedOpts.hasOption(HOST_OPT) ? parsedOpts.getOptionValue(HOST_OPT) : DEFAULT_REST_SERVER_HOST; int port = DEFAULT_REST_SERVER_PORT; try { if (parsedOpts.hasOption(PORT_OPT)) { port = Integer.parseInt(parsedOpts.getOptionValue(PORT_OPT)); } } catch (NumberFormatException e) { printHelpAndExit("The port must be a valid integer."); } return new GlobalOptions(host, port); }
java
private GlobalOptions createGlobalOptions(CommandLine parsedOpts) { String host = parsedOpts.hasOption(HOST_OPT) ? parsedOpts.getOptionValue(HOST_OPT) : DEFAULT_REST_SERVER_HOST; int port = DEFAULT_REST_SERVER_PORT; try { if (parsedOpts.hasOption(PORT_OPT)) { port = Integer.parseInt(parsedOpts.getOptionValue(PORT_OPT)); } } catch (NumberFormatException e) { printHelpAndExit("The port must be a valid integer."); } return new GlobalOptions(host, port); }
[ "private", "GlobalOptions", "createGlobalOptions", "(", "CommandLine", "parsedOpts", ")", "{", "String", "host", "=", "parsedOpts", ".", "hasOption", "(", "HOST_OPT", ")", "?", "parsedOpts", ".", "getOptionValue", "(", "HOST_OPT", ")", ":", "DEFAULT_REST_SERVER_HOST", ";", "int", "port", "=", "DEFAULT_REST_SERVER_PORT", ";", "try", "{", "if", "(", "parsedOpts", ".", "hasOption", "(", "PORT_OPT", ")", ")", "{", "port", "=", "Integer", ".", "parseInt", "(", "parsedOpts", ".", "getOptionValue", "(", "PORT_OPT", ")", ")", ";", "}", "}", "catch", "(", "NumberFormatException", "e", ")", "{", "printHelpAndExit", "(", "\"The port must be a valid integer.\"", ")", ";", "}", "return", "new", "GlobalOptions", "(", "host", ",", "port", ")", ";", "}" ]
Build the GlobalOptions information from the raw parsed options @param parsedOpts Options parsed from the cmd line @return
[ "Build", "the", "GlobalOptions", "information", "from", "the", "raw", "parsed", "options" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-admin/src/main/java/org/apache/gobblin/cli/Cli.java#L144-L157
26,191
apache/incubator-gobblin
gobblin-utility/src/main/java/org/apache/gobblin/util/PortUtils.java
PortUtils.replacePortTokens
public String replacePortTokens(String value) { BiMap<String, Optional<Integer>> portMappings = HashBiMap.create(); Matcher regexMatcher = PORT_REGEX.matcher(value); while (regexMatcher.find()) { String token = regexMatcher.group(0); if (!portMappings.containsKey(token)) { Optional<Integer> portStart = Optional.absent(); Optional<Integer> portEnd = Optional.absent(); String unboundedStart = regexMatcher.group(1); if (unboundedStart != null) { int requestedEndPort = Integer.parseInt(unboundedStart); Preconditions.checkArgument(requestedEndPort <= PortUtils.MAXIMUM_PORT); portEnd = Optional.of(requestedEndPort); } else { String unboundedEnd = regexMatcher.group(2); if (unboundedEnd != null) { int requestedStartPort = Integer.parseInt(unboundedEnd); Preconditions.checkArgument(requestedStartPort >= PortUtils.MINIMUM_PORT); portStart = Optional.of(requestedStartPort); } else { String absolute = regexMatcher.group(3); if (!"?".equals(absolute)) { int requestedPort = Integer.parseInt(absolute); Preconditions.checkArgument(requestedPort >= PortUtils.MINIMUM_PORT && requestedPort <= PortUtils.MAXIMUM_PORT); portStart = Optional.of(requestedPort); portEnd = Optional.of(requestedPort); } } } Optional<Integer> port = takePort(portStart, portEnd); portMappings.put(token, port); } } for (Map.Entry<String, Optional<Integer>> port : portMappings.entrySet()) { if (port.getValue().isPresent()) { value = value.replace(port.getKey(), port.getValue().get().toString()); } } return value; }
java
public String replacePortTokens(String value) { BiMap<String, Optional<Integer>> portMappings = HashBiMap.create(); Matcher regexMatcher = PORT_REGEX.matcher(value); while (regexMatcher.find()) { String token = regexMatcher.group(0); if (!portMappings.containsKey(token)) { Optional<Integer> portStart = Optional.absent(); Optional<Integer> portEnd = Optional.absent(); String unboundedStart = regexMatcher.group(1); if (unboundedStart != null) { int requestedEndPort = Integer.parseInt(unboundedStart); Preconditions.checkArgument(requestedEndPort <= PortUtils.MAXIMUM_PORT); portEnd = Optional.of(requestedEndPort); } else { String unboundedEnd = regexMatcher.group(2); if (unboundedEnd != null) { int requestedStartPort = Integer.parseInt(unboundedEnd); Preconditions.checkArgument(requestedStartPort >= PortUtils.MINIMUM_PORT); portStart = Optional.of(requestedStartPort); } else { String absolute = regexMatcher.group(3); if (!"?".equals(absolute)) { int requestedPort = Integer.parseInt(absolute); Preconditions.checkArgument(requestedPort >= PortUtils.MINIMUM_PORT && requestedPort <= PortUtils.MAXIMUM_PORT); portStart = Optional.of(requestedPort); portEnd = Optional.of(requestedPort); } } } Optional<Integer> port = takePort(portStart, portEnd); portMappings.put(token, port); } } for (Map.Entry<String, Optional<Integer>> port : portMappings.entrySet()) { if (port.getValue().isPresent()) { value = value.replace(port.getKey(), port.getValue().get().toString()); } } return value; }
[ "public", "String", "replacePortTokens", "(", "String", "value", ")", "{", "BiMap", "<", "String", ",", "Optional", "<", "Integer", ">", ">", "portMappings", "=", "HashBiMap", ".", "create", "(", ")", ";", "Matcher", "regexMatcher", "=", "PORT_REGEX", ".", "matcher", "(", "value", ")", ";", "while", "(", "regexMatcher", ".", "find", "(", ")", ")", "{", "String", "token", "=", "regexMatcher", ".", "group", "(", "0", ")", ";", "if", "(", "!", "portMappings", ".", "containsKey", "(", "token", ")", ")", "{", "Optional", "<", "Integer", ">", "portStart", "=", "Optional", ".", "absent", "(", ")", ";", "Optional", "<", "Integer", ">", "portEnd", "=", "Optional", ".", "absent", "(", ")", ";", "String", "unboundedStart", "=", "regexMatcher", ".", "group", "(", "1", ")", ";", "if", "(", "unboundedStart", "!=", "null", ")", "{", "int", "requestedEndPort", "=", "Integer", ".", "parseInt", "(", "unboundedStart", ")", ";", "Preconditions", ".", "checkArgument", "(", "requestedEndPort", "<=", "PortUtils", ".", "MAXIMUM_PORT", ")", ";", "portEnd", "=", "Optional", ".", "of", "(", "requestedEndPort", ")", ";", "}", "else", "{", "String", "unboundedEnd", "=", "regexMatcher", ".", "group", "(", "2", ")", ";", "if", "(", "unboundedEnd", "!=", "null", ")", "{", "int", "requestedStartPort", "=", "Integer", ".", "parseInt", "(", "unboundedEnd", ")", ";", "Preconditions", ".", "checkArgument", "(", "requestedStartPort", ">=", "PortUtils", ".", "MINIMUM_PORT", ")", ";", "portStart", "=", "Optional", ".", "of", "(", "requestedStartPort", ")", ";", "}", "else", "{", "String", "absolute", "=", "regexMatcher", ".", "group", "(", "3", ")", ";", "if", "(", "!", "\"?\"", ".", "equals", "(", "absolute", ")", ")", "{", "int", "requestedPort", "=", "Integer", ".", "parseInt", "(", "absolute", ")", ";", "Preconditions", ".", "checkArgument", "(", "requestedPort", ">=", "PortUtils", ".", "MINIMUM_PORT", "&&", "requestedPort", "<=", "PortUtils", ".", "MAXIMUM_PORT", ")", ";", "portStart", "=", "Optional", ".", "of", "(", "requestedPort", ")", ";", "portEnd", "=", "Optional", ".", "of", "(", "requestedPort", ")", ";", "}", "}", "}", "Optional", "<", "Integer", ">", "port", "=", "takePort", "(", "portStart", ",", "portEnd", ")", ";", "portMappings", ".", "put", "(", "token", ",", "port", ")", ";", "}", "}", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Optional", "<", "Integer", ">", ">", "port", ":", "portMappings", ".", "entrySet", "(", ")", ")", "{", "if", "(", "port", ".", "getValue", "(", ")", ".", "isPresent", "(", ")", ")", "{", "value", "=", "value", ".", "replace", "(", "port", ".", "getKey", "(", ")", ",", "port", ".", "getValue", "(", ")", ".", "get", "(", ")", ".", "toString", "(", ")", ")", ";", "}", "}", "return", "value", ";", "}" ]
Replaces any port tokens in the specified string. NOTE: Tokens can be in the following forms: 1. ${PORT_123} 2. ${PORT_?123} 3. ${PORT_123?} 4. ${PORT_?} @param value The string in which to replace port tokens. @return The replaced string.
[ "Replaces", "any", "port", "tokens", "in", "the", "specified", "string", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/PortUtils.java#L62-L102
26,192
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/converter/avro/JsonIntermediateToAvroConverter.java
JsonIntermediateToAvroConverter.generateSchemaWithNullifiedField
protected Schema generateSchemaWithNullifiedField(WorkUnitState workUnitState, Schema currentAvroSchema) { Configuration conf = new Configuration(); for (String key : workUnitState.getPropertyNames()) { conf.set(key, workUnitState.getProp(key)); } // Get the original schema for merging. Path originalSchemaPath = null; if (workUnitState.contains(CONVERTER_AVRO_NULLIFY_FIELDS_ORIGINAL_SCHEMA_PATH)) { originalSchemaPath = new Path(workUnitState.getProp(CONVERTER_AVRO_NULLIFY_FIELDS_ORIGINAL_SCHEMA_PATH)); } else { // If the path to get the original schema is not specified in the configuration, // adopt the best-try policy to search adjacent output folders. LOG.info("Property " + CONVERTER_AVRO_NULLIFY_FIELDS_ORIGINAL_SCHEMA_PATH + "is not specified. Trying to get the orignal schema from previous avro files."); originalSchemaPath = WriterUtils .getDataPublisherFinalDir(workUnitState, workUnitState.getPropAsInt(ConfigurationKeys.FORK_BRANCHES_KEY, 1), workUnitState.getPropAsInt(ConfigurationKeys.FORK_BRANCH_ID_KEY, 0)).getParent(); } try { Schema prevSchema = AvroUtils.getDirectorySchema(originalSchemaPath, conf, false); Schema mergedSchema = AvroUtils.nullifyFieldsForSchemaMerge(prevSchema, currentAvroSchema); return mergedSchema; } catch (IOException ioe) { LOG.error("Unable to nullify fields. Will retain the current avro schema.", ioe); return currentAvroSchema; } }
java
protected Schema generateSchemaWithNullifiedField(WorkUnitState workUnitState, Schema currentAvroSchema) { Configuration conf = new Configuration(); for (String key : workUnitState.getPropertyNames()) { conf.set(key, workUnitState.getProp(key)); } // Get the original schema for merging. Path originalSchemaPath = null; if (workUnitState.contains(CONVERTER_AVRO_NULLIFY_FIELDS_ORIGINAL_SCHEMA_PATH)) { originalSchemaPath = new Path(workUnitState.getProp(CONVERTER_AVRO_NULLIFY_FIELDS_ORIGINAL_SCHEMA_PATH)); } else { // If the path to get the original schema is not specified in the configuration, // adopt the best-try policy to search adjacent output folders. LOG.info("Property " + CONVERTER_AVRO_NULLIFY_FIELDS_ORIGINAL_SCHEMA_PATH + "is not specified. Trying to get the orignal schema from previous avro files."); originalSchemaPath = WriterUtils .getDataPublisherFinalDir(workUnitState, workUnitState.getPropAsInt(ConfigurationKeys.FORK_BRANCHES_KEY, 1), workUnitState.getPropAsInt(ConfigurationKeys.FORK_BRANCH_ID_KEY, 0)).getParent(); } try { Schema prevSchema = AvroUtils.getDirectorySchema(originalSchemaPath, conf, false); Schema mergedSchema = AvroUtils.nullifyFieldsForSchemaMerge(prevSchema, currentAvroSchema); return mergedSchema; } catch (IOException ioe) { LOG.error("Unable to nullify fields. Will retain the current avro schema.", ioe); return currentAvroSchema; } }
[ "protected", "Schema", "generateSchemaWithNullifiedField", "(", "WorkUnitState", "workUnitState", ",", "Schema", "currentAvroSchema", ")", "{", "Configuration", "conf", "=", "new", "Configuration", "(", ")", ";", "for", "(", "String", "key", ":", "workUnitState", ".", "getPropertyNames", "(", ")", ")", "{", "conf", ".", "set", "(", "key", ",", "workUnitState", ".", "getProp", "(", "key", ")", ")", ";", "}", "// Get the original schema for merging.", "Path", "originalSchemaPath", "=", "null", ";", "if", "(", "workUnitState", ".", "contains", "(", "CONVERTER_AVRO_NULLIFY_FIELDS_ORIGINAL_SCHEMA_PATH", ")", ")", "{", "originalSchemaPath", "=", "new", "Path", "(", "workUnitState", ".", "getProp", "(", "CONVERTER_AVRO_NULLIFY_FIELDS_ORIGINAL_SCHEMA_PATH", ")", ")", ";", "}", "else", "{", "// If the path to get the original schema is not specified in the configuration,", "// adopt the best-try policy to search adjacent output folders.", "LOG", ".", "info", "(", "\"Property \"", "+", "CONVERTER_AVRO_NULLIFY_FIELDS_ORIGINAL_SCHEMA_PATH", "+", "\"is not specified. Trying to get the orignal schema from previous avro files.\"", ")", ";", "originalSchemaPath", "=", "WriterUtils", ".", "getDataPublisherFinalDir", "(", "workUnitState", ",", "workUnitState", ".", "getPropAsInt", "(", "ConfigurationKeys", ".", "FORK_BRANCHES_KEY", ",", "1", ")", ",", "workUnitState", ".", "getPropAsInt", "(", "ConfigurationKeys", ".", "FORK_BRANCH_ID_KEY", ",", "0", ")", ")", ".", "getParent", "(", ")", ";", "}", "try", "{", "Schema", "prevSchema", "=", "AvroUtils", ".", "getDirectorySchema", "(", "originalSchemaPath", ",", "conf", ",", "false", ")", ";", "Schema", "mergedSchema", "=", "AvroUtils", ".", "nullifyFieldsForSchemaMerge", "(", "prevSchema", ",", "currentAvroSchema", ")", ";", "return", "mergedSchema", ";", "}", "catch", "(", "IOException", "ioe", ")", "{", "LOG", ".", "error", "(", "\"Unable to nullify fields. Will retain the current avro schema.\"", ",", "ioe", ")", ";", "return", "currentAvroSchema", ";", "}", "}" ]
Generate new avro schema by nullifying fields that previously existed but not in the current schema. @param workUnitState work unit state @param currentAvroSchema current schema @return merged schema with previous fields nullified. @throws SchemaConversionException
[ "Generate", "new", "avro", "schema", "by", "nullifying", "fields", "that", "previously", "existed", "but", "not", "in", "the", "current", "schema", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/converter/avro/JsonIntermediateToAvroConverter.java#L96-L122
26,193
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/CopySource.java
CopySource.setWorkUnitGuid
public static void setWorkUnitGuid(State state, Guid guid) { state.setProp(WORK_UNIT_GUID, guid.toString()); }
java
public static void setWorkUnitGuid(State state, Guid guid) { state.setProp(WORK_UNIT_GUID, guid.toString()); }
[ "public", "static", "void", "setWorkUnitGuid", "(", "State", "state", ",", "Guid", "guid", ")", "{", "state", ".", "setProp", "(", "WORK_UNIT_GUID", ",", "guid", ".", "toString", "(", ")", ")", ";", "}" ]
Set a unique, replicable guid for this work unit. Used for recovering partially successful work units. @param state {@link State} where guid should be written. @param guid A byte array guid.
[ "Set", "a", "unique", "replicable", "guid", "for", "this", "work", "unit", ".", "Used", "for", "recovering", "partially", "successful", "work", "units", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/CopySource.java#L490-L492
26,194
apache/incubator-gobblin
gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/converter/BaseEnvelopeSchemaConverter.java
BaseEnvelopeSchemaConverter.getFieldSchema
protected Schema getFieldSchema(GenericRecord record, String schemaIdLocation) throws Exception { Optional<Object> schemaIdValue = AvroUtils.getFieldValue(record, schemaIdLocation); if (!schemaIdValue.isPresent()) { throw new Exception("Schema id with key " + schemaIdLocation + " not found in the record"); } String schemaKey = String.valueOf(schemaIdValue.get()); return (Schema) registry.getSchemaByKey(schemaKey); }
java
protected Schema getFieldSchema(GenericRecord record, String schemaIdLocation) throws Exception { Optional<Object> schemaIdValue = AvroUtils.getFieldValue(record, schemaIdLocation); if (!schemaIdValue.isPresent()) { throw new Exception("Schema id with key " + schemaIdLocation + " not found in the record"); } String schemaKey = String.valueOf(schemaIdValue.get()); return (Schema) registry.getSchemaByKey(schemaKey); }
[ "protected", "Schema", "getFieldSchema", "(", "GenericRecord", "record", ",", "String", "schemaIdLocation", ")", "throws", "Exception", "{", "Optional", "<", "Object", ">", "schemaIdValue", "=", "AvroUtils", ".", "getFieldValue", "(", "record", ",", "schemaIdLocation", ")", ";", "if", "(", "!", "schemaIdValue", ".", "isPresent", "(", ")", ")", "{", "throw", "new", "Exception", "(", "\"Schema id with key \"", "+", "schemaIdLocation", "+", "\" not found in the record\"", ")", ";", "}", "String", "schemaKey", "=", "String", ".", "valueOf", "(", "schemaIdValue", ".", "get", "(", ")", ")", ";", "return", "(", "Schema", ")", "registry", ".", "getSchemaByKey", "(", "schemaKey", ")", ";", "}" ]
Get the schema of a field @param record the input record which has the schema id @param schemaIdLocation a dot separated location string the schema id @return a schema referenced by the schema id
[ "Get", "the", "schema", "of", "a", "field" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/converter/BaseEnvelopeSchemaConverter.java#L101-L108
26,195
apache/incubator-gobblin
gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/converter/BaseEnvelopeSchemaConverter.java
BaseEnvelopeSchemaConverter.getPayloadBytes
@Deprecated protected byte[] getPayloadBytes(GenericRecord inputRecord) { try { return getFieldAsBytes(inputRecord, payloadField); } catch (Exception e) { return null; } }
java
@Deprecated protected byte[] getPayloadBytes(GenericRecord inputRecord) { try { return getFieldAsBytes(inputRecord, payloadField); } catch (Exception e) { return null; } }
[ "@", "Deprecated", "protected", "byte", "[", "]", "getPayloadBytes", "(", "GenericRecord", "inputRecord", ")", "{", "try", "{", "return", "getFieldAsBytes", "(", "inputRecord", ",", "payloadField", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "null", ";", "}", "}" ]
Get payload field and convert to byte array @param inputRecord the input record which has the payload @return the byte array of the payload in the input record @deprecated use {@link #getFieldAsBytes(GenericRecord, String)}
[ "Get", "payload", "field", "and", "convert", "to", "byte", "array" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/converter/BaseEnvelopeSchemaConverter.java#L117-L124
26,196
apache/incubator-gobblin
gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/converter/BaseEnvelopeSchemaConverter.java
BaseEnvelopeSchemaConverter.getFieldAsBytes
protected byte[] getFieldAsBytes(GenericRecord record, String fieldLocation) throws Exception { Optional<Object> bytesValue = AvroUtils.getFieldValue(record, fieldLocation); if (!bytesValue.isPresent()) { throw new Exception("Bytes value with key " + fieldLocation + " not found in the record"); } ByteBuffer bb = (ByteBuffer) bytesValue.get(); if (bb.hasArray()) { return bb.array(); } else { byte[] payloadBytes = new byte[bb.remaining()]; bb.get(payloadBytes); return payloadBytes; } }
java
protected byte[] getFieldAsBytes(GenericRecord record, String fieldLocation) throws Exception { Optional<Object> bytesValue = AvroUtils.getFieldValue(record, fieldLocation); if (!bytesValue.isPresent()) { throw new Exception("Bytes value with key " + fieldLocation + " not found in the record"); } ByteBuffer bb = (ByteBuffer) bytesValue.get(); if (bb.hasArray()) { return bb.array(); } else { byte[] payloadBytes = new byte[bb.remaining()]; bb.get(payloadBytes); return payloadBytes; } }
[ "protected", "byte", "[", "]", "getFieldAsBytes", "(", "GenericRecord", "record", ",", "String", "fieldLocation", ")", "throws", "Exception", "{", "Optional", "<", "Object", ">", "bytesValue", "=", "AvroUtils", ".", "getFieldValue", "(", "record", ",", "fieldLocation", ")", ";", "if", "(", "!", "bytesValue", ".", "isPresent", "(", ")", ")", "{", "throw", "new", "Exception", "(", "\"Bytes value with key \"", "+", "fieldLocation", "+", "\" not found in the record\"", ")", ";", "}", "ByteBuffer", "bb", "=", "(", "ByteBuffer", ")", "bytesValue", ".", "get", "(", ")", ";", "if", "(", "bb", ".", "hasArray", "(", ")", ")", "{", "return", "bb", ".", "array", "(", ")", ";", "}", "else", "{", "byte", "[", "]", "payloadBytes", "=", "new", "byte", "[", "bb", ".", "remaining", "(", ")", "]", ";", "bb", ".", "get", "(", "payloadBytes", ")", ";", "return", "payloadBytes", ";", "}", "}" ]
Get field value byte array @param record the input record which has the field @param fieldLocation a dot separated location string to the field @return the byte array of field value
[ "Get", "field", "value", "byte", "array" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/converter/BaseEnvelopeSchemaConverter.java#L133-L146
26,197
apache/incubator-gobblin
gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/converter/BaseEnvelopeSchemaConverter.java
BaseEnvelopeSchemaConverter.upConvertPayload
protected P upConvertPayload(GenericRecord inputRecord) throws DataConversionException { try { Schema payloadSchema = getPayloadSchema(inputRecord); // Set writer schema latestPayloadReader.setSchema(payloadSchema); byte[] payloadBytes = getPayloadBytes(inputRecord); Decoder decoder = DecoderFactory.get().binaryDecoder(payloadBytes, null); // 'latestPayloadReader.read' will convert the record from 'payloadSchema' to the latest payload schema return latestPayloadReader.read(null, decoder); } catch (Exception e) { throw new DataConversionException(e); } }
java
protected P upConvertPayload(GenericRecord inputRecord) throws DataConversionException { try { Schema payloadSchema = getPayloadSchema(inputRecord); // Set writer schema latestPayloadReader.setSchema(payloadSchema); byte[] payloadBytes = getPayloadBytes(inputRecord); Decoder decoder = DecoderFactory.get().binaryDecoder(payloadBytes, null); // 'latestPayloadReader.read' will convert the record from 'payloadSchema' to the latest payload schema return latestPayloadReader.read(null, decoder); } catch (Exception e) { throw new DataConversionException(e); } }
[ "protected", "P", "upConvertPayload", "(", "GenericRecord", "inputRecord", ")", "throws", "DataConversionException", "{", "try", "{", "Schema", "payloadSchema", "=", "getPayloadSchema", "(", "inputRecord", ")", ";", "// Set writer schema", "latestPayloadReader", ".", "setSchema", "(", "payloadSchema", ")", ";", "byte", "[", "]", "payloadBytes", "=", "getPayloadBytes", "(", "inputRecord", ")", ";", "Decoder", "decoder", "=", "DecoderFactory", ".", "get", "(", ")", ".", "binaryDecoder", "(", "payloadBytes", ",", "null", ")", ";", "// 'latestPayloadReader.read' will convert the record from 'payloadSchema' to the latest payload schema", "return", "latestPayloadReader", ".", "read", "(", "null", ",", "decoder", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "DataConversionException", "(", "e", ")", ";", "}", "}" ]
Convert the payload in the input record to a deserialized object with the latest schema @param inputRecord the input record @return the schema'ed payload object
[ "Convert", "the", "payload", "in", "the", "input", "record", "to", "a", "deserialized", "object", "with", "the", "latest", "schema" ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/converter/BaseEnvelopeSchemaConverter.java#L160-L174
26,198
apache/incubator-gobblin
gobblin-core-base/src/main/java/org/apache/gobblin/instrumented/fork/InstrumentedForkOperatorBase.java
InstrumentedForkOperatorBase.afterFork
protected void afterFork(List<Boolean> forks, long startTimeNanos) { int forksGenerated = 0; for (Boolean fork : forks) { forksGenerated += fork ? 1 : 0; } Instrumented.markMeter(this.outputForks, forksGenerated); Instrumented.updateTimer(this.forkOperatorTimer, System.nanoTime() - startTimeNanos, TimeUnit.NANOSECONDS); }
java
protected void afterFork(List<Boolean> forks, long startTimeNanos) { int forksGenerated = 0; for (Boolean fork : forks) { forksGenerated += fork ? 1 : 0; } Instrumented.markMeter(this.outputForks, forksGenerated); Instrumented.updateTimer(this.forkOperatorTimer, System.nanoTime() - startTimeNanos, TimeUnit.NANOSECONDS); }
[ "protected", "void", "afterFork", "(", "List", "<", "Boolean", ">", "forks", ",", "long", "startTimeNanos", ")", "{", "int", "forksGenerated", "=", "0", ";", "for", "(", "Boolean", "fork", ":", "forks", ")", "{", "forksGenerated", "+=", "fork", "?", "1", ":", "0", ";", "}", "Instrumented", ".", "markMeter", "(", "this", ".", "outputForks", ",", "forksGenerated", ")", ";", "Instrumented", ".", "updateTimer", "(", "this", ".", "forkOperatorTimer", ",", "System", ".", "nanoTime", "(", ")", "-", "startTimeNanos", ",", "TimeUnit", ".", "NANOSECONDS", ")", ";", "}" ]
Called after forkDataRecord. @param forks result from forkDataRecord. @param startTimeNanos start time of forkDataRecord.
[ "Called", "after", "forkDataRecord", "." ]
f029b4c0fea0fe4aa62f36dda2512344ff708bae
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core-base/src/main/java/org/apache/gobblin/instrumented/fork/InstrumentedForkOperatorBase.java#L152-L159
26,199
apache/incubator-gobblin
gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/source/extractor/extract/kafka/KafkaExtractor.java
KafkaExtractor.readRecordImpl
@SuppressWarnings("unchecked") @Override public D readRecordImpl(D reuse) throws DataRecordException, IOException { if (this.shutdownRequested.get()) { return null; } long readStartTime = System.nanoTime(); while (!allPartitionsFinished()) { if (currentPartitionFinished()) { moveToNextPartition(); continue; } if (this.messageIterator == null || !this.messageIterator.hasNext()) { try { long fetchStartTime = System.nanoTime(); this.messageIterator = fetchNextMessageBuffer(); this.currentPartitionFetchMessageBufferTime += System.nanoTime() - fetchStartTime; } catch (Exception e) { LOG.error(String.format("Failed to fetch next message buffer for partition %s. Will skip this partition.", getCurrentPartition()), e); moveToNextPartition(); continue; } if (this.messageIterator == null || !this.messageIterator.hasNext()) { moveToNextPartition(); continue; } } while (!currentPartitionFinished()) { if (!this.messageIterator.hasNext()) { break; } KafkaConsumerRecord nextValidMessage = this.messageIterator.next(); // Even though we ask Kafka to give us a message buffer starting from offset x, it may // return a buffer that starts from offset smaller than x, so we need to skip messages // until we get to x. if (nextValidMessage.getOffset() < this.nextWatermark.get(this.currentPartitionIdx)) { continue; } this.nextWatermark.set(this.currentPartitionIdx, nextValidMessage.getNextOffset()); try { // track time for decode/convert depending on the record type long decodeStartTime = System.nanoTime(); D record = decodeKafkaMessage(nextValidMessage); this.currentPartitionDecodeRecordTime += System.nanoTime() - decodeStartTime; this.currentPartitionRecordCount++; this.currentPartitionTotalSize += nextValidMessage.getValueSizeInBytes(); this.currentPartitionReadRecordTime += System.nanoTime() - readStartTime; this.currentPartitionLastSuccessfulRecord = record; return record; } catch (Throwable t) { this.errorPartitions.add(this.currentPartitionIdx); this.undecodableMessageCount++; if (shouldLogError()) { LOG.error(String.format("A record from partition %s cannot be decoded.", getCurrentPartition()), t); } incrementErrorCount(); } } } LOG.info("Finished pulling topic " + this.topicName); this.currentPartitionReadRecordTime += System.nanoTime() - readStartTime; return null; }
java
@SuppressWarnings("unchecked") @Override public D readRecordImpl(D reuse) throws DataRecordException, IOException { if (this.shutdownRequested.get()) { return null; } long readStartTime = System.nanoTime(); while (!allPartitionsFinished()) { if (currentPartitionFinished()) { moveToNextPartition(); continue; } if (this.messageIterator == null || !this.messageIterator.hasNext()) { try { long fetchStartTime = System.nanoTime(); this.messageIterator = fetchNextMessageBuffer(); this.currentPartitionFetchMessageBufferTime += System.nanoTime() - fetchStartTime; } catch (Exception e) { LOG.error(String.format("Failed to fetch next message buffer for partition %s. Will skip this partition.", getCurrentPartition()), e); moveToNextPartition(); continue; } if (this.messageIterator == null || !this.messageIterator.hasNext()) { moveToNextPartition(); continue; } } while (!currentPartitionFinished()) { if (!this.messageIterator.hasNext()) { break; } KafkaConsumerRecord nextValidMessage = this.messageIterator.next(); // Even though we ask Kafka to give us a message buffer starting from offset x, it may // return a buffer that starts from offset smaller than x, so we need to skip messages // until we get to x. if (nextValidMessage.getOffset() < this.nextWatermark.get(this.currentPartitionIdx)) { continue; } this.nextWatermark.set(this.currentPartitionIdx, nextValidMessage.getNextOffset()); try { // track time for decode/convert depending on the record type long decodeStartTime = System.nanoTime(); D record = decodeKafkaMessage(nextValidMessage); this.currentPartitionDecodeRecordTime += System.nanoTime() - decodeStartTime; this.currentPartitionRecordCount++; this.currentPartitionTotalSize += nextValidMessage.getValueSizeInBytes(); this.currentPartitionReadRecordTime += System.nanoTime() - readStartTime; this.currentPartitionLastSuccessfulRecord = record; return record; } catch (Throwable t) { this.errorPartitions.add(this.currentPartitionIdx); this.undecodableMessageCount++; if (shouldLogError()) { LOG.error(String.format("A record from partition %s cannot be decoded.", getCurrentPartition()), t); } incrementErrorCount(); } } } LOG.info("Finished pulling topic " + this.topicName); this.currentPartitionReadRecordTime += System.nanoTime() - readStartTime; return null; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "@", "Override", "public", "D", "readRecordImpl", "(", "D", "reuse", ")", "throws", "DataRecordException", ",", "IOException", "{", "if", "(", "this", ".", "shutdownRequested", ".", "get", "(", ")", ")", "{", "return", "null", ";", "}", "long", "readStartTime", "=", "System", ".", "nanoTime", "(", ")", ";", "while", "(", "!", "allPartitionsFinished", "(", ")", ")", "{", "if", "(", "currentPartitionFinished", "(", ")", ")", "{", "moveToNextPartition", "(", ")", ";", "continue", ";", "}", "if", "(", "this", ".", "messageIterator", "==", "null", "||", "!", "this", ".", "messageIterator", ".", "hasNext", "(", ")", ")", "{", "try", "{", "long", "fetchStartTime", "=", "System", ".", "nanoTime", "(", ")", ";", "this", ".", "messageIterator", "=", "fetchNextMessageBuffer", "(", ")", ";", "this", ".", "currentPartitionFetchMessageBufferTime", "+=", "System", ".", "nanoTime", "(", ")", "-", "fetchStartTime", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "error", "(", "String", ".", "format", "(", "\"Failed to fetch next message buffer for partition %s. Will skip this partition.\"", ",", "getCurrentPartition", "(", ")", ")", ",", "e", ")", ";", "moveToNextPartition", "(", ")", ";", "continue", ";", "}", "if", "(", "this", ".", "messageIterator", "==", "null", "||", "!", "this", ".", "messageIterator", ".", "hasNext", "(", ")", ")", "{", "moveToNextPartition", "(", ")", ";", "continue", ";", "}", "}", "while", "(", "!", "currentPartitionFinished", "(", ")", ")", "{", "if", "(", "!", "this", ".", "messageIterator", ".", "hasNext", "(", ")", ")", "{", "break", ";", "}", "KafkaConsumerRecord", "nextValidMessage", "=", "this", ".", "messageIterator", ".", "next", "(", ")", ";", "// Even though we ask Kafka to give us a message buffer starting from offset x, it may", "// return a buffer that starts from offset smaller than x, so we need to skip messages", "// until we get to x.", "if", "(", "nextValidMessage", ".", "getOffset", "(", ")", "<", "this", ".", "nextWatermark", ".", "get", "(", "this", ".", "currentPartitionIdx", ")", ")", "{", "continue", ";", "}", "this", ".", "nextWatermark", ".", "set", "(", "this", ".", "currentPartitionIdx", ",", "nextValidMessage", ".", "getNextOffset", "(", ")", ")", ";", "try", "{", "// track time for decode/convert depending on the record type", "long", "decodeStartTime", "=", "System", ".", "nanoTime", "(", ")", ";", "D", "record", "=", "decodeKafkaMessage", "(", "nextValidMessage", ")", ";", "this", ".", "currentPartitionDecodeRecordTime", "+=", "System", ".", "nanoTime", "(", ")", "-", "decodeStartTime", ";", "this", ".", "currentPartitionRecordCount", "++", ";", "this", ".", "currentPartitionTotalSize", "+=", "nextValidMessage", ".", "getValueSizeInBytes", "(", ")", ";", "this", ".", "currentPartitionReadRecordTime", "+=", "System", ".", "nanoTime", "(", ")", "-", "readStartTime", ";", "this", ".", "currentPartitionLastSuccessfulRecord", "=", "record", ";", "return", "record", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "this", ".", "errorPartitions", ".", "add", "(", "this", ".", "currentPartitionIdx", ")", ";", "this", ".", "undecodableMessageCount", "++", ";", "if", "(", "shouldLogError", "(", ")", ")", "{", "LOG", ".", "error", "(", "String", ".", "format", "(", "\"A record from partition %s cannot be decoded.\"", ",", "getCurrentPartition", "(", ")", ")", ",", "t", ")", ";", "}", "incrementErrorCount", "(", ")", ";", "}", "}", "}", "LOG", ".", "info", "(", "\"Finished pulling topic \"", "+", "this", ".", "topicName", ")", ";", "this", ".", "currentPartitionReadRecordTime", "+=", "System", ".", "nanoTime", "(", ")", "-", "readStartTime", ";", "return", "null", ";", "}" ]
Return the next decodable record from the current partition. If the current partition has no more decodable record, move on to the next partition. If all partitions have been processed, return null.
[ "Return", "the", "next", "decodable", "record", "from", "the", "current", "partition", ".", "If", "the", "current", "partition", "has", "no", "more", "decodable", "record", "move", "on", "to", "the", "next", "partition", ".", "If", "all", "partitions", "have", "been", "processed", "return", "null", "." ]
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#L168-L239