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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
25,600 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/utils/ResponseUtils.java | ResponseUtils.contains | public static boolean contains(final byte[] pByte, final SwEnum... pEnum) {
SwEnum val = SwEnum.getSW(pByte);
if (LOGGER.isDebugEnabled() && pByte != null) {
LOGGER.debug("Response Status <"
+ BytesUtils.bytesToStringNoSpace(Arrays.copyOfRange(pByte, Math.max(pByte.length - 2, 0), pByte.length)) + "> : "
+ (val != null ? val.getDetail() : "Unknow"));
}
return val != null && ArrayUtils.contains(pEnum, val);
} | java | public static boolean contains(final byte[] pByte, final SwEnum... pEnum) {
SwEnum val = SwEnum.getSW(pByte);
if (LOGGER.isDebugEnabled() && pByte != null) {
LOGGER.debug("Response Status <"
+ BytesUtils.bytesToStringNoSpace(Arrays.copyOfRange(pByte, Math.max(pByte.length - 2, 0), pByte.length)) + "> : "
+ (val != null ? val.getDetail() : "Unknow"));
}
return val != null && ArrayUtils.contains(pEnum, val);
} | [
"public",
"static",
"boolean",
"contains",
"(",
"final",
"byte",
"[",
"]",
"pByte",
",",
"final",
"SwEnum",
"...",
"pEnum",
")",
"{",
"SwEnum",
"val",
"=",
"SwEnum",
".",
"getSW",
"(",
"pByte",
")",
";",
"if",
"(",
"LOGGER",
".",
"isDebugEnabled",
"(",
")",
"&&",
"pByte",
"!=",
"null",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Response Status <\"",
"+",
"BytesUtils",
".",
"bytesToStringNoSpace",
"(",
"Arrays",
".",
"copyOfRange",
"(",
"pByte",
",",
"Math",
".",
"max",
"(",
"pByte",
".",
"length",
"-",
"2",
",",
"0",
")",
",",
"pByte",
".",
"length",
")",
")",
"+",
"\"> : \"",
"+",
"(",
"val",
"!=",
"null",
"?",
"val",
".",
"getDetail",
"(",
")",
":",
"\"Unknow\"",
")",
")",
";",
"}",
"return",
"val",
"!=",
"null",
"&&",
"ArrayUtils",
".",
"contains",
"(",
"pEnum",
",",
"val",
")",
";",
"}"
] | Method used to check equality with the last command return SW1SW2 ==
pEnum
@param pByte
response to the last command
@param pEnum
responses to check
@return true if the response of the last command is contained in pEnum | [
"Method",
"used",
"to",
"check",
"equality",
"with",
"the",
"last",
"command",
"return",
"SW1SW2",
"==",
"pEnum"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/utils/ResponseUtils.java#L75-L83 |
25,601 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/impl/EmvParser.java | EmvParser.extractPublicData | protected boolean extractPublicData(final Application pApplication) throws CommunicationException {
boolean ret = false;
// Select AID
byte[] data = selectAID(pApplication.getAid());
// check response
// Add SW_6285 to fix Interact issue
if (ResponseUtils.contains(data, SwEnum.SW_9000, SwEnum.SW_6285)) {
// Update reading state
pApplication.setReadingStep(ApplicationStepEnum.SELECTED);
// Parse select response
ret = parse(data, pApplication);
if (ret) {
// Get AID
String aid = BytesUtils.bytesToStringNoSpace(TlvUtil.getValue(data, EmvTags.DEDICATED_FILE_NAME));
String applicationLabel = extractApplicationLabel(data);
if (applicationLabel == null) {
applicationLabel = pApplication.getApplicationLabel();
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Application label:" + applicationLabel + " with Aid:" + aid);
}
template.get().getCard().setType(findCardScheme(aid, template.get().getCard().getCardNumber()));
pApplication.setAid(BytesUtils.fromString(aid));
pApplication.setApplicationLabel(applicationLabel);
pApplication.setLeftPinTry(getLeftPinTry());
pApplication.setTransactionCounter(getTransactionCounter());
template.get().getCard().setState(CardStateEnum.ACTIVE);
}
}
return ret;
} | java | protected boolean extractPublicData(final Application pApplication) throws CommunicationException {
boolean ret = false;
// Select AID
byte[] data = selectAID(pApplication.getAid());
// check response
// Add SW_6285 to fix Interact issue
if (ResponseUtils.contains(data, SwEnum.SW_9000, SwEnum.SW_6285)) {
// Update reading state
pApplication.setReadingStep(ApplicationStepEnum.SELECTED);
// Parse select response
ret = parse(data, pApplication);
if (ret) {
// Get AID
String aid = BytesUtils.bytesToStringNoSpace(TlvUtil.getValue(data, EmvTags.DEDICATED_FILE_NAME));
String applicationLabel = extractApplicationLabel(data);
if (applicationLabel == null) {
applicationLabel = pApplication.getApplicationLabel();
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Application label:" + applicationLabel + " with Aid:" + aid);
}
template.get().getCard().setType(findCardScheme(aid, template.get().getCard().getCardNumber()));
pApplication.setAid(BytesUtils.fromString(aid));
pApplication.setApplicationLabel(applicationLabel);
pApplication.setLeftPinTry(getLeftPinTry());
pApplication.setTransactionCounter(getTransactionCounter());
template.get().getCard().setState(CardStateEnum.ACTIVE);
}
}
return ret;
} | [
"protected",
"boolean",
"extractPublicData",
"(",
"final",
"Application",
"pApplication",
")",
"throws",
"CommunicationException",
"{",
"boolean",
"ret",
"=",
"false",
";",
"// Select AID",
"byte",
"[",
"]",
"data",
"=",
"selectAID",
"(",
"pApplication",
".",
"getAid",
"(",
")",
")",
";",
"// check response",
"// Add SW_6285 to fix Interact issue",
"if",
"(",
"ResponseUtils",
".",
"contains",
"(",
"data",
",",
"SwEnum",
".",
"SW_9000",
",",
"SwEnum",
".",
"SW_6285",
")",
")",
"{",
"// Update reading state",
"pApplication",
".",
"setReadingStep",
"(",
"ApplicationStepEnum",
".",
"SELECTED",
")",
";",
"// Parse select response",
"ret",
"=",
"parse",
"(",
"data",
",",
"pApplication",
")",
";",
"if",
"(",
"ret",
")",
"{",
"// Get AID",
"String",
"aid",
"=",
"BytesUtils",
".",
"bytesToStringNoSpace",
"(",
"TlvUtil",
".",
"getValue",
"(",
"data",
",",
"EmvTags",
".",
"DEDICATED_FILE_NAME",
")",
")",
";",
"String",
"applicationLabel",
"=",
"extractApplicationLabel",
"(",
"data",
")",
";",
"if",
"(",
"applicationLabel",
"==",
"null",
")",
"{",
"applicationLabel",
"=",
"pApplication",
".",
"getApplicationLabel",
"(",
")",
";",
"}",
"if",
"(",
"LOGGER",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Application label:\"",
"+",
"applicationLabel",
"+",
"\" with Aid:\"",
"+",
"aid",
")",
";",
"}",
"template",
".",
"get",
"(",
")",
".",
"getCard",
"(",
")",
".",
"setType",
"(",
"findCardScheme",
"(",
"aid",
",",
"template",
".",
"get",
"(",
")",
".",
"getCard",
"(",
")",
".",
"getCardNumber",
"(",
")",
")",
")",
";",
"pApplication",
".",
"setAid",
"(",
"BytesUtils",
".",
"fromString",
"(",
"aid",
")",
")",
";",
"pApplication",
".",
"setApplicationLabel",
"(",
"applicationLabel",
")",
";",
"pApplication",
".",
"setLeftPinTry",
"(",
"getLeftPinTry",
"(",
")",
")",
";",
"pApplication",
".",
"setTransactionCounter",
"(",
"getTransactionCounter",
"(",
")",
")",
";",
"template",
".",
"get",
"(",
")",
".",
"getCard",
"(",
")",
".",
"setState",
"(",
"CardStateEnum",
".",
"ACTIVE",
")",
";",
"}",
"}",
"return",
"ret",
";",
"}"
] | Read public card data from parameter AID
@param pApplication
application data
@return true if succeed false otherwise
@throws CommunicationException communication error | [
"Read",
"public",
"card",
"data",
"from",
"parameter",
"AID"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/impl/EmvParser.java#L96-L126 |
25,602 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/impl/EmvParser.java | EmvParser.findCardScheme | protected EmvCardScheme findCardScheme(final String pAid, final String pCardNumber) {
EmvCardScheme type = EmvCardScheme.getCardTypeByAid(pAid);
// Get real type for french card
if (type == EmvCardScheme.CB) {
type = EmvCardScheme.getCardTypeByCardNumber(pCardNumber);
if (type != null) {
LOGGER.debug("Real type:" + type.getName());
}
}
return type;
} | java | protected EmvCardScheme findCardScheme(final String pAid, final String pCardNumber) {
EmvCardScheme type = EmvCardScheme.getCardTypeByAid(pAid);
// Get real type for french card
if (type == EmvCardScheme.CB) {
type = EmvCardScheme.getCardTypeByCardNumber(pCardNumber);
if (type != null) {
LOGGER.debug("Real type:" + type.getName());
}
}
return type;
} | [
"protected",
"EmvCardScheme",
"findCardScheme",
"(",
"final",
"String",
"pAid",
",",
"final",
"String",
"pCardNumber",
")",
"{",
"EmvCardScheme",
"type",
"=",
"EmvCardScheme",
".",
"getCardTypeByAid",
"(",
"pAid",
")",
";",
"// Get real type for french card",
"if",
"(",
"type",
"==",
"EmvCardScheme",
".",
"CB",
")",
"{",
"type",
"=",
"EmvCardScheme",
".",
"getCardTypeByCardNumber",
"(",
"pCardNumber",
")",
";",
"if",
"(",
"type",
"!=",
"null",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Real type:\"",
"+",
"type",
".",
"getName",
"(",
")",
")",
";",
"}",
"}",
"return",
"type",
";",
"}"
] | Method used to find the real card scheme
@param pAid
card complete AID
@param pCardNumber
card number
@return card scheme | [
"Method",
"used",
"to",
"find",
"the",
"real",
"card",
"scheme"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/impl/EmvParser.java#L137-L147 |
25,603 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/impl/EmvParser.java | EmvParser.parse | protected boolean parse(final byte[] pSelectResponse, final Application pApplication) throws CommunicationException {
boolean ret = false;
// Get TLV log entry
byte[] logEntry = getLogEntry(pSelectResponse);
// Get PDOL
byte[] pdol = TlvUtil.getValue(pSelectResponse, EmvTags.PDOL);
// Send GPO Command
byte[] gpo = getGetProcessingOptions(pdol);
// Extract Bank data
extractBankData(pSelectResponse);
// Check empty PDOL
if (!ResponseUtils.isSucceed(gpo)) {
if (pdol != null) {
gpo = getGetProcessingOptions(null);
}
// Check response
if (pdol == null || !ResponseUtils.isSucceed(gpo)) {
// Try to read EF 1 and record 1
gpo = template.get().getProvider().transceive(new CommandApdu(CommandEnum.READ_RECORD, 1, 0x0C, 0).toBytes());
if (!ResponseUtils.isSucceed(gpo)) {
return false;
}
}
}
// Update Reading state
pApplication.setReadingStep(ApplicationStepEnum.READ);
// Extract commons card data (number, expire date, ...)
if (extractCommonsCardData(gpo)) {
// Extract log entry
pApplication.setListTransactions(extractLogEntry(logEntry));
ret = true;
}
return ret;
} | java | protected boolean parse(final byte[] pSelectResponse, final Application pApplication) throws CommunicationException {
boolean ret = false;
// Get TLV log entry
byte[] logEntry = getLogEntry(pSelectResponse);
// Get PDOL
byte[] pdol = TlvUtil.getValue(pSelectResponse, EmvTags.PDOL);
// Send GPO Command
byte[] gpo = getGetProcessingOptions(pdol);
// Extract Bank data
extractBankData(pSelectResponse);
// Check empty PDOL
if (!ResponseUtils.isSucceed(gpo)) {
if (pdol != null) {
gpo = getGetProcessingOptions(null);
}
// Check response
if (pdol == null || !ResponseUtils.isSucceed(gpo)) {
// Try to read EF 1 and record 1
gpo = template.get().getProvider().transceive(new CommandApdu(CommandEnum.READ_RECORD, 1, 0x0C, 0).toBytes());
if (!ResponseUtils.isSucceed(gpo)) {
return false;
}
}
}
// Update Reading state
pApplication.setReadingStep(ApplicationStepEnum.READ);
// Extract commons card data (number, expire date, ...)
if (extractCommonsCardData(gpo)) {
// Extract log entry
pApplication.setListTransactions(extractLogEntry(logEntry));
ret = true;
}
return ret;
} | [
"protected",
"boolean",
"parse",
"(",
"final",
"byte",
"[",
"]",
"pSelectResponse",
",",
"final",
"Application",
"pApplication",
")",
"throws",
"CommunicationException",
"{",
"boolean",
"ret",
"=",
"false",
";",
"// Get TLV log entry",
"byte",
"[",
"]",
"logEntry",
"=",
"getLogEntry",
"(",
"pSelectResponse",
")",
";",
"// Get PDOL",
"byte",
"[",
"]",
"pdol",
"=",
"TlvUtil",
".",
"getValue",
"(",
"pSelectResponse",
",",
"EmvTags",
".",
"PDOL",
")",
";",
"// Send GPO Command",
"byte",
"[",
"]",
"gpo",
"=",
"getGetProcessingOptions",
"(",
"pdol",
")",
";",
"// Extract Bank data",
"extractBankData",
"(",
"pSelectResponse",
")",
";",
"// Check empty PDOL",
"if",
"(",
"!",
"ResponseUtils",
".",
"isSucceed",
"(",
"gpo",
")",
")",
"{",
"if",
"(",
"pdol",
"!=",
"null",
")",
"{",
"gpo",
"=",
"getGetProcessingOptions",
"(",
"null",
")",
";",
"}",
"// Check response",
"if",
"(",
"pdol",
"==",
"null",
"||",
"!",
"ResponseUtils",
".",
"isSucceed",
"(",
"gpo",
")",
")",
"{",
"// Try to read EF 1 and record 1",
"gpo",
"=",
"template",
".",
"get",
"(",
")",
".",
"getProvider",
"(",
")",
".",
"transceive",
"(",
"new",
"CommandApdu",
"(",
"CommandEnum",
".",
"READ_RECORD",
",",
"1",
",",
"0x0C",
",",
"0",
")",
".",
"toBytes",
"(",
")",
")",
";",
"if",
"(",
"!",
"ResponseUtils",
".",
"isSucceed",
"(",
"gpo",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"}",
"// Update Reading state",
"pApplication",
".",
"setReadingStep",
"(",
"ApplicationStepEnum",
".",
"READ",
")",
";",
"// Extract commons card data (number, expire date, ...)",
"if",
"(",
"extractCommonsCardData",
"(",
"gpo",
")",
")",
"{",
"// Extract log entry",
"pApplication",
".",
"setListTransactions",
"(",
"extractLogEntry",
"(",
"logEntry",
")",
")",
";",
"ret",
"=",
"true",
";",
"}",
"return",
"ret",
";",
"}"
] | Method used to parse EMV card
@param pSelectResponse
select response data
@param pApplication
application selected
@return true if the parsing succeed false otherwise
@throws CommunicationException communication error | [
"Method",
"used",
"to",
"parse",
"EMV",
"card"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/impl/EmvParser.java#L161-L198 |
25,604 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/impl/EmvParser.java | EmvParser.extractCommonsCardData | protected boolean extractCommonsCardData(final byte[] pGpo) throws CommunicationException {
boolean ret = false;
// Extract data from Message Template 1
byte data[] = TlvUtil.getValue(pGpo, EmvTags.RESPONSE_MESSAGE_TEMPLATE_1);
if (data != null) {
data = ArrayUtils.subarray(data, 2, data.length);
} else { // Extract AFL data from Message template 2
ret = extractTrackData(template.get().getCard(), pGpo);
if (!ret) {
data = TlvUtil.getValue(pGpo, EmvTags.APPLICATION_FILE_LOCATOR);
} else {
extractCardHolderName(pGpo);
}
}
if (data != null) {
// Extract Afl
List<Afl> listAfl = extractAfl(data);
// for each AFL
for (Afl afl : listAfl) {
// check all records
for (int index = afl.getFirstRecord(); index <= afl.getLastRecord(); index++) {
byte[] info = template.get().getProvider()
.transceive(new CommandApdu(CommandEnum.READ_RECORD, index, afl.getSfi() << 3 | 4, 0).toBytes());
// Extract card data
if (ResponseUtils.isSucceed(info)) {
extractCardHolderName(info);
if (extractTrackData(template.get().getCard(), info)) {
return true;
}
}
}
}
}
return ret;
} | java | protected boolean extractCommonsCardData(final byte[] pGpo) throws CommunicationException {
boolean ret = false;
// Extract data from Message Template 1
byte data[] = TlvUtil.getValue(pGpo, EmvTags.RESPONSE_MESSAGE_TEMPLATE_1);
if (data != null) {
data = ArrayUtils.subarray(data, 2, data.length);
} else { // Extract AFL data from Message template 2
ret = extractTrackData(template.get().getCard(), pGpo);
if (!ret) {
data = TlvUtil.getValue(pGpo, EmvTags.APPLICATION_FILE_LOCATOR);
} else {
extractCardHolderName(pGpo);
}
}
if (data != null) {
// Extract Afl
List<Afl> listAfl = extractAfl(data);
// for each AFL
for (Afl afl : listAfl) {
// check all records
for (int index = afl.getFirstRecord(); index <= afl.getLastRecord(); index++) {
byte[] info = template.get().getProvider()
.transceive(new CommandApdu(CommandEnum.READ_RECORD, index, afl.getSfi() << 3 | 4, 0).toBytes());
// Extract card data
if (ResponseUtils.isSucceed(info)) {
extractCardHolderName(info);
if (extractTrackData(template.get().getCard(), info)) {
return true;
}
}
}
}
}
return ret;
} | [
"protected",
"boolean",
"extractCommonsCardData",
"(",
"final",
"byte",
"[",
"]",
"pGpo",
")",
"throws",
"CommunicationException",
"{",
"boolean",
"ret",
"=",
"false",
";",
"// Extract data from Message Template 1",
"byte",
"data",
"[",
"]",
"=",
"TlvUtil",
".",
"getValue",
"(",
"pGpo",
",",
"EmvTags",
".",
"RESPONSE_MESSAGE_TEMPLATE_1",
")",
";",
"if",
"(",
"data",
"!=",
"null",
")",
"{",
"data",
"=",
"ArrayUtils",
".",
"subarray",
"(",
"data",
",",
"2",
",",
"data",
".",
"length",
")",
";",
"}",
"else",
"{",
"// Extract AFL data from Message template 2",
"ret",
"=",
"extractTrackData",
"(",
"template",
".",
"get",
"(",
")",
".",
"getCard",
"(",
")",
",",
"pGpo",
")",
";",
"if",
"(",
"!",
"ret",
")",
"{",
"data",
"=",
"TlvUtil",
".",
"getValue",
"(",
"pGpo",
",",
"EmvTags",
".",
"APPLICATION_FILE_LOCATOR",
")",
";",
"}",
"else",
"{",
"extractCardHolderName",
"(",
"pGpo",
")",
";",
"}",
"}",
"if",
"(",
"data",
"!=",
"null",
")",
"{",
"// Extract Afl",
"List",
"<",
"Afl",
">",
"listAfl",
"=",
"extractAfl",
"(",
"data",
")",
";",
"// for each AFL",
"for",
"(",
"Afl",
"afl",
":",
"listAfl",
")",
"{",
"// check all records",
"for",
"(",
"int",
"index",
"=",
"afl",
".",
"getFirstRecord",
"(",
")",
";",
"index",
"<=",
"afl",
".",
"getLastRecord",
"(",
")",
";",
"index",
"++",
")",
"{",
"byte",
"[",
"]",
"info",
"=",
"template",
".",
"get",
"(",
")",
".",
"getProvider",
"(",
")",
".",
"transceive",
"(",
"new",
"CommandApdu",
"(",
"CommandEnum",
".",
"READ_RECORD",
",",
"index",
",",
"afl",
".",
"getSfi",
"(",
")",
"<<",
"3",
"|",
"4",
",",
"0",
")",
".",
"toBytes",
"(",
")",
")",
";",
"// Extract card data",
"if",
"(",
"ResponseUtils",
".",
"isSucceed",
"(",
"info",
")",
")",
"{",
"extractCardHolderName",
"(",
"info",
")",
";",
"if",
"(",
"extractTrackData",
"(",
"template",
".",
"get",
"(",
")",
".",
"getCard",
"(",
")",
",",
"info",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
"}",
"}",
"return",
"ret",
";",
"}"
] | Method used to extract commons card data
@param pGpo
global processing options response
@return true if the extraction succeed
@throws CommunicationException communication error | [
"Method",
"used",
"to",
"extract",
"commons",
"card",
"data"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/impl/EmvParser.java#L208-L243 |
25,605 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/impl/EmvParser.java | EmvParser.extractAfl | protected List<Afl> extractAfl(final byte[] pAfl) {
List<Afl> list = new ArrayList<Afl>();
ByteArrayInputStream bai = new ByteArrayInputStream(pAfl);
while (bai.available() >= 4) {
Afl afl = new Afl();
afl.setSfi(bai.read() >> 3);
afl.setFirstRecord(bai.read());
afl.setLastRecord(bai.read());
afl.setOfflineAuthentication(bai.read() == 1);
list.add(afl);
}
return list;
} | java | protected List<Afl> extractAfl(final byte[] pAfl) {
List<Afl> list = new ArrayList<Afl>();
ByteArrayInputStream bai = new ByteArrayInputStream(pAfl);
while (bai.available() >= 4) {
Afl afl = new Afl();
afl.setSfi(bai.read() >> 3);
afl.setFirstRecord(bai.read());
afl.setLastRecord(bai.read());
afl.setOfflineAuthentication(bai.read() == 1);
list.add(afl);
}
return list;
} | [
"protected",
"List",
"<",
"Afl",
">",
"extractAfl",
"(",
"final",
"byte",
"[",
"]",
"pAfl",
")",
"{",
"List",
"<",
"Afl",
">",
"list",
"=",
"new",
"ArrayList",
"<",
"Afl",
">",
"(",
")",
";",
"ByteArrayInputStream",
"bai",
"=",
"new",
"ByteArrayInputStream",
"(",
"pAfl",
")",
";",
"while",
"(",
"bai",
".",
"available",
"(",
")",
">=",
"4",
")",
"{",
"Afl",
"afl",
"=",
"new",
"Afl",
"(",
")",
";",
"afl",
".",
"setSfi",
"(",
"bai",
".",
"read",
"(",
")",
">>",
"3",
")",
";",
"afl",
".",
"setFirstRecord",
"(",
"bai",
".",
"read",
"(",
")",
")",
";",
"afl",
".",
"setLastRecord",
"(",
"bai",
".",
"read",
"(",
")",
")",
";",
"afl",
".",
"setOfflineAuthentication",
"(",
"bai",
".",
"read",
"(",
")",
"==",
"1",
")",
";",
"list",
".",
"add",
"(",
"afl",
")",
";",
"}",
"return",
"list",
";",
"}"
] | Extract list of application file locator from Afl response
@param pAfl
AFL data
@return list of AFL | [
"Extract",
"list",
"of",
"application",
"file",
"locator",
"from",
"Afl",
"response"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/impl/EmvParser.java#L253-L265 |
25,606 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/impl/EmvParser.java | EmvParser.getGetProcessingOptions | protected byte[] getGetProcessingOptions(final byte[] pPdol) throws CommunicationException {
// List Tag and length from PDOL
List<TagAndLength> list = TlvUtil.parseTagAndLength(pPdol);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
out.write(EmvTags.COMMAND_TEMPLATE.getTagBytes()); // COMMAND
// TEMPLATE
out.write(TlvUtil.getLength(list)); // ADD total length
if (list != null) {
for (TagAndLength tl : list) {
out.write(template.get().getTerminal().constructValue(tl));
}
}
} catch (IOException ioe) {
LOGGER.error("Construct GPO Command:" + ioe.getMessage(), ioe);
}
return template.get().getProvider().transceive(new CommandApdu(CommandEnum.GPO, out.toByteArray(), 0).toBytes());
} | java | protected byte[] getGetProcessingOptions(final byte[] pPdol) throws CommunicationException {
// List Tag and length from PDOL
List<TagAndLength> list = TlvUtil.parseTagAndLength(pPdol);
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
out.write(EmvTags.COMMAND_TEMPLATE.getTagBytes()); // COMMAND
// TEMPLATE
out.write(TlvUtil.getLength(list)); // ADD total length
if (list != null) {
for (TagAndLength tl : list) {
out.write(template.get().getTerminal().constructValue(tl));
}
}
} catch (IOException ioe) {
LOGGER.error("Construct GPO Command:" + ioe.getMessage(), ioe);
}
return template.get().getProvider().transceive(new CommandApdu(CommandEnum.GPO, out.toByteArray(), 0).toBytes());
} | [
"protected",
"byte",
"[",
"]",
"getGetProcessingOptions",
"(",
"final",
"byte",
"[",
"]",
"pPdol",
")",
"throws",
"CommunicationException",
"{",
"// List Tag and length from PDOL",
"List",
"<",
"TagAndLength",
">",
"list",
"=",
"TlvUtil",
".",
"parseTagAndLength",
"(",
"pPdol",
")",
";",
"ByteArrayOutputStream",
"out",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"try",
"{",
"out",
".",
"write",
"(",
"EmvTags",
".",
"COMMAND_TEMPLATE",
".",
"getTagBytes",
"(",
")",
")",
";",
"// COMMAND",
"// TEMPLATE",
"out",
".",
"write",
"(",
"TlvUtil",
".",
"getLength",
"(",
"list",
")",
")",
";",
"// ADD total length",
"if",
"(",
"list",
"!=",
"null",
")",
"{",
"for",
"(",
"TagAndLength",
"tl",
":",
"list",
")",
"{",
"out",
".",
"write",
"(",
"template",
".",
"get",
"(",
")",
".",
"getTerminal",
"(",
")",
".",
"constructValue",
"(",
"tl",
")",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"IOException",
"ioe",
")",
"{",
"LOGGER",
".",
"error",
"(",
"\"Construct GPO Command:\"",
"+",
"ioe",
".",
"getMessage",
"(",
")",
",",
"ioe",
")",
";",
"}",
"return",
"template",
".",
"get",
"(",
")",
".",
"getProvider",
"(",
")",
".",
"transceive",
"(",
"new",
"CommandApdu",
"(",
"CommandEnum",
".",
"GPO",
",",
"out",
".",
"toByteArray",
"(",
")",
",",
"0",
")",
".",
"toBytes",
"(",
")",
")",
";",
"}"
] | Method used to create GPO command and execute it
@param pPdol
PDOL raw data
@return return data
@throws CommunicationException communication error | [
"Method",
"used",
"to",
"create",
"GPO",
"command",
"and",
"execute",
"it"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/impl/EmvParser.java#L275-L292 |
25,607 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/impl/EmvParser.java | EmvParser.extractTrackData | protected boolean extractTrackData(final EmvCard pEmvCard, final byte[] pData) {
template.get().getCard().setTrack1(TrackUtils.extractTrack1Data(TlvUtil.getValue(pData, EmvTags.TRACK1_DATA)));
template.get().getCard().setTrack2(TrackUtils.extractTrack2EquivalentData(TlvUtil.getValue(pData, EmvTags.TRACK_2_EQV_DATA, EmvTags.TRACK2_DATA)));
return pEmvCard.getTrack1() != null || pEmvCard.getTrack2() != null;
} | java | protected boolean extractTrackData(final EmvCard pEmvCard, final byte[] pData) {
template.get().getCard().setTrack1(TrackUtils.extractTrack1Data(TlvUtil.getValue(pData, EmvTags.TRACK1_DATA)));
template.get().getCard().setTrack2(TrackUtils.extractTrack2EquivalentData(TlvUtil.getValue(pData, EmvTags.TRACK_2_EQV_DATA, EmvTags.TRACK2_DATA)));
return pEmvCard.getTrack1() != null || pEmvCard.getTrack2() != null;
} | [
"protected",
"boolean",
"extractTrackData",
"(",
"final",
"EmvCard",
"pEmvCard",
",",
"final",
"byte",
"[",
"]",
"pData",
")",
"{",
"template",
".",
"get",
"(",
")",
".",
"getCard",
"(",
")",
".",
"setTrack1",
"(",
"TrackUtils",
".",
"extractTrack1Data",
"(",
"TlvUtil",
".",
"getValue",
"(",
"pData",
",",
"EmvTags",
".",
"TRACK1_DATA",
")",
")",
")",
";",
"template",
".",
"get",
"(",
")",
".",
"getCard",
"(",
")",
".",
"setTrack2",
"(",
"TrackUtils",
".",
"extractTrack2EquivalentData",
"(",
"TlvUtil",
".",
"getValue",
"(",
"pData",
",",
"EmvTags",
".",
"TRACK_2_EQV_DATA",
",",
"EmvTags",
".",
"TRACK2_DATA",
")",
")",
")",
";",
"return",
"pEmvCard",
".",
"getTrack1",
"(",
")",
"!=",
"null",
"||",
"pEmvCard",
".",
"getTrack2",
"(",
")",
"!=",
"null",
";",
"}"
] | Method used to extract track data from response
@param pEmvCard
Card data
@param pData
data send by card
@return true if track 1 or track 2 can be read | [
"Method",
"used",
"to",
"extract",
"track",
"data",
"from",
"response"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/impl/EmvParser.java#L303-L307 |
25,608 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/annotation/AnnotationUtils.java | AnnotationUtils.extractAnnotation | private void extractAnnotation() {
for (Class<? extends IFile> clazz : LISTE_CLASS) {
Map<ITag, AnnotationData> maps = new HashMap<ITag, AnnotationData>();
Set<AnnotationData> set = new TreeSet<AnnotationData>();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
AnnotationData param = new AnnotationData();
field.setAccessible(true);
param.setField(field);
Data annotation = field.getAnnotation(Data.class);
if (annotation != null) {
param.initFromAnnotation(annotation);
maps.put(param.getTag(), param);
try {
set.add((AnnotationData) param.clone());
} catch (CloneNotSupportedException e) {
// do nothing
}
}
}
mapSet.put(clazz.getName(), set);
map.put(clazz.getName(), maps);
}
} | java | private void extractAnnotation() {
for (Class<? extends IFile> clazz : LISTE_CLASS) {
Map<ITag, AnnotationData> maps = new HashMap<ITag, AnnotationData>();
Set<AnnotationData> set = new TreeSet<AnnotationData>();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
AnnotationData param = new AnnotationData();
field.setAccessible(true);
param.setField(field);
Data annotation = field.getAnnotation(Data.class);
if (annotation != null) {
param.initFromAnnotation(annotation);
maps.put(param.getTag(), param);
try {
set.add((AnnotationData) param.clone());
} catch (CloneNotSupportedException e) {
// do nothing
}
}
}
mapSet.put(clazz.getName(), set);
map.put(clazz.getName(), maps);
}
} | [
"private",
"void",
"extractAnnotation",
"(",
")",
"{",
"for",
"(",
"Class",
"<",
"?",
"extends",
"IFile",
">",
"clazz",
":",
"LISTE_CLASS",
")",
"{",
"Map",
"<",
"ITag",
",",
"AnnotationData",
">",
"maps",
"=",
"new",
"HashMap",
"<",
"ITag",
",",
"AnnotationData",
">",
"(",
")",
";",
"Set",
"<",
"AnnotationData",
">",
"set",
"=",
"new",
"TreeSet",
"<",
"AnnotationData",
">",
"(",
")",
";",
"Field",
"[",
"]",
"fields",
"=",
"clazz",
".",
"getDeclaredFields",
"(",
")",
";",
"for",
"(",
"Field",
"field",
":",
"fields",
")",
"{",
"AnnotationData",
"param",
"=",
"new",
"AnnotationData",
"(",
")",
";",
"field",
".",
"setAccessible",
"(",
"true",
")",
";",
"param",
".",
"setField",
"(",
"field",
")",
";",
"Data",
"annotation",
"=",
"field",
".",
"getAnnotation",
"(",
"Data",
".",
"class",
")",
";",
"if",
"(",
"annotation",
"!=",
"null",
")",
"{",
"param",
".",
"initFromAnnotation",
"(",
"annotation",
")",
";",
"maps",
".",
"put",
"(",
"param",
".",
"getTag",
"(",
")",
",",
"param",
")",
";",
"try",
"{",
"set",
".",
"add",
"(",
"(",
"AnnotationData",
")",
"param",
".",
"clone",
"(",
")",
")",
";",
"}",
"catch",
"(",
"CloneNotSupportedException",
"e",
")",
"{",
"// do nothing",
"}",
"}",
"}",
"mapSet",
".",
"put",
"(",
"clazz",
".",
"getName",
"(",
")",
",",
"set",
")",
";",
"map",
".",
"put",
"(",
"clazz",
".",
"getName",
"(",
")",
",",
"maps",
")",
";",
"}",
"}"
] | Method to extract all annotation information and store them in the map | [
"Method",
"to",
"extract",
"all",
"annotation",
"information",
"and",
"store",
"them",
"in",
"the",
"map"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/annotation/AnnotationUtils.java#L75-L100 |
25,609 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/model/EmvCard.java | EmvCard.getHolderLastname | public String getHolderLastname() {
String ret = holderLastname;
if (ret == null && track1 != null) {
ret = track1.getHolderLastname();
}
return ret;
} | java | public String getHolderLastname() {
String ret = holderLastname;
if (ret == null && track1 != null) {
ret = track1.getHolderLastname();
}
return ret;
} | [
"public",
"String",
"getHolderLastname",
"(",
")",
"{",
"String",
"ret",
"=",
"holderLastname",
";",
"if",
"(",
"ret",
"==",
"null",
"&&",
"track1",
"!=",
"null",
")",
"{",
"ret",
"=",
"track1",
".",
"getHolderLastname",
"(",
")",
";",
"}",
"return",
"ret",
";",
"}"
] | Method used to get the field holderLastname
@return the holderLastname | [
"Method",
"used",
"to",
"get",
"the",
"field",
"holderLastname"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/model/EmvCard.java#L104-L110 |
25,610 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/model/EmvCard.java | EmvCard.getHolderFirstname | public String getHolderFirstname() {
String ret = holderFirstname;
if (ret == null && track1 != null) {
ret = track1.getHolderFirstname();
}
return ret;
} | java | public String getHolderFirstname() {
String ret = holderFirstname;
if (ret == null && track1 != null) {
ret = track1.getHolderFirstname();
}
return ret;
} | [
"public",
"String",
"getHolderFirstname",
"(",
")",
"{",
"String",
"ret",
"=",
"holderFirstname",
";",
"if",
"(",
"ret",
"==",
"null",
"&&",
"track1",
"!=",
"null",
")",
"{",
"ret",
"=",
"track1",
".",
"getHolderFirstname",
"(",
")",
";",
"}",
"return",
"ret",
";",
"}"
] | Method used to get the field holderFirstname
@return the holderFirstname | [
"Method",
"used",
"to",
"get",
"the",
"field",
"holderFirstname"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/model/EmvCard.java#L127-L133 |
25,611 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/model/EmvCard.java | EmvCard.getCardNumber | public String getCardNumber() {
String ret = null;
if (track2 != null) {
ret = track2.getCardNumber();
}
if (ret == null && track1 != null) {
ret = track1.getCardNumber();
}
return ret;
} | java | public String getCardNumber() {
String ret = null;
if (track2 != null) {
ret = track2.getCardNumber();
}
if (ret == null && track1 != null) {
ret = track1.getCardNumber();
}
return ret;
} | [
"public",
"String",
"getCardNumber",
"(",
")",
"{",
"String",
"ret",
"=",
"null",
";",
"if",
"(",
"track2",
"!=",
"null",
")",
"{",
"ret",
"=",
"track2",
".",
"getCardNumber",
"(",
")",
";",
"}",
"if",
"(",
"ret",
"==",
"null",
"&&",
"track1",
"!=",
"null",
")",
"{",
"ret",
"=",
"track1",
".",
"getCardNumber",
"(",
")",
";",
"}",
"return",
"ret",
";",
"}"
] | Method used to get the field cardNumber
@return the cardNumber | [
"Method",
"used",
"to",
"get",
"the",
"field",
"cardNumber"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/model/EmvCard.java#L150-L159 |
25,612 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/model/EmvCard.java | EmvCard.getExpireDate | public Date getExpireDate() {
Date ret = null;
if (track2 != null) {
ret = track2.getExpireDate();
}
if (ret == null && track1 != null) {
ret = track1.getExpireDate();
}
return ret;
} | java | public Date getExpireDate() {
Date ret = null;
if (track2 != null) {
ret = track2.getExpireDate();
}
if (ret == null && track1 != null) {
ret = track1.getExpireDate();
}
return ret;
} | [
"public",
"Date",
"getExpireDate",
"(",
")",
"{",
"Date",
"ret",
"=",
"null",
";",
"if",
"(",
"track2",
"!=",
"null",
")",
"{",
"ret",
"=",
"track2",
".",
"getExpireDate",
"(",
")",
";",
"}",
"if",
"(",
"ret",
"==",
"null",
"&&",
"track1",
"!=",
"null",
")",
"{",
"ret",
"=",
"track1",
".",
"getExpireDate",
"(",
")",
";",
"}",
"return",
"ret",
";",
"}"
] | Method used to get the field expireDate
@return the expireDate | [
"Method",
"used",
"to",
"get",
"the",
"field",
"expireDate"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/model/EmvCard.java#L166-L175 |
25,613 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/utils/TlvUtil.java | TlvUtil.getTagValueAsString | private static String getTagValueAsString(final ITag tag, final byte[] value) {
StringBuilder buf = new StringBuilder();
switch (tag.getTagValueType()) {
case TEXT:
buf.append("=");
buf.append(new String(value));
break;
case NUMERIC:
buf.append("NUMERIC");
break;
case BINARY:
buf.append("BINARY");
break;
case MIXED:
buf.append("=");
buf.append(getSafePrintChars(value));
break;
case DOL:
buf.append("");
break;
default:
break;
}
return buf.toString();
} | java | private static String getTagValueAsString(final ITag tag, final byte[] value) {
StringBuilder buf = new StringBuilder();
switch (tag.getTagValueType()) {
case TEXT:
buf.append("=");
buf.append(new String(value));
break;
case NUMERIC:
buf.append("NUMERIC");
break;
case BINARY:
buf.append("BINARY");
break;
case MIXED:
buf.append("=");
buf.append(getSafePrintChars(value));
break;
case DOL:
buf.append("");
break;
default:
break;
}
return buf.toString();
} | [
"private",
"static",
"String",
"getTagValueAsString",
"(",
"final",
"ITag",
"tag",
",",
"final",
"byte",
"[",
"]",
"value",
")",
"{",
"StringBuilder",
"buf",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"switch",
"(",
"tag",
".",
"getTagValueType",
"(",
")",
")",
"{",
"case",
"TEXT",
":",
"buf",
".",
"append",
"(",
"\"=\"",
")",
";",
"buf",
".",
"append",
"(",
"new",
"String",
"(",
"value",
")",
")",
";",
"break",
";",
"case",
"NUMERIC",
":",
"buf",
".",
"append",
"(",
"\"NUMERIC\"",
")",
";",
"break",
";",
"case",
"BINARY",
":",
"buf",
".",
"append",
"(",
"\"BINARY\"",
")",
";",
"break",
";",
"case",
"MIXED",
":",
"buf",
".",
"append",
"(",
"\"=\"",
")",
";",
"buf",
".",
"append",
"(",
"getSafePrintChars",
"(",
"value",
")",
")",
";",
"break",
";",
"case",
"DOL",
":",
"buf",
".",
"append",
"(",
"\"\"",
")",
";",
"break",
";",
"default",
":",
"break",
";",
"}",
"return",
"buf",
".",
"toString",
"(",
")",
";",
"}"
] | Method used get Tag value as String
@param tag
tag type
@param value
tag value
@return | [
"Method",
"used",
"get",
"Tag",
"value",
"as",
"String"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/utils/TlvUtil.java#L127-L153 |
25,614 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/utils/TlvUtil.java | TlvUtil.parseTagAndLength | public static List<TagAndLength> parseTagAndLength(final byte[] data) {
List<TagAndLength> tagAndLengthList = new ArrayList<TagAndLength>();
if (data != null) {
TLVInputStream stream = new TLVInputStream(new ByteArrayInputStream(data));
try {
while (stream.available() > 0) {
if (stream.available() < 2) {
throw new TlvException("Data length < 2 : " + stream.available());
}
ITag tag = searchTagById(stream.readTag());
int tagValueLength = stream.readLength();
tagAndLengthList.add(new TagAndLength(tag, tagValueLength));
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(stream);
}
}
return tagAndLengthList;
} | java | public static List<TagAndLength> parseTagAndLength(final byte[] data) {
List<TagAndLength> tagAndLengthList = new ArrayList<TagAndLength>();
if (data != null) {
TLVInputStream stream = new TLVInputStream(new ByteArrayInputStream(data));
try {
while (stream.available() > 0) {
if (stream.available() < 2) {
throw new TlvException("Data length < 2 : " + stream.available());
}
ITag tag = searchTagById(stream.readTag());
int tagValueLength = stream.readLength();
tagAndLengthList.add(new TagAndLength(tag, tagValueLength));
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(stream);
}
}
return tagAndLengthList;
} | [
"public",
"static",
"List",
"<",
"TagAndLength",
">",
"parseTagAndLength",
"(",
"final",
"byte",
"[",
"]",
"data",
")",
"{",
"List",
"<",
"TagAndLength",
">",
"tagAndLengthList",
"=",
"new",
"ArrayList",
"<",
"TagAndLength",
">",
"(",
")",
";",
"if",
"(",
"data",
"!=",
"null",
")",
"{",
"TLVInputStream",
"stream",
"=",
"new",
"TLVInputStream",
"(",
"new",
"ByteArrayInputStream",
"(",
"data",
")",
")",
";",
"try",
"{",
"while",
"(",
"stream",
".",
"available",
"(",
")",
">",
"0",
")",
"{",
"if",
"(",
"stream",
".",
"available",
"(",
")",
"<",
"2",
")",
"{",
"throw",
"new",
"TlvException",
"(",
"\"Data length < 2 : \"",
"+",
"stream",
".",
"available",
"(",
")",
")",
";",
"}",
"ITag",
"tag",
"=",
"searchTagById",
"(",
"stream",
".",
"readTag",
"(",
")",
")",
";",
"int",
"tagValueLength",
"=",
"stream",
".",
"readLength",
"(",
")",
";",
"tagAndLengthList",
".",
"add",
"(",
"new",
"TagAndLength",
"(",
"tag",
",",
"tagValueLength",
")",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOGGER",
".",
"error",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"finally",
"{",
"IOUtils",
".",
"closeQuietly",
"(",
"stream",
")",
";",
"}",
"}",
"return",
"tagAndLengthList",
";",
"}"
] | Method used to parser Tag and length
@param data
data to parse
@return tag and length | [
"Method",
"used",
"to",
"parser",
"Tag",
"and",
"length"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/utils/TlvUtil.java#L162-L185 |
25,615 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/utils/TlvUtil.java | TlvUtil.getlistTLV | public static List<TLV> getlistTLV(final byte[] pData, final ITag... pTag) {
List<TLV> list = new ArrayList<TLV>();
TLVInputStream stream = new TLVInputStream(new ByteArrayInputStream(pData));
try {
while (stream.available() > 0) {
TLV tlv = TlvUtil.getNextTLV(stream);
if (tlv == null) {
break;
}
if (ArrayUtils.contains(pTag, tlv.getTag())) {
list.add(tlv);
} else if (tlv.getTag().isConstructed()) {
list.addAll(TlvUtil.getlistTLV(tlv.getValueBytes(), pTag));
}
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(stream);
}
return list;
} | java | public static List<TLV> getlistTLV(final byte[] pData, final ITag... pTag) {
List<TLV> list = new ArrayList<TLV>();
TLVInputStream stream = new TLVInputStream(new ByteArrayInputStream(pData));
try {
while (stream.available() > 0) {
TLV tlv = TlvUtil.getNextTLV(stream);
if (tlv == null) {
break;
}
if (ArrayUtils.contains(pTag, tlv.getTag())) {
list.add(tlv);
} else if (tlv.getTag().isConstructed()) {
list.addAll(TlvUtil.getlistTLV(tlv.getValueBytes(), pTag));
}
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(stream);
}
return list;
} | [
"public",
"static",
"List",
"<",
"TLV",
">",
"getlistTLV",
"(",
"final",
"byte",
"[",
"]",
"pData",
",",
"final",
"ITag",
"...",
"pTag",
")",
"{",
"List",
"<",
"TLV",
">",
"list",
"=",
"new",
"ArrayList",
"<",
"TLV",
">",
"(",
")",
";",
"TLVInputStream",
"stream",
"=",
"new",
"TLVInputStream",
"(",
"new",
"ByteArrayInputStream",
"(",
"pData",
")",
")",
";",
"try",
"{",
"while",
"(",
"stream",
".",
"available",
"(",
")",
">",
"0",
")",
"{",
"TLV",
"tlv",
"=",
"TlvUtil",
".",
"getNextTLV",
"(",
"stream",
")",
";",
"if",
"(",
"tlv",
"==",
"null",
")",
"{",
"break",
";",
"}",
"if",
"(",
"ArrayUtils",
".",
"contains",
"(",
"pTag",
",",
"tlv",
".",
"getTag",
"(",
")",
")",
")",
"{",
"list",
".",
"add",
"(",
"tlv",
")",
";",
"}",
"else",
"if",
"(",
"tlv",
".",
"getTag",
"(",
")",
".",
"isConstructed",
"(",
")",
")",
"{",
"list",
".",
"addAll",
"(",
"TlvUtil",
".",
"getlistTLV",
"(",
"tlv",
".",
"getValueBytes",
"(",
")",
",",
"pTag",
")",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOGGER",
".",
"error",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"finally",
"{",
"IOUtils",
".",
"closeQuietly",
"(",
"stream",
")",
";",
"}",
"return",
"list",
";",
"}"
] | Method used to get the list of TLV corresponding to tags specified in parameters
@param pData
data to parse
@param pTag
tags to find
@return the list of TLV | [
"Method",
"used",
"to",
"get",
"the",
"list",
"of",
"TLV",
"corresponding",
"to",
"tags",
"specified",
"in",
"parameters"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/utils/TlvUtil.java#L239-L265 |
25,616 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/utils/TlvUtil.java | TlvUtil.getValue | public static byte[] getValue(final byte[] pData, final ITag... pTag) {
byte[] ret = null;
if (pData != null) {
TLVInputStream stream = new TLVInputStream(new ByteArrayInputStream(pData));
try {
while (stream.available() > 0) {
TLV tlv = TlvUtil.getNextTLV(stream);
if (tlv == null) {
break;
}
if (ArrayUtils.contains(pTag, tlv.getTag())) {
return tlv.getValueBytes();
} else if (tlv.getTag().isConstructed()) {
ret = TlvUtil.getValue(tlv.getValueBytes(), pTag);
if (ret != null) {
break;
}
}
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(stream);
}
}
return ret;
} | java | public static byte[] getValue(final byte[] pData, final ITag... pTag) {
byte[] ret = null;
if (pData != null) {
TLVInputStream stream = new TLVInputStream(new ByteArrayInputStream(pData));
try {
while (stream.available() > 0) {
TLV tlv = TlvUtil.getNextTLV(stream);
if (tlv == null) {
break;
}
if (ArrayUtils.contains(pTag, tlv.getTag())) {
return tlv.getValueBytes();
} else if (tlv.getTag().isConstructed()) {
ret = TlvUtil.getValue(tlv.getValueBytes(), pTag);
if (ret != null) {
break;
}
}
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(stream);
}
}
return ret;
} | [
"public",
"static",
"byte",
"[",
"]",
"getValue",
"(",
"final",
"byte",
"[",
"]",
"pData",
",",
"final",
"ITag",
"...",
"pTag",
")",
"{",
"byte",
"[",
"]",
"ret",
"=",
"null",
";",
"if",
"(",
"pData",
"!=",
"null",
")",
"{",
"TLVInputStream",
"stream",
"=",
"new",
"TLVInputStream",
"(",
"new",
"ByteArrayInputStream",
"(",
"pData",
")",
")",
";",
"try",
"{",
"while",
"(",
"stream",
".",
"available",
"(",
")",
">",
"0",
")",
"{",
"TLV",
"tlv",
"=",
"TlvUtil",
".",
"getNextTLV",
"(",
"stream",
")",
";",
"if",
"(",
"tlv",
"==",
"null",
")",
"{",
"break",
";",
"}",
"if",
"(",
"ArrayUtils",
".",
"contains",
"(",
"pTag",
",",
"tlv",
".",
"getTag",
"(",
")",
")",
")",
"{",
"return",
"tlv",
".",
"getValueBytes",
"(",
")",
";",
"}",
"else",
"if",
"(",
"tlv",
".",
"getTag",
"(",
")",
".",
"isConstructed",
"(",
")",
")",
"{",
"ret",
"=",
"TlvUtil",
".",
"getValue",
"(",
"tlv",
".",
"getValueBytes",
"(",
")",
",",
"pTag",
")",
";",
"if",
"(",
"ret",
"!=",
"null",
")",
"{",
"break",
";",
"}",
"}",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOGGER",
".",
"error",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"finally",
"{",
"IOUtils",
".",
"closeQuietly",
"(",
"stream",
")",
";",
"}",
"}",
"return",
"ret",
";",
"}"
] | Method used to get Tag value
@param pData
data
@param pTag
tag to find
@return tag value or null | [
"Method",
"used",
"to",
"get",
"Tag",
"value"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/utils/TlvUtil.java#L276-L308 |
25,617 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/utils/TlvUtil.java | TlvUtil.getLength | public static int getLength(final List<TagAndLength> pList) {
int ret = 0;
if (pList != null) {
for (TagAndLength tl : pList) {
ret += tl.getLength();
}
}
return ret;
} | java | public static int getLength(final List<TagAndLength> pList) {
int ret = 0;
if (pList != null) {
for (TagAndLength tl : pList) {
ret += tl.getLength();
}
}
return ret;
} | [
"public",
"static",
"int",
"getLength",
"(",
"final",
"List",
"<",
"TagAndLength",
">",
"pList",
")",
"{",
"int",
"ret",
"=",
"0",
";",
"if",
"(",
"pList",
"!=",
"null",
")",
"{",
"for",
"(",
"TagAndLength",
"tl",
":",
"pList",
")",
"{",
"ret",
"+=",
"tl",
".",
"getLength",
"(",
")",
";",
"}",
"}",
"return",
"ret",
";",
"}"
] | Method used to get length of all Tags
@param pList
tag length list
@return the sum of tag length | [
"Method",
"used",
"to",
"get",
"length",
"of",
"all",
"Tags"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/utils/TlvUtil.java#L448-L456 |
25,618 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/EmvTemplate.java | EmvTemplate.addDefaultParsers | private void addDefaultParsers() {
parsers = new ArrayList<IParser>();
parsers.add(new GeldKarteParser(this));
parsers.add(new EmvParser(this));
} | java | private void addDefaultParsers() {
parsers = new ArrayList<IParser>();
parsers.add(new GeldKarteParser(this));
parsers.add(new EmvParser(this));
} | [
"private",
"void",
"addDefaultParsers",
"(",
")",
"{",
"parsers",
"=",
"new",
"ArrayList",
"<",
"IParser",
">",
"(",
")",
";",
"parsers",
".",
"add",
"(",
"new",
"GeldKarteParser",
"(",
"this",
")",
")",
";",
"parsers",
".",
"add",
"(",
"new",
"EmvParser",
"(",
"this",
")",
")",
";",
"}"
] | Add default parser implementation | [
"Add",
"default",
"parser",
"implementation"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/EmvTemplate.java#L323-L327 |
25,619 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/EmvTemplate.java | EmvTemplate.addParsers | public EmvTemplate addParsers(final IParser... pParsers) {
if (pParsers != null) {
for (IParser parser : pParsers) {
parsers.add(0, parser);
}
}
return this;
} | java | public EmvTemplate addParsers(final IParser... pParsers) {
if (pParsers != null) {
for (IParser parser : pParsers) {
parsers.add(0, parser);
}
}
return this;
} | [
"public",
"EmvTemplate",
"addParsers",
"(",
"final",
"IParser",
"...",
"pParsers",
")",
"{",
"if",
"(",
"pParsers",
"!=",
"null",
")",
"{",
"for",
"(",
"IParser",
"parser",
":",
"pParsers",
")",
"{",
"parsers",
".",
"add",
"(",
"0",
",",
"parser",
")",
";",
"}",
"}",
"return",
"this",
";",
"}"
] | Method used to add a list of parser to the current EMV template
@param pParsers
parser implementation to add
@return current EmvTemplate | [
"Method",
"used",
"to",
"add",
"a",
"list",
"of",
"parser",
"to",
"the",
"current",
"EMV",
"template"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/EmvTemplate.java#L336-L343 |
25,620 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/EmvTemplate.java | EmvTemplate.readEmvCard | public EmvCard readEmvCard() throws CommunicationException {
// Read CPLC Infos
if (config.readCplc){
readCPLCInfos();
}
// Update ATS or ATR
if (config.readAt){
card.setAt(BytesUtils.bytesToStringNoSpace(provider.getAt()));
card.setAtrDescription(config.contactLess ? AtrUtils.getDescriptionFromAts(card.getAt()) : AtrUtils.getDescription(card.getAt()));
}
// use PSE first
if (!readWithPSE()) {
// Find with AID
readWithAID();
}
return card;
} | java | public EmvCard readEmvCard() throws CommunicationException {
// Read CPLC Infos
if (config.readCplc){
readCPLCInfos();
}
// Update ATS or ATR
if (config.readAt){
card.setAt(BytesUtils.bytesToStringNoSpace(provider.getAt()));
card.setAtrDescription(config.contactLess ? AtrUtils.getDescriptionFromAts(card.getAt()) : AtrUtils.getDescription(card.getAt()));
}
// use PSE first
if (!readWithPSE()) {
// Find with AID
readWithAID();
}
return card;
} | [
"public",
"EmvCard",
"readEmvCard",
"(",
")",
"throws",
"CommunicationException",
"{",
"// Read CPLC Infos",
"if",
"(",
"config",
".",
"readCplc",
")",
"{",
"readCPLCInfos",
"(",
")",
";",
"}",
"// Update ATS or ATR",
"if",
"(",
"config",
".",
"readAt",
")",
"{",
"card",
".",
"setAt",
"(",
"BytesUtils",
".",
"bytesToStringNoSpace",
"(",
"provider",
".",
"getAt",
"(",
")",
")",
")",
";",
"card",
".",
"setAtrDescription",
"(",
"config",
".",
"contactLess",
"?",
"AtrUtils",
".",
"getDescriptionFromAts",
"(",
"card",
".",
"getAt",
"(",
")",
")",
":",
"AtrUtils",
".",
"getDescription",
"(",
"card",
".",
"getAt",
"(",
")",
")",
")",
";",
"}",
"// use PSE first",
"if",
"(",
"!",
"readWithPSE",
"(",
")",
")",
"{",
"// Find with AID",
"readWithAID",
"(",
")",
";",
"}",
"return",
"card",
";",
"}"
] | Method used to read public data from EMV card
@return data read from card or null if any provider match the card type
@throws CommunicationException communication error | [
"Method",
"used",
"to",
"read",
"public",
"data",
"from",
"EMV",
"card"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/EmvTemplate.java#L351-L369 |
25,621 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/EmvTemplate.java | EmvTemplate.readWithPSE | protected boolean readWithPSE() throws CommunicationException {
boolean ret = false;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Try to read card with Payment System Environment");
}
// Select the payment environment PPSE or PSE directory
byte[] data = selectPaymentEnvironment();
if (ResponseUtils.isSucceed(data)) {
// Parse FCI Template
card.getApplications().addAll(parseFCIProprietaryTemplate(data));
Collections.sort(card.getApplications());
// For each application
for (Application app : card.getApplications()) {
boolean status = false;
String applicationAid = BytesUtils.bytesToStringNoSpace(app.getAid());
for (IParser impl : parsers) {
if (impl.getId() != null && impl.getId().matcher(applicationAid).matches()) {
status = impl.parse(app);
break;
}
}
if (!ret && status) {
ret = status;
if (!config.readAllAids) {
break;
}
}
}
if (!ret) {
card.setState(CardStateEnum.LOCKED);
}
} else if (LOGGER.isDebugEnabled()) {
LOGGER.debug((config.contactLess ? "PPSE" : "PSE") + " not found -> Use kown AID");
}
return ret;
} | java | protected boolean readWithPSE() throws CommunicationException {
boolean ret = false;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Try to read card with Payment System Environment");
}
// Select the payment environment PPSE or PSE directory
byte[] data = selectPaymentEnvironment();
if (ResponseUtils.isSucceed(data)) {
// Parse FCI Template
card.getApplications().addAll(parseFCIProprietaryTemplate(data));
Collections.sort(card.getApplications());
// For each application
for (Application app : card.getApplications()) {
boolean status = false;
String applicationAid = BytesUtils.bytesToStringNoSpace(app.getAid());
for (IParser impl : parsers) {
if (impl.getId() != null && impl.getId().matcher(applicationAid).matches()) {
status = impl.parse(app);
break;
}
}
if (!ret && status) {
ret = status;
if (!config.readAllAids) {
break;
}
}
}
if (!ret) {
card.setState(CardStateEnum.LOCKED);
}
} else if (LOGGER.isDebugEnabled()) {
LOGGER.debug((config.contactLess ? "PPSE" : "PSE") + " not found -> Use kown AID");
}
return ret;
} | [
"protected",
"boolean",
"readWithPSE",
"(",
")",
"throws",
"CommunicationException",
"{",
"boolean",
"ret",
"=",
"false",
";",
"if",
"(",
"LOGGER",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Try to read card with Payment System Environment\"",
")",
";",
"}",
"// Select the payment environment PPSE or PSE directory",
"byte",
"[",
"]",
"data",
"=",
"selectPaymentEnvironment",
"(",
")",
";",
"if",
"(",
"ResponseUtils",
".",
"isSucceed",
"(",
"data",
")",
")",
"{",
"// Parse FCI Template",
"card",
".",
"getApplications",
"(",
")",
".",
"addAll",
"(",
"parseFCIProprietaryTemplate",
"(",
"data",
")",
")",
";",
"Collections",
".",
"sort",
"(",
"card",
".",
"getApplications",
"(",
")",
")",
";",
"// For each application",
"for",
"(",
"Application",
"app",
":",
"card",
".",
"getApplications",
"(",
")",
")",
"{",
"boolean",
"status",
"=",
"false",
";",
"String",
"applicationAid",
"=",
"BytesUtils",
".",
"bytesToStringNoSpace",
"(",
"app",
".",
"getAid",
"(",
")",
")",
";",
"for",
"(",
"IParser",
"impl",
":",
"parsers",
")",
"{",
"if",
"(",
"impl",
".",
"getId",
"(",
")",
"!=",
"null",
"&&",
"impl",
".",
"getId",
"(",
")",
".",
"matcher",
"(",
"applicationAid",
")",
".",
"matches",
"(",
")",
")",
"{",
"status",
"=",
"impl",
".",
"parse",
"(",
"app",
")",
";",
"break",
";",
"}",
"}",
"if",
"(",
"!",
"ret",
"&&",
"status",
")",
"{",
"ret",
"=",
"status",
";",
"if",
"(",
"!",
"config",
".",
"readAllAids",
")",
"{",
"break",
";",
"}",
"}",
"}",
"if",
"(",
"!",
"ret",
")",
"{",
"card",
".",
"setState",
"(",
"CardStateEnum",
".",
"LOCKED",
")",
";",
"}",
"}",
"else",
"if",
"(",
"LOGGER",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"(",
"config",
".",
"contactLess",
"?",
"\"PPSE\"",
":",
"\"PSE\"",
")",
"+",
"\" not found -> Use kown AID\"",
")",
";",
"}",
"return",
"ret",
";",
"}"
] | Read EMV card with Payment System Environment or Proximity Payment System
Environment
@return true is succeed false otherwise
@throws CommunicationException communication error | [
"Read",
"EMV",
"card",
"with",
"Payment",
"System",
"Environment",
"or",
"Proximity",
"Payment",
"System",
"Environment"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/EmvTemplate.java#L389-L425 |
25,622 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/EmvTemplate.java | EmvTemplate.parseFCIProprietaryTemplate | protected List<Application> parseFCIProprietaryTemplate(final byte[] pData) throws CommunicationException {
List<Application> ret = new ArrayList<Application>();
// Get SFI
byte[] data = TlvUtil.getValue(pData, EmvTags.SFI);
// Check SFI
if (data != null) {
int sfi = BytesUtils.byteArrayToInt(data);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("SFI found:" + sfi);
}
// For each records
for (int rec = 0; rec < MAX_RECORD_SFI; rec++) {
data = provider.transceive(new CommandApdu(CommandEnum.READ_RECORD, rec, sfi << 3 | 4, 0).toBytes());
// Check response
if (ResponseUtils.isSucceed(data)) {
// Get applications Tags
ret.addAll(getApplicationTemplate(data));
} else {
// No more records
break;
}
}
} else {
// Read Application template
ret.addAll(getApplicationTemplate(pData));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("(FCI) Issuer Discretionary Data is already present");
}
}
return ret;
} | java | protected List<Application> parseFCIProprietaryTemplate(final byte[] pData) throws CommunicationException {
List<Application> ret = new ArrayList<Application>();
// Get SFI
byte[] data = TlvUtil.getValue(pData, EmvTags.SFI);
// Check SFI
if (data != null) {
int sfi = BytesUtils.byteArrayToInt(data);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("SFI found:" + sfi);
}
// For each records
for (int rec = 0; rec < MAX_RECORD_SFI; rec++) {
data = provider.transceive(new CommandApdu(CommandEnum.READ_RECORD, rec, sfi << 3 | 4, 0).toBytes());
// Check response
if (ResponseUtils.isSucceed(data)) {
// Get applications Tags
ret.addAll(getApplicationTemplate(data));
} else {
// No more records
break;
}
}
} else {
// Read Application template
ret.addAll(getApplicationTemplate(pData));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("(FCI) Issuer Discretionary Data is already present");
}
}
return ret;
} | [
"protected",
"List",
"<",
"Application",
">",
"parseFCIProprietaryTemplate",
"(",
"final",
"byte",
"[",
"]",
"pData",
")",
"throws",
"CommunicationException",
"{",
"List",
"<",
"Application",
">",
"ret",
"=",
"new",
"ArrayList",
"<",
"Application",
">",
"(",
")",
";",
"// Get SFI",
"byte",
"[",
"]",
"data",
"=",
"TlvUtil",
".",
"getValue",
"(",
"pData",
",",
"EmvTags",
".",
"SFI",
")",
";",
"// Check SFI",
"if",
"(",
"data",
"!=",
"null",
")",
"{",
"int",
"sfi",
"=",
"BytesUtils",
".",
"byteArrayToInt",
"(",
"data",
")",
";",
"if",
"(",
"LOGGER",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"SFI found:\"",
"+",
"sfi",
")",
";",
"}",
"// For each records",
"for",
"(",
"int",
"rec",
"=",
"0",
";",
"rec",
"<",
"MAX_RECORD_SFI",
";",
"rec",
"++",
")",
"{",
"data",
"=",
"provider",
".",
"transceive",
"(",
"new",
"CommandApdu",
"(",
"CommandEnum",
".",
"READ_RECORD",
",",
"rec",
",",
"sfi",
"<<",
"3",
"|",
"4",
",",
"0",
")",
".",
"toBytes",
"(",
")",
")",
";",
"// Check response",
"if",
"(",
"ResponseUtils",
".",
"isSucceed",
"(",
"data",
")",
")",
"{",
"// Get applications Tags",
"ret",
".",
"addAll",
"(",
"getApplicationTemplate",
"(",
"data",
")",
")",
";",
"}",
"else",
"{",
"// No more records",
"break",
";",
"}",
"}",
"}",
"else",
"{",
"// Read Application template",
"ret",
".",
"addAll",
"(",
"getApplicationTemplate",
"(",
"pData",
")",
")",
";",
"if",
"(",
"LOGGER",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"(FCI) Issuer Discretionary Data is already present\"",
")",
";",
"}",
"}",
"return",
"ret",
";",
"}"
] | Method used to parse FCI Proprietary Template
@param pData
data to parse
@return the list of EMV application in the card
@throws CommunicationException communication error | [
"Method",
"used",
"to",
"parse",
"FCI",
"Proprietary",
"Template"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/EmvTemplate.java#L435-L466 |
25,623 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/EmvTemplate.java | EmvTemplate.readWithAID | protected void readWithAID() throws CommunicationException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Try to read card with AID");
}
// Test each card from know EMV AID
Application app = new Application();
for (EmvCardScheme type : EmvCardScheme.values()) {
for (byte[] aid : type.getAidByte()) {
app.setAid(aid);
app.setApplicationLabel(type.getName());
String applicationAid = BytesUtils.bytesToStringNoSpace(aid);
for (IParser impl : parsers) {
if (impl.getId() != null && impl.getId().matcher(applicationAid).matches() && impl.parse(app)) {
// Remove previously added Application template
card.getApplications().clear();
// Add Application
card.getApplications().add(app);
return;
}
}
}
}
} | java | protected void readWithAID() throws CommunicationException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Try to read card with AID");
}
// Test each card from know EMV AID
Application app = new Application();
for (EmvCardScheme type : EmvCardScheme.values()) {
for (byte[] aid : type.getAidByte()) {
app.setAid(aid);
app.setApplicationLabel(type.getName());
String applicationAid = BytesUtils.bytesToStringNoSpace(aid);
for (IParser impl : parsers) {
if (impl.getId() != null && impl.getId().matcher(applicationAid).matches() && impl.parse(app)) {
// Remove previously added Application template
card.getApplications().clear();
// Add Application
card.getApplications().add(app);
return;
}
}
}
}
} | [
"protected",
"void",
"readWithAID",
"(",
")",
"throws",
"CommunicationException",
"{",
"if",
"(",
"LOGGER",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Try to read card with AID\"",
")",
";",
"}",
"// Test each card from know EMV AID",
"Application",
"app",
"=",
"new",
"Application",
"(",
")",
";",
"for",
"(",
"EmvCardScheme",
"type",
":",
"EmvCardScheme",
".",
"values",
"(",
")",
")",
"{",
"for",
"(",
"byte",
"[",
"]",
"aid",
":",
"type",
".",
"getAidByte",
"(",
")",
")",
"{",
"app",
".",
"setAid",
"(",
"aid",
")",
";",
"app",
".",
"setApplicationLabel",
"(",
"type",
".",
"getName",
"(",
")",
")",
";",
"String",
"applicationAid",
"=",
"BytesUtils",
".",
"bytesToStringNoSpace",
"(",
"aid",
")",
";",
"for",
"(",
"IParser",
"impl",
":",
"parsers",
")",
"{",
"if",
"(",
"impl",
".",
"getId",
"(",
")",
"!=",
"null",
"&&",
"impl",
".",
"getId",
"(",
")",
".",
"matcher",
"(",
"applicationAid",
")",
".",
"matches",
"(",
")",
"&&",
"impl",
".",
"parse",
"(",
"app",
")",
")",
"{",
"// Remove previously added Application template",
"card",
".",
"getApplications",
"(",
")",
".",
"clear",
"(",
")",
";",
"// Add Application",
"card",
".",
"getApplications",
"(",
")",
".",
"add",
"(",
"app",
")",
";",
"return",
";",
"}",
"}",
"}",
"}",
"}"
] | Read EMV card with AID | [
"Read",
"EMV",
"card",
"with",
"AID"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/EmvTemplate.java#L506-L528 |
25,624 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/EmvTemplate.java | EmvTemplate.selectPaymentEnvironment | protected byte[] selectPaymentEnvironment() throws CommunicationException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Select " + (config.contactLess ? "PPSE" : "PSE") + " Application");
}
// Select the PPSE or PSE directory
return provider.transceive(new CommandApdu(CommandEnum.SELECT, config.contactLess ? PPSE : PSE, 0).toBytes());
} | java | protected byte[] selectPaymentEnvironment() throws CommunicationException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Select " + (config.contactLess ? "PPSE" : "PSE") + " Application");
}
// Select the PPSE or PSE directory
return provider.transceive(new CommandApdu(CommandEnum.SELECT, config.contactLess ? PPSE : PSE, 0).toBytes());
} | [
"protected",
"byte",
"[",
"]",
"selectPaymentEnvironment",
"(",
")",
"throws",
"CommunicationException",
"{",
"if",
"(",
"LOGGER",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Select \"",
"+",
"(",
"config",
".",
"contactLess",
"?",
"\"PPSE\"",
":",
"\"PSE\"",
")",
"+",
"\" Application\"",
")",
";",
"}",
"// Select the PPSE or PSE directory",
"return",
"provider",
".",
"transceive",
"(",
"new",
"CommandApdu",
"(",
"CommandEnum",
".",
"SELECT",
",",
"config",
".",
"contactLess",
"?",
"PPSE",
":",
"PSE",
",",
"0",
")",
".",
"toBytes",
"(",
")",
")",
";",
"}"
] | Method used to select payment environment PSE or PPSE
@return response byte array
@throws CommunicationException communication error | [
"Method",
"used",
"to",
"select",
"payment",
"environment",
"PSE",
"or",
"PPSE"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/EmvTemplate.java#L536-L542 |
25,625 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/impl/AbstractParser.java | AbstractParser.selectAID | protected byte[] selectAID(final byte[] pAid) throws CommunicationException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Select AID: " + BytesUtils.bytesToString(pAid));
}
return template.get().getProvider().transceive(new CommandApdu(CommandEnum.SELECT, pAid, 0).toBytes());
} | java | protected byte[] selectAID(final byte[] pAid) throws CommunicationException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Select AID: " + BytesUtils.bytesToString(pAid));
}
return template.get().getProvider().transceive(new CommandApdu(CommandEnum.SELECT, pAid, 0).toBytes());
} | [
"protected",
"byte",
"[",
"]",
"selectAID",
"(",
"final",
"byte",
"[",
"]",
"pAid",
")",
"throws",
"CommunicationException",
"{",
"if",
"(",
"LOGGER",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Select AID: \"",
"+",
"BytesUtils",
".",
"bytesToString",
"(",
"pAid",
")",
")",
";",
"}",
"return",
"template",
".",
"get",
"(",
")",
".",
"getProvider",
"(",
")",
".",
"transceive",
"(",
"new",
"CommandApdu",
"(",
"CommandEnum",
".",
"SELECT",
",",
"pAid",
",",
"0",
")",
".",
"toBytes",
"(",
")",
")",
";",
"}"
] | Select application with AID or RID
@param pAid
byte array containing AID or RID
@return response byte array
@throws CommunicationException communication error | [
"Select",
"application",
"with",
"AID",
"or",
"RID"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/impl/AbstractParser.java#L80-L85 |
25,626 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/impl/AbstractParser.java | AbstractParser.extractApplicationLabel | protected String extractApplicationLabel(final byte[] pData) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Extract Application label");
}
String label = null;
// Get Preferred name first
byte[] labelByte = TlvUtil.getValue(pData, EmvTags.APPLICATION_PREFERRED_NAME);
// Get Application label
if (labelByte == null) {
labelByte = TlvUtil.getValue(pData, EmvTags.APPLICATION_LABEL);
}
// Convert to String
if (labelByte != null) {
label = new String(labelByte);
}
return label;
} | java | protected String extractApplicationLabel(final byte[] pData) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Extract Application label");
}
String label = null;
// Get Preferred name first
byte[] labelByte = TlvUtil.getValue(pData, EmvTags.APPLICATION_PREFERRED_NAME);
// Get Application label
if (labelByte == null) {
labelByte = TlvUtil.getValue(pData, EmvTags.APPLICATION_LABEL);
}
// Convert to String
if (labelByte != null) {
label = new String(labelByte);
}
return label;
} | [
"protected",
"String",
"extractApplicationLabel",
"(",
"final",
"byte",
"[",
"]",
"pData",
")",
"{",
"if",
"(",
"LOGGER",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Extract Application label\"",
")",
";",
"}",
"String",
"label",
"=",
"null",
";",
"// Get Preferred name first",
"byte",
"[",
"]",
"labelByte",
"=",
"TlvUtil",
".",
"getValue",
"(",
"pData",
",",
"EmvTags",
".",
"APPLICATION_PREFERRED_NAME",
")",
";",
"// Get Application label",
"if",
"(",
"labelByte",
"==",
"null",
")",
"{",
"labelByte",
"=",
"TlvUtil",
".",
"getValue",
"(",
"pData",
",",
"EmvTags",
".",
"APPLICATION_LABEL",
")",
";",
"}",
"// Convert to String",
"if",
"(",
"labelByte",
"!=",
"null",
")",
"{",
"label",
"=",
"new",
"String",
"(",
"labelByte",
")",
";",
"}",
"return",
"label",
";",
"}"
] | Method used to extract application label
@param pData
raw response data
@return decoded application label or null | [
"Method",
"used",
"to",
"extract",
"application",
"label"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/impl/AbstractParser.java#L95-L111 |
25,627 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/impl/AbstractParser.java | AbstractParser.extractCardHolderName | protected void extractCardHolderName(final byte[] pData) {
// Extract Card Holder name (if exist)
byte[] cardHolderByte = TlvUtil.getValue(pData, EmvTags.CARDHOLDER_NAME);
if (cardHolderByte != null) {
String[] name = StringUtils.split(new String(cardHolderByte).trim(), TrackUtils.CARD_HOLDER_NAME_SEPARATOR);
if (name != null && name.length > 0) {
template.get().getCard().setHolderLastname(StringUtils.trimToNull(name[0]));
if (name.length == 2) {
template.get().getCard().setHolderFirstname(StringUtils.trimToNull(name[1]));
}
}
}
} | java | protected void extractCardHolderName(final byte[] pData) {
// Extract Card Holder name (if exist)
byte[] cardHolderByte = TlvUtil.getValue(pData, EmvTags.CARDHOLDER_NAME);
if (cardHolderByte != null) {
String[] name = StringUtils.split(new String(cardHolderByte).trim(), TrackUtils.CARD_HOLDER_NAME_SEPARATOR);
if (name != null && name.length > 0) {
template.get().getCard().setHolderLastname(StringUtils.trimToNull(name[0]));
if (name.length == 2) {
template.get().getCard().setHolderFirstname(StringUtils.trimToNull(name[1]));
}
}
}
} | [
"protected",
"void",
"extractCardHolderName",
"(",
"final",
"byte",
"[",
"]",
"pData",
")",
"{",
"// Extract Card Holder name (if exist)",
"byte",
"[",
"]",
"cardHolderByte",
"=",
"TlvUtil",
".",
"getValue",
"(",
"pData",
",",
"EmvTags",
".",
"CARDHOLDER_NAME",
")",
";",
"if",
"(",
"cardHolderByte",
"!=",
"null",
")",
"{",
"String",
"[",
"]",
"name",
"=",
"StringUtils",
".",
"split",
"(",
"new",
"String",
"(",
"cardHolderByte",
")",
".",
"trim",
"(",
")",
",",
"TrackUtils",
".",
"CARD_HOLDER_NAME_SEPARATOR",
")",
";",
"if",
"(",
"name",
"!=",
"null",
"&&",
"name",
".",
"length",
">",
"0",
")",
"{",
"template",
".",
"get",
"(",
")",
".",
"getCard",
"(",
")",
".",
"setHolderLastname",
"(",
"StringUtils",
".",
"trimToNull",
"(",
"name",
"[",
"0",
"]",
")",
")",
";",
"if",
"(",
"name",
".",
"length",
"==",
"2",
")",
"{",
"template",
".",
"get",
"(",
")",
".",
"getCard",
"(",
")",
".",
"setHolderFirstname",
"(",
"StringUtils",
".",
"trimToNull",
"(",
"name",
"[",
"1",
"]",
")",
")",
";",
"}",
"}",
"}",
"}"
] | Extract card holder lastname and firstname
@param pData
card data | [
"Extract",
"card",
"holder",
"lastname",
"and",
"firstname"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/impl/AbstractParser.java#L138-L150 |
25,628 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/impl/AbstractParser.java | AbstractParser.getTransactionCounter | protected int getTransactionCounter() throws CommunicationException {
int ret = UNKNOW;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Get Transaction Counter ATC");
}
byte[] data = template.get().getProvider().transceive(new CommandApdu(CommandEnum.GET_DATA, 0x9F, 0x36, 0).toBytes());
if (ResponseUtils.isSucceed(data)) {
// Extract ATC
byte[] val = TlvUtil.getValue(data, EmvTags.APP_TRANSACTION_COUNTER);
if (val != null) {
ret = BytesUtils.byteArrayToInt(val);
}
}
return ret;
} | java | protected int getTransactionCounter() throws CommunicationException {
int ret = UNKNOW;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Get Transaction Counter ATC");
}
byte[] data = template.get().getProvider().transceive(new CommandApdu(CommandEnum.GET_DATA, 0x9F, 0x36, 0).toBytes());
if (ResponseUtils.isSucceed(data)) {
// Extract ATC
byte[] val = TlvUtil.getValue(data, EmvTags.APP_TRANSACTION_COUNTER);
if (val != null) {
ret = BytesUtils.byteArrayToInt(val);
}
}
return ret;
} | [
"protected",
"int",
"getTransactionCounter",
"(",
")",
"throws",
"CommunicationException",
"{",
"int",
"ret",
"=",
"UNKNOW",
";",
"if",
"(",
"LOGGER",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Get Transaction Counter ATC\"",
")",
";",
"}",
"byte",
"[",
"]",
"data",
"=",
"template",
".",
"get",
"(",
")",
".",
"getProvider",
"(",
")",
".",
"transceive",
"(",
"new",
"CommandApdu",
"(",
"CommandEnum",
".",
"GET_DATA",
",",
"0x9F",
",",
"0x36",
",",
"0",
")",
".",
"toBytes",
"(",
")",
")",
";",
"if",
"(",
"ResponseUtils",
".",
"isSucceed",
"(",
"data",
")",
")",
"{",
"// Extract ATC",
"byte",
"[",
"]",
"val",
"=",
"TlvUtil",
".",
"getValue",
"(",
"data",
",",
"EmvTags",
".",
"APP_TRANSACTION_COUNTER",
")",
";",
"if",
"(",
"val",
"!=",
"null",
")",
"{",
"ret",
"=",
"BytesUtils",
".",
"byteArrayToInt",
"(",
"val",
")",
";",
"}",
"}",
"return",
"ret",
";",
"}"
] | Method used to get Transaction counter
@return the number of card transaction
@throws CommunicationException communication error | [
"Method",
"used",
"to",
"get",
"Transaction",
"counter"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/impl/AbstractParser.java#L169-L183 |
25,629 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/impl/AbstractParser.java | AbstractParser.getLogFormat | protected List<TagAndLength> getLogFormat() throws CommunicationException {
List<TagAndLength> ret = new ArrayList<TagAndLength>();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("GET log format");
}
// Get log format
byte[] data = template.get().getProvider().transceive(new CommandApdu(CommandEnum.GET_DATA, 0x9F, 0x4F, 0).toBytes());
if (ResponseUtils.isSucceed(data)) {
ret = TlvUtil.parseTagAndLength(TlvUtil.getValue(data, EmvTags.LOG_FORMAT));
} else {
LOGGER.warn("No Log format found");
}
return ret;
} | java | protected List<TagAndLength> getLogFormat() throws CommunicationException {
List<TagAndLength> ret = new ArrayList<TagAndLength>();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("GET log format");
}
// Get log format
byte[] data = template.get().getProvider().transceive(new CommandApdu(CommandEnum.GET_DATA, 0x9F, 0x4F, 0).toBytes());
if (ResponseUtils.isSucceed(data)) {
ret = TlvUtil.parseTagAndLength(TlvUtil.getValue(data, EmvTags.LOG_FORMAT));
} else {
LOGGER.warn("No Log format found");
}
return ret;
} | [
"protected",
"List",
"<",
"TagAndLength",
">",
"getLogFormat",
"(",
")",
"throws",
"CommunicationException",
"{",
"List",
"<",
"TagAndLength",
">",
"ret",
"=",
"new",
"ArrayList",
"<",
"TagAndLength",
">",
"(",
")",
";",
"if",
"(",
"LOGGER",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"GET log format\"",
")",
";",
"}",
"// Get log format",
"byte",
"[",
"]",
"data",
"=",
"template",
".",
"get",
"(",
")",
".",
"getProvider",
"(",
")",
".",
"transceive",
"(",
"new",
"CommandApdu",
"(",
"CommandEnum",
".",
"GET_DATA",
",",
"0x9F",
",",
"0x4F",
",",
"0",
")",
".",
"toBytes",
"(",
")",
")",
";",
"if",
"(",
"ResponseUtils",
".",
"isSucceed",
"(",
"data",
")",
")",
"{",
"ret",
"=",
"TlvUtil",
".",
"parseTagAndLength",
"(",
"TlvUtil",
".",
"getValue",
"(",
"data",
",",
"EmvTags",
".",
"LOG_FORMAT",
")",
")",
";",
"}",
"else",
"{",
"LOGGER",
".",
"warn",
"(",
"\"No Log format found\"",
")",
";",
"}",
"return",
"ret",
";",
"}"
] | Method used to get log format
@return list of tag and length for the log format
@throws CommunicationException communication error | [
"Method",
"used",
"to",
"get",
"log",
"format"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/impl/AbstractParser.java#L214-L227 |
25,630 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/impl/AbstractParser.java | AbstractParser.extractLogEntry | protected List<EmvTransactionRecord> extractLogEntry(final byte[] pLogEntry) throws CommunicationException {
List<EmvTransactionRecord> listRecord = new ArrayList<EmvTransactionRecord>();
// If log entry is defined
if (template.get().getConfig().readTransactions && pLogEntry != null) {
List<TagAndLength> tals = getLogFormat();
if (tals != null && !tals.isEmpty()) {
// read all records
for (int rec = 1; rec <= pLogEntry[1]; rec++) {
byte[] response = template.get().getProvider()
.transceive(new CommandApdu(CommandEnum.READ_RECORD, rec, pLogEntry[0] << 3 | 4, 0).toBytes());
// Extract data
if (ResponseUtils.isSucceed(response)) {
try {
EmvTransactionRecord record = new EmvTransactionRecord();
record.parse(response, tals);
if (record.getAmount() != null) {
// Fix artifact in EMV VISA card
if (record.getAmount() >= 1500000000) {
record.setAmount(record.getAmount() - 1500000000);
}
// Skip transaction with null amount
if (record.getAmount() == null || record.getAmount() <= 1) {
continue;
}
}
if (record != null) {
// Unknown currency
if (record.getCurrency() == null) {
record.setCurrency(CurrencyEnum.XXX);
}
listRecord.add(record);
}
} catch (Exception e) {
LOGGER.error("Error in transaction format: " + e.getMessage(), e);
}
} else {
// No more transaction log or transaction disabled
break;
}
}
}
}
return listRecord;
} | java | protected List<EmvTransactionRecord> extractLogEntry(final byte[] pLogEntry) throws CommunicationException {
List<EmvTransactionRecord> listRecord = new ArrayList<EmvTransactionRecord>();
// If log entry is defined
if (template.get().getConfig().readTransactions && pLogEntry != null) {
List<TagAndLength> tals = getLogFormat();
if (tals != null && !tals.isEmpty()) {
// read all records
for (int rec = 1; rec <= pLogEntry[1]; rec++) {
byte[] response = template.get().getProvider()
.transceive(new CommandApdu(CommandEnum.READ_RECORD, rec, pLogEntry[0] << 3 | 4, 0).toBytes());
// Extract data
if (ResponseUtils.isSucceed(response)) {
try {
EmvTransactionRecord record = new EmvTransactionRecord();
record.parse(response, tals);
if (record.getAmount() != null) {
// Fix artifact in EMV VISA card
if (record.getAmount() >= 1500000000) {
record.setAmount(record.getAmount() - 1500000000);
}
// Skip transaction with null amount
if (record.getAmount() == null || record.getAmount() <= 1) {
continue;
}
}
if (record != null) {
// Unknown currency
if (record.getCurrency() == null) {
record.setCurrency(CurrencyEnum.XXX);
}
listRecord.add(record);
}
} catch (Exception e) {
LOGGER.error("Error in transaction format: " + e.getMessage(), e);
}
} else {
// No more transaction log or transaction disabled
break;
}
}
}
}
return listRecord;
} | [
"protected",
"List",
"<",
"EmvTransactionRecord",
">",
"extractLogEntry",
"(",
"final",
"byte",
"[",
"]",
"pLogEntry",
")",
"throws",
"CommunicationException",
"{",
"List",
"<",
"EmvTransactionRecord",
">",
"listRecord",
"=",
"new",
"ArrayList",
"<",
"EmvTransactionRecord",
">",
"(",
")",
";",
"// If log entry is defined",
"if",
"(",
"template",
".",
"get",
"(",
")",
".",
"getConfig",
"(",
")",
".",
"readTransactions",
"&&",
"pLogEntry",
"!=",
"null",
")",
"{",
"List",
"<",
"TagAndLength",
">",
"tals",
"=",
"getLogFormat",
"(",
")",
";",
"if",
"(",
"tals",
"!=",
"null",
"&&",
"!",
"tals",
".",
"isEmpty",
"(",
")",
")",
"{",
"// read all records",
"for",
"(",
"int",
"rec",
"=",
"1",
";",
"rec",
"<=",
"pLogEntry",
"[",
"1",
"]",
";",
"rec",
"++",
")",
"{",
"byte",
"[",
"]",
"response",
"=",
"template",
".",
"get",
"(",
")",
".",
"getProvider",
"(",
")",
".",
"transceive",
"(",
"new",
"CommandApdu",
"(",
"CommandEnum",
".",
"READ_RECORD",
",",
"rec",
",",
"pLogEntry",
"[",
"0",
"]",
"<<",
"3",
"|",
"4",
",",
"0",
")",
".",
"toBytes",
"(",
")",
")",
";",
"// Extract data",
"if",
"(",
"ResponseUtils",
".",
"isSucceed",
"(",
"response",
")",
")",
"{",
"try",
"{",
"EmvTransactionRecord",
"record",
"=",
"new",
"EmvTransactionRecord",
"(",
")",
";",
"record",
".",
"parse",
"(",
"response",
",",
"tals",
")",
";",
"if",
"(",
"record",
".",
"getAmount",
"(",
")",
"!=",
"null",
")",
"{",
"// Fix artifact in EMV VISA card",
"if",
"(",
"record",
".",
"getAmount",
"(",
")",
">=",
"1500000000",
")",
"{",
"record",
".",
"setAmount",
"(",
"record",
".",
"getAmount",
"(",
")",
"-",
"1500000000",
")",
";",
"}",
"// Skip transaction with null amount",
"if",
"(",
"record",
".",
"getAmount",
"(",
")",
"==",
"null",
"||",
"record",
".",
"getAmount",
"(",
")",
"<=",
"1",
")",
"{",
"continue",
";",
"}",
"}",
"if",
"(",
"record",
"!=",
"null",
")",
"{",
"// Unknown currency",
"if",
"(",
"record",
".",
"getCurrency",
"(",
")",
"==",
"null",
")",
"{",
"record",
".",
"setCurrency",
"(",
"CurrencyEnum",
".",
"XXX",
")",
";",
"}",
"listRecord",
".",
"add",
"(",
"record",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"LOGGER",
".",
"error",
"(",
"\"Error in transaction format: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"}",
"else",
"{",
"// No more transaction log or transaction disabled",
"break",
";",
"}",
"}",
"}",
"}",
"return",
"listRecord",
";",
"}"
] | Method used to extract log entry from card
@param pLogEntry
log entry position
@return list of transaction records
@throws CommunicationException communication error | [
"Method",
"used",
"to",
"extract",
"log",
"entry",
"from",
"card"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/impl/AbstractParser.java#L237-L283 |
25,631 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/impl/DataFactory.java | DataFactory.getDate | private static Date getDate(final AnnotationData pAnnotation, final BitUtils pBit) {
Date date = null;
if (pAnnotation.getDateStandard() == BCD_DATE) {
date = pBit.getNextDate(pAnnotation.getSize(), pAnnotation.getFormat(), true);
} else if (pAnnotation.getDateStandard() == CPCL_DATE) {
date = calculateCplcDate(pBit.getNextByte(pAnnotation.getSize()));
} else {
date = pBit.getNextDate(pAnnotation.getSize(), pAnnotation.getFormat());
}
return date;
} | java | private static Date getDate(final AnnotationData pAnnotation, final BitUtils pBit) {
Date date = null;
if (pAnnotation.getDateStandard() == BCD_DATE) {
date = pBit.getNextDate(pAnnotation.getSize(), pAnnotation.getFormat(), true);
} else if (pAnnotation.getDateStandard() == CPCL_DATE) {
date = calculateCplcDate(pBit.getNextByte(pAnnotation.getSize()));
} else {
date = pBit.getNextDate(pAnnotation.getSize(), pAnnotation.getFormat());
}
return date;
} | [
"private",
"static",
"Date",
"getDate",
"(",
"final",
"AnnotationData",
"pAnnotation",
",",
"final",
"BitUtils",
"pBit",
")",
"{",
"Date",
"date",
"=",
"null",
";",
"if",
"(",
"pAnnotation",
".",
"getDateStandard",
"(",
")",
"==",
"BCD_DATE",
")",
"{",
"date",
"=",
"pBit",
".",
"getNextDate",
"(",
"pAnnotation",
".",
"getSize",
"(",
")",
",",
"pAnnotation",
".",
"getFormat",
"(",
")",
",",
"true",
")",
";",
"}",
"else",
"if",
"(",
"pAnnotation",
".",
"getDateStandard",
"(",
")",
"==",
"CPCL_DATE",
")",
"{",
"date",
"=",
"calculateCplcDate",
"(",
"pBit",
".",
"getNextByte",
"(",
"pAnnotation",
".",
"getSize",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"date",
"=",
"pBit",
".",
"getNextDate",
"(",
"pAnnotation",
".",
"getSize",
"(",
")",
",",
"pAnnotation",
".",
"getFormat",
"(",
")",
")",
";",
"}",
"return",
"date",
";",
"}"
] | Method to get a date from the bytes array
@param pAnnotation
annotation data
@param pBit
table bytes
@return The date read of null | [
"Method",
"to",
"get",
"a",
"date",
"from",
"the",
"bytes",
"array"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/impl/DataFactory.java#L66-L76 |
25,632 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/impl/DataFactory.java | DataFactory.getObject | public static Object getObject(final AnnotationData pAnnotation, final BitUtils pBit) {
Object obj = null;
Class<?> clazz = pAnnotation.getField().getType();
if (clazz.equals(Integer.class)) {
obj = getInteger(pAnnotation, pBit);
} else if (clazz.equals(Float.class)) {
obj = getFloat(pAnnotation, pBit);
} else if (clazz.equals(String.class)) {
obj = getString(pAnnotation, pBit);
} else if (clazz.equals(Date.class)) {
obj = getDate(pAnnotation, pBit);
} else if (clazz.isEnum()) {
obj = getEnum(pAnnotation, pBit);
}
return obj;
} | java | public static Object getObject(final AnnotationData pAnnotation, final BitUtils pBit) {
Object obj = null;
Class<?> clazz = pAnnotation.getField().getType();
if (clazz.equals(Integer.class)) {
obj = getInteger(pAnnotation, pBit);
} else if (clazz.equals(Float.class)) {
obj = getFloat(pAnnotation, pBit);
} else if (clazz.equals(String.class)) {
obj = getString(pAnnotation, pBit);
} else if (clazz.equals(Date.class)) {
obj = getDate(pAnnotation, pBit);
} else if (clazz.isEnum()) {
obj = getEnum(pAnnotation, pBit);
}
return obj;
} | [
"public",
"static",
"Object",
"getObject",
"(",
"final",
"AnnotationData",
"pAnnotation",
",",
"final",
"BitUtils",
"pBit",
")",
"{",
"Object",
"obj",
"=",
"null",
";",
"Class",
"<",
"?",
">",
"clazz",
"=",
"pAnnotation",
".",
"getField",
"(",
")",
".",
"getType",
"(",
")",
";",
"if",
"(",
"clazz",
".",
"equals",
"(",
"Integer",
".",
"class",
")",
")",
"{",
"obj",
"=",
"getInteger",
"(",
"pAnnotation",
",",
"pBit",
")",
";",
"}",
"else",
"if",
"(",
"clazz",
".",
"equals",
"(",
"Float",
".",
"class",
")",
")",
"{",
"obj",
"=",
"getFloat",
"(",
"pAnnotation",
",",
"pBit",
")",
";",
"}",
"else",
"if",
"(",
"clazz",
".",
"equals",
"(",
"String",
".",
"class",
")",
")",
"{",
"obj",
"=",
"getString",
"(",
"pAnnotation",
",",
"pBit",
")",
";",
"}",
"else",
"if",
"(",
"clazz",
".",
"equals",
"(",
"Date",
".",
"class",
")",
")",
"{",
"obj",
"=",
"getDate",
"(",
"pAnnotation",
",",
"pBit",
")",
";",
"}",
"else",
"if",
"(",
"clazz",
".",
"isEnum",
"(",
")",
")",
"{",
"obj",
"=",
"getEnum",
"(",
"pAnnotation",
",",
"pBit",
")",
";",
"}",
"return",
"obj",
";",
"}"
] | Method to read and object from the bytes tab
@param pAnnotation
all information data
@param pBit
bytes tab
@return an object | [
"Method",
"to",
"read",
"and",
"object",
"from",
"the",
"bytes",
"tab"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/impl/DataFactory.java#L145-L161 |
25,633 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/impl/DataFactory.java | DataFactory.getFloat | private static Float getFloat(final AnnotationData pAnnotation, final BitUtils pBit) {
Float ret = null;
if (BCD_FORMAT.equals(pAnnotation.getFormat())) {
ret = Float.parseFloat(pBit.getNextHexaString(pAnnotation.getSize()));
} else {
ret = (float) getInteger(pAnnotation, pBit);
}
return ret;
} | java | private static Float getFloat(final AnnotationData pAnnotation, final BitUtils pBit) {
Float ret = null;
if (BCD_FORMAT.equals(pAnnotation.getFormat())) {
ret = Float.parseFloat(pBit.getNextHexaString(pAnnotation.getSize()));
} else {
ret = (float) getInteger(pAnnotation, pBit);
}
return ret;
} | [
"private",
"static",
"Float",
"getFloat",
"(",
"final",
"AnnotationData",
"pAnnotation",
",",
"final",
"BitUtils",
"pBit",
")",
"{",
"Float",
"ret",
"=",
"null",
";",
"if",
"(",
"BCD_FORMAT",
".",
"equals",
"(",
"pAnnotation",
".",
"getFormat",
"(",
")",
")",
")",
"{",
"ret",
"=",
"Float",
".",
"parseFloat",
"(",
"pBit",
".",
"getNextHexaString",
"(",
"pAnnotation",
".",
"getSize",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"ret",
"=",
"(",
"float",
")",
"getInteger",
"(",
"pAnnotation",
",",
"pBit",
")",
";",
"}",
"return",
"ret",
";",
"}"
] | Method use to get float
@param pAnnotation
annotation
@param pBit
bit utils
@return | [
"Method",
"use",
"to",
"get",
"float"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/impl/DataFactory.java#L172-L182 |
25,634 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/impl/DataFactory.java | DataFactory.getEnum | @SuppressWarnings("unchecked")
private static IKeyEnum getEnum(final AnnotationData pAnnotation, final BitUtils pBit) {
int val = 0;
try {
val = Integer.parseInt(pBit.getNextHexaString(pAnnotation.getSize()), pAnnotation.isReadHexa() ? 16 : 10);
} catch (NumberFormatException nfe) {
// do nothing
}
return EnumUtils.getValue(val, (Class<? extends IKeyEnum>) pAnnotation.getField().getType());
} | java | @SuppressWarnings("unchecked")
private static IKeyEnum getEnum(final AnnotationData pAnnotation, final BitUtils pBit) {
int val = 0;
try {
val = Integer.parseInt(pBit.getNextHexaString(pAnnotation.getSize()), pAnnotation.isReadHexa() ? 16 : 10);
} catch (NumberFormatException nfe) {
// do nothing
}
return EnumUtils.getValue(val, (Class<? extends IKeyEnum>) pAnnotation.getField().getType());
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"static",
"IKeyEnum",
"getEnum",
"(",
"final",
"AnnotationData",
"pAnnotation",
",",
"final",
"BitUtils",
"pBit",
")",
"{",
"int",
"val",
"=",
"0",
";",
"try",
"{",
"val",
"=",
"Integer",
".",
"parseInt",
"(",
"pBit",
".",
"getNextHexaString",
"(",
"pAnnotation",
".",
"getSize",
"(",
")",
")",
",",
"pAnnotation",
".",
"isReadHexa",
"(",
")",
"?",
"16",
":",
"10",
")",
";",
"}",
"catch",
"(",
"NumberFormatException",
"nfe",
")",
"{",
"// do nothing",
"}",
"return",
"EnumUtils",
".",
"getValue",
"(",
"val",
",",
"(",
"Class",
"<",
"?",
"extends",
"IKeyEnum",
">",
")",
"pAnnotation",
".",
"getField",
"(",
")",
".",
"getType",
"(",
")",
")",
";",
"}"
] | This method is used to get an enum with his key
@param pAnnotation
annotation
@param pBit
bit array | [
"This",
"method",
"is",
"used",
"to",
"get",
"an",
"enum",
"with",
"his",
"key"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/impl/DataFactory.java#L192-L201 |
25,635 | devnied/EMV-NFC-Paycard-Enrollment | library/src/main/java/com/github/devnied/emvnfccard/utils/EnumUtils.java | EnumUtils.getValue | @SuppressWarnings("unchecked")
public static <T extends IKeyEnum> T getValue(final int pKey, final Class<T> pClass) {
for (IKeyEnum val : pClass.getEnumConstants()) {
if (val.getKey() == pKey) {
return (T) val;
}
}
LOGGER.error("Unknow value:" + pKey + " for Enum:" + pClass.getName());
return null;
} | java | @SuppressWarnings("unchecked")
public static <T extends IKeyEnum> T getValue(final int pKey, final Class<T> pClass) {
for (IKeyEnum val : pClass.getEnumConstants()) {
if (val.getKey() == pKey) {
return (T) val;
}
}
LOGGER.error("Unknow value:" + pKey + " for Enum:" + pClass.getName());
return null;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"T",
"extends",
"IKeyEnum",
">",
"T",
"getValue",
"(",
"final",
"int",
"pKey",
",",
"final",
"Class",
"<",
"T",
">",
"pClass",
")",
"{",
"for",
"(",
"IKeyEnum",
"val",
":",
"pClass",
".",
"getEnumConstants",
"(",
")",
")",
"{",
"if",
"(",
"val",
".",
"getKey",
"(",
")",
"==",
"pKey",
")",
"{",
"return",
"(",
"T",
")",
"val",
";",
"}",
"}",
"LOGGER",
".",
"error",
"(",
"\"Unknow value:\"",
"+",
"pKey",
"+",
"\" for Enum:\"",
"+",
"pClass",
".",
"getName",
"(",
")",
")",
";",
"return",
"null",
";",
"}"
] | Get the value of and enum from his key
@param pKey
key to find
@param pClass
Enum class
@return Enum instance of the specified key or null otherwise | [
"Get",
"the",
"value",
"of",
"and",
"enum",
"from",
"his",
"key"
] | bfbd3960708689154a7a75c8a9a934197d738a5b | https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/utils/EnumUtils.java#L44-L53 |
25,636 | SnappyDataInc/snappydata | core/src/main/java/io/snappydata/util/com/clearspring/analytics/stream/membership/Filter.java | Filter.getHashBuckets | public static int[] getHashBuckets(String key, int hashCount, int max, boolean applyWidth) {
byte[] b;
b = key.getBytes(StandardCharsets.UTF_8);
return getHashBuckets(b, hashCount, max, applyWidth);
} | java | public static int[] getHashBuckets(String key, int hashCount, int max, boolean applyWidth) {
byte[] b;
b = key.getBytes(StandardCharsets.UTF_8);
return getHashBuckets(b, hashCount, max, applyWidth);
} | [
"public",
"static",
"int",
"[",
"]",
"getHashBuckets",
"(",
"String",
"key",
",",
"int",
"hashCount",
",",
"int",
"max",
",",
"boolean",
"applyWidth",
")",
"{",
"byte",
"[",
"]",
"b",
";",
"b",
"=",
"key",
".",
"getBytes",
"(",
"StandardCharsets",
".",
"UTF_8",
")",
";",
"return",
"getHashBuckets",
"(",
"b",
",",
"hashCount",
",",
"max",
",",
"applyWidth",
")",
";",
"}"
] | than performing further iterations of murmur. | [
"than",
"performing",
"further",
"iterations",
"of",
"murmur",
"."
] | 96fe3e37e9f8d407ab68ef9e394083960acad21d | https://github.com/SnappyDataInc/snappydata/blob/96fe3e37e9f8d407ab68ef9e394083960acad21d/core/src/main/java/io/snappydata/util/com/clearspring/analytics/stream/membership/Filter.java#L91-L95 |
25,637 | SnappyDataInc/snappydata | launcher/src/main/java/io/snappydata/tools/QuickLauncher.java | QuickLauncher.status | private void status(final String[] args) throws FileNotFoundException {
setWorkingDir(args);
final Path statusFile = this.workingDir.resolve(this.statusName);
readStatus(true, statusFile);
if (args.length > 2 && args[2].equalsIgnoreCase("verbose")) {
System.out.println(this.status);
} else {
System.out.println(this.status.shortStatus());
}
} | java | private void status(final String[] args) throws FileNotFoundException {
setWorkingDir(args);
final Path statusFile = this.workingDir.resolve(this.statusName);
readStatus(true, statusFile);
if (args.length > 2 && args[2].equalsIgnoreCase("verbose")) {
System.out.println(this.status);
} else {
System.out.println(this.status.shortStatus());
}
} | [
"private",
"void",
"status",
"(",
"final",
"String",
"[",
"]",
"args",
")",
"throws",
"FileNotFoundException",
"{",
"setWorkingDir",
"(",
"args",
")",
";",
"final",
"Path",
"statusFile",
"=",
"this",
".",
"workingDir",
".",
"resolve",
"(",
"this",
".",
"statusName",
")",
";",
"readStatus",
"(",
"true",
",",
"statusFile",
")",
";",
"if",
"(",
"args",
".",
"length",
">",
"2",
"&&",
"args",
"[",
"2",
"]",
".",
"equalsIgnoreCase",
"(",
"\"verbose\"",
")",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"this",
".",
"status",
")",
";",
"}",
"else",
"{",
"System",
".",
"out",
".",
"println",
"(",
"this",
".",
"status",
".",
"shortStatus",
"(",
")",
")",
";",
"}",
"}"
] | Prints the status of the node running in the configured working directory. | [
"Prints",
"the",
"status",
"of",
"the",
"node",
"running",
"in",
"the",
"configured",
"working",
"directory",
"."
] | 96fe3e37e9f8d407ab68ef9e394083960acad21d | https://github.com/SnappyDataInc/snappydata/blob/96fe3e37e9f8d407ab68ef9e394083960acad21d/launcher/src/main/java/io/snappydata/tools/QuickLauncher.java#L301-L310 |
25,638 | SnappyDataInc/snappydata | core/src/main/java/io/snappydata/util/com/clearspring/analytics/stream/membership/BloomCalculations.java | BloomCalculations.computeBestK | public static int computeBestK(int bucketsPerElement) {
assert bucketsPerElement >= 0;
if (bucketsPerElement >= optKPerBuckets.length) {
return optKPerBuckets[optKPerBuckets.length - 1];
}
return optKPerBuckets[bucketsPerElement];
} | java | public static int computeBestK(int bucketsPerElement) {
assert bucketsPerElement >= 0;
if (bucketsPerElement >= optKPerBuckets.length) {
return optKPerBuckets[optKPerBuckets.length - 1];
}
return optKPerBuckets[bucketsPerElement];
} | [
"public",
"static",
"int",
"computeBestK",
"(",
"int",
"bucketsPerElement",
")",
"{",
"assert",
"bucketsPerElement",
">=",
"0",
";",
"if",
"(",
"bucketsPerElement",
">=",
"optKPerBuckets",
".",
"length",
")",
"{",
"return",
"optKPerBuckets",
"[",
"optKPerBuckets",
".",
"length",
"-",
"1",
"]",
";",
"}",
"return",
"optKPerBuckets",
"[",
"bucketsPerElement",
"]",
";",
"}"
] | Given the number of buckets that can be used per element, return the optimal
number of hash functions in order to minimize the false positive rate.
@param bucketsPerElement
@return The number of hash functions that minimize the false positive rate. | [
"Given",
"the",
"number",
"of",
"buckets",
"that",
"can",
"be",
"used",
"per",
"element",
"return",
"the",
"optimal",
"number",
"of",
"hash",
"functions",
"in",
"order",
"to",
"minimize",
"the",
"false",
"positive",
"rate",
"."
] | 96fe3e37e9f8d407ab68ef9e394083960acad21d | https://github.com/SnappyDataInc/snappydata/blob/96fe3e37e9f8d407ab68ef9e394083960acad21d/core/src/main/java/io/snappydata/util/com/clearspring/analytics/stream/membership/BloomCalculations.java#L79-L85 |
25,639 | apache/incubator-gobblin | gobblin-core/src/main/java/org/apache/gobblin/converter/json/JsonStringToJsonIntermediateConverter.java | JsonStringToJsonIntermediateConverter.convertRecord | @Override
public Iterable<JsonObject> convertRecord(JsonArray outputSchema, String strInputRecord, WorkUnitState workUnit)
throws DataConversionException {
JsonParser jsonParser = new JsonParser();
JsonObject inputRecord = (JsonObject) jsonParser.parse(strInputRecord);
if (!this.unpackComplexSchemas) {
return new SingleRecordIterable<>(inputRecord);
}
JsonSchema schema = new JsonSchema(outputSchema);
JsonObject rec = parse(inputRecord, schema);
return new SingleRecordIterable(rec);
} | java | @Override
public Iterable<JsonObject> convertRecord(JsonArray outputSchema, String strInputRecord, WorkUnitState workUnit)
throws DataConversionException {
JsonParser jsonParser = new JsonParser();
JsonObject inputRecord = (JsonObject) jsonParser.parse(strInputRecord);
if (!this.unpackComplexSchemas) {
return new SingleRecordIterable<>(inputRecord);
}
JsonSchema schema = new JsonSchema(outputSchema);
JsonObject rec = parse(inputRecord, schema);
return new SingleRecordIterable(rec);
} | [
"@",
"Override",
"public",
"Iterable",
"<",
"JsonObject",
">",
"convertRecord",
"(",
"JsonArray",
"outputSchema",
",",
"String",
"strInputRecord",
",",
"WorkUnitState",
"workUnit",
")",
"throws",
"DataConversionException",
"{",
"JsonParser",
"jsonParser",
"=",
"new",
"JsonParser",
"(",
")",
";",
"JsonObject",
"inputRecord",
"=",
"(",
"JsonObject",
")",
"jsonParser",
".",
"parse",
"(",
"strInputRecord",
")",
";",
"if",
"(",
"!",
"this",
".",
"unpackComplexSchemas",
")",
"{",
"return",
"new",
"SingleRecordIterable",
"<>",
"(",
"inputRecord",
")",
";",
"}",
"JsonSchema",
"schema",
"=",
"new",
"JsonSchema",
"(",
"outputSchema",
")",
";",
"JsonObject",
"rec",
"=",
"parse",
"(",
"inputRecord",
",",
"schema",
")",
";",
"return",
"new",
"SingleRecordIterable",
"(",
"rec",
")",
";",
"}"
] | Takes in a record with format String and Uses the inputSchema to convert the record to a JsonObject
@return a JsonObject representing the record
@throws IOException | [
"Takes",
"in",
"a",
"record",
"with",
"format",
"String",
"and",
"Uses",
"the",
"inputSchema",
"to",
"convert",
"the",
"record",
"to",
"a",
"JsonObject"
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/converter/json/JsonStringToJsonIntermediateConverter.java#L79-L91 |
25,640 | apache/incubator-gobblin | gobblin-core/src/main/java/org/apache/gobblin/converter/json/JsonStringToJsonIntermediateConverter.java | JsonStringToJsonIntermediateConverter.parseEnumType | private JsonElement parseEnumType(JsonSchema schema, JsonElement value)
throws DataConversionException {
if (schema.getSymbols().contains(value)) {
return value;
}
throw new DataConversionException(
"Invalid symbol: " + value.getAsString() + " allowed values: " + schema.getSymbols().toString());
} | java | private JsonElement parseEnumType(JsonSchema schema, JsonElement value)
throws DataConversionException {
if (schema.getSymbols().contains(value)) {
return value;
}
throw new DataConversionException(
"Invalid symbol: " + value.getAsString() + " allowed values: " + schema.getSymbols().toString());
} | [
"private",
"JsonElement",
"parseEnumType",
"(",
"JsonSchema",
"schema",
",",
"JsonElement",
"value",
")",
"throws",
"DataConversionException",
"{",
"if",
"(",
"schema",
".",
"getSymbols",
"(",
")",
".",
"contains",
"(",
"value",
")",
")",
"{",
"return",
"value",
";",
"}",
"throw",
"new",
"DataConversionException",
"(",
"\"Invalid symbol: \"",
"+",
"value",
".",
"getAsString",
"(",
")",
"+",
"\" allowed values: \"",
"+",
"schema",
".",
"getSymbols",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"}"
] | Parses Enum type values
@param schema
@param value
@return
@throws DataConversionException | [
"Parses",
"Enum",
"type",
"values"
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/converter/json/JsonStringToJsonIntermediateConverter.java#L167-L174 |
25,641 | apache/incubator-gobblin | gobblin-core/src/main/java/org/apache/gobblin/converter/json/JsonStringToJsonIntermediateConverter.java | JsonStringToJsonIntermediateConverter.parseJsonArrayType | private JsonElement parseJsonArrayType(JsonSchema schema, JsonElement value)
throws DataConversionException {
Type arrayType = schema.getTypeOfArrayItems();
JsonArray tempArray = new JsonArray();
if (Type.isPrimitive(arrayType)) {
return value;
}
JsonSchema nestedSchema = schema.getItemsWithinDataType();
for (JsonElement v : value.getAsJsonArray()) {
tempArray.add(parse(v, nestedSchema));
}
return tempArray;
} | java | private JsonElement parseJsonArrayType(JsonSchema schema, JsonElement value)
throws DataConversionException {
Type arrayType = schema.getTypeOfArrayItems();
JsonArray tempArray = new JsonArray();
if (Type.isPrimitive(arrayType)) {
return value;
}
JsonSchema nestedSchema = schema.getItemsWithinDataType();
for (JsonElement v : value.getAsJsonArray()) {
tempArray.add(parse(v, nestedSchema));
}
return tempArray;
} | [
"private",
"JsonElement",
"parseJsonArrayType",
"(",
"JsonSchema",
"schema",
",",
"JsonElement",
"value",
")",
"throws",
"DataConversionException",
"{",
"Type",
"arrayType",
"=",
"schema",
".",
"getTypeOfArrayItems",
"(",
")",
";",
"JsonArray",
"tempArray",
"=",
"new",
"JsonArray",
"(",
")",
";",
"if",
"(",
"Type",
".",
"isPrimitive",
"(",
"arrayType",
")",
")",
"{",
"return",
"value",
";",
"}",
"JsonSchema",
"nestedSchema",
"=",
"schema",
".",
"getItemsWithinDataType",
"(",
")",
";",
"for",
"(",
"JsonElement",
"v",
":",
"value",
".",
"getAsJsonArray",
"(",
")",
")",
"{",
"tempArray",
".",
"add",
"(",
"parse",
"(",
"v",
",",
"nestedSchema",
")",
")",
";",
"}",
"return",
"tempArray",
";",
"}"
] | Parses JsonArray type values
@param schema
@param value
@return
@throws DataConversionException | [
"Parses",
"JsonArray",
"type",
"values"
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/converter/json/JsonStringToJsonIntermediateConverter.java#L183-L195 |
25,642 | apache/incubator-gobblin | gobblin-core/src/main/java/org/apache/gobblin/converter/json/JsonStringToJsonIntermediateConverter.java | JsonStringToJsonIntermediateConverter.parseJsonObjectType | private JsonElement parseJsonObjectType(JsonSchema schema, JsonElement value)
throws DataConversionException {
JsonSchema valuesWithinDataType = schema.getValuesWithinDataType();
if (schema.isType(MAP)) {
if (Type.isPrimitive(valuesWithinDataType.getType())) {
return value;
}
JsonObject map = new JsonObject();
for (Entry<String, JsonElement> mapEntry : value.getAsJsonObject().entrySet()) {
JsonElement mapValue = mapEntry.getValue();
map.add(mapEntry.getKey(), parse(mapValue, valuesWithinDataType));
}
return map;
} else if (schema.isType(RECORD)) {
JsonSchema schemaArray = valuesWithinDataType.getValuesWithinDataType();
return parse((JsonObject) value, schemaArray);
} else {
return JsonNull.INSTANCE;
}
} | java | private JsonElement parseJsonObjectType(JsonSchema schema, JsonElement value)
throws DataConversionException {
JsonSchema valuesWithinDataType = schema.getValuesWithinDataType();
if (schema.isType(MAP)) {
if (Type.isPrimitive(valuesWithinDataType.getType())) {
return value;
}
JsonObject map = new JsonObject();
for (Entry<String, JsonElement> mapEntry : value.getAsJsonObject().entrySet()) {
JsonElement mapValue = mapEntry.getValue();
map.add(mapEntry.getKey(), parse(mapValue, valuesWithinDataType));
}
return map;
} else if (schema.isType(RECORD)) {
JsonSchema schemaArray = valuesWithinDataType.getValuesWithinDataType();
return parse((JsonObject) value, schemaArray);
} else {
return JsonNull.INSTANCE;
}
} | [
"private",
"JsonElement",
"parseJsonObjectType",
"(",
"JsonSchema",
"schema",
",",
"JsonElement",
"value",
")",
"throws",
"DataConversionException",
"{",
"JsonSchema",
"valuesWithinDataType",
"=",
"schema",
".",
"getValuesWithinDataType",
"(",
")",
";",
"if",
"(",
"schema",
".",
"isType",
"(",
"MAP",
")",
")",
"{",
"if",
"(",
"Type",
".",
"isPrimitive",
"(",
"valuesWithinDataType",
".",
"getType",
"(",
")",
")",
")",
"{",
"return",
"value",
";",
"}",
"JsonObject",
"map",
"=",
"new",
"JsonObject",
"(",
")",
";",
"for",
"(",
"Entry",
"<",
"String",
",",
"JsonElement",
">",
"mapEntry",
":",
"value",
".",
"getAsJsonObject",
"(",
")",
".",
"entrySet",
"(",
")",
")",
"{",
"JsonElement",
"mapValue",
"=",
"mapEntry",
".",
"getValue",
"(",
")",
";",
"map",
".",
"add",
"(",
"mapEntry",
".",
"getKey",
"(",
")",
",",
"parse",
"(",
"mapValue",
",",
"valuesWithinDataType",
")",
")",
";",
"}",
"return",
"map",
";",
"}",
"else",
"if",
"(",
"schema",
".",
"isType",
"(",
"RECORD",
")",
")",
"{",
"JsonSchema",
"schemaArray",
"=",
"valuesWithinDataType",
".",
"getValuesWithinDataType",
"(",
")",
";",
"return",
"parse",
"(",
"(",
"JsonObject",
")",
"value",
",",
"schemaArray",
")",
";",
"}",
"else",
"{",
"return",
"JsonNull",
".",
"INSTANCE",
";",
"}",
"}"
] | Parses JsonObject type values
@param value
@return
@throws DataConversionException | [
"Parses",
"JsonObject",
"type",
"values"
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/converter/json/JsonStringToJsonIntermediateConverter.java#L203-L223 |
25,643 | apache/incubator-gobblin | gobblin-core/src/main/java/org/apache/gobblin/converter/json/JsonStringToJsonIntermediateConverter.java | JsonStringToJsonIntermediateConverter.parsePrimitiveType | private JsonElement parsePrimitiveType(JsonSchema schema, JsonElement value)
throws DataConversionException {
if ((schema.isType(NULL) || schema.isNullable()) && value.isJsonNull()) {
return JsonNull.INSTANCE;
}
if ((schema.isType(NULL) && !value.isJsonNull()) || (!schema.isType(NULL) && value.isJsonNull())) {
throw new DataConversionException(
"Type mismatch for " + value.toString() + " of type " + schema.getDataTypes().toString());
}
if (schema.isType(FIXED)) {
int expectedSize = schema.getSizeOfFixedData();
if (value.getAsString().length() == expectedSize) {
return value;
} else {
throw new DataConversionException(
"Fixed type value is not same as defined value expected fieldsCount: " + expectedSize);
}
} else {
return value;
}
} | java | private JsonElement parsePrimitiveType(JsonSchema schema, JsonElement value)
throws DataConversionException {
if ((schema.isType(NULL) || schema.isNullable()) && value.isJsonNull()) {
return JsonNull.INSTANCE;
}
if ((schema.isType(NULL) && !value.isJsonNull()) || (!schema.isType(NULL) && value.isJsonNull())) {
throw new DataConversionException(
"Type mismatch for " + value.toString() + " of type " + schema.getDataTypes().toString());
}
if (schema.isType(FIXED)) {
int expectedSize = schema.getSizeOfFixedData();
if (value.getAsString().length() == expectedSize) {
return value;
} else {
throw new DataConversionException(
"Fixed type value is not same as defined value expected fieldsCount: " + expectedSize);
}
} else {
return value;
}
} | [
"private",
"JsonElement",
"parsePrimitiveType",
"(",
"JsonSchema",
"schema",
",",
"JsonElement",
"value",
")",
"throws",
"DataConversionException",
"{",
"if",
"(",
"(",
"schema",
".",
"isType",
"(",
"NULL",
")",
"||",
"schema",
".",
"isNullable",
"(",
")",
")",
"&&",
"value",
".",
"isJsonNull",
"(",
")",
")",
"{",
"return",
"JsonNull",
".",
"INSTANCE",
";",
"}",
"if",
"(",
"(",
"schema",
".",
"isType",
"(",
"NULL",
")",
"&&",
"!",
"value",
".",
"isJsonNull",
"(",
")",
")",
"||",
"(",
"!",
"schema",
".",
"isType",
"(",
"NULL",
")",
"&&",
"value",
".",
"isJsonNull",
"(",
")",
")",
")",
"{",
"throw",
"new",
"DataConversionException",
"(",
"\"Type mismatch for \"",
"+",
"value",
".",
"toString",
"(",
")",
"+",
"\" of type \"",
"+",
"schema",
".",
"getDataTypes",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"}",
"if",
"(",
"schema",
".",
"isType",
"(",
"FIXED",
")",
")",
"{",
"int",
"expectedSize",
"=",
"schema",
".",
"getSizeOfFixedData",
"(",
")",
";",
"if",
"(",
"value",
".",
"getAsString",
"(",
")",
".",
"length",
"(",
")",
"==",
"expectedSize",
")",
"{",
"return",
"value",
";",
"}",
"else",
"{",
"throw",
"new",
"DataConversionException",
"(",
"\"Fixed type value is not same as defined value expected fieldsCount: \"",
"+",
"expectedSize",
")",
";",
"}",
"}",
"else",
"{",
"return",
"value",
";",
"}",
"}"
] | Parses primitive types
@param schema
@param value
@return
@throws DataConversionException | [
"Parses",
"primitive",
"types"
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/converter/json/JsonStringToJsonIntermediateConverter.java#L232-L255 |
25,644 | apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/PathUtils.java | PathUtils.isAncestor | public static boolean isAncestor(Path possibleAncestor, Path fullPath) {
return !relativizePath(fullPath, possibleAncestor).equals(getPathWithoutSchemeAndAuthority(fullPath));
} | java | public static boolean isAncestor(Path possibleAncestor, Path fullPath) {
return !relativizePath(fullPath, possibleAncestor).equals(getPathWithoutSchemeAndAuthority(fullPath));
} | [
"public",
"static",
"boolean",
"isAncestor",
"(",
"Path",
"possibleAncestor",
",",
"Path",
"fullPath",
")",
"{",
"return",
"!",
"relativizePath",
"(",
"fullPath",
",",
"possibleAncestor",
")",
".",
"equals",
"(",
"getPathWithoutSchemeAndAuthority",
"(",
"fullPath",
")",
")",
";",
"}"
] | Checks whether possibleAncestor is an ancestor of fullPath.
@param possibleAncestor Possible ancestor of fullPath.
@param fullPath path to check.
@return true if possibleAncestor is an ancestor of fullPath. | [
"Checks",
"whether",
"possibleAncestor",
"is",
"an",
"ancestor",
"of",
"fullPath",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/PathUtils.java#L57-L59 |
25,645 | apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/PathUtils.java | PathUtils.getPathWithoutSchemeAndAuthority | public static Path getPathWithoutSchemeAndAuthority(Path path) {
return new Path(null, null, path.toUri().getPath());
} | java | public static Path getPathWithoutSchemeAndAuthority(Path path) {
return new Path(null, null, path.toUri().getPath());
} | [
"public",
"static",
"Path",
"getPathWithoutSchemeAndAuthority",
"(",
"Path",
"path",
")",
"{",
"return",
"new",
"Path",
"(",
"null",
",",
"null",
",",
"path",
".",
"toUri",
"(",
")",
".",
"getPath",
"(",
")",
")",
";",
"}"
] | Removes the Scheme and Authority from a Path.
@see Path
@see URI | [
"Removes",
"the",
"Scheme",
"and",
"Authority",
"from",
"a",
"Path",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/PathUtils.java#L67-L69 |
25,646 | apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/PathUtils.java | PathUtils.getRootPath | public static Path getRootPath(Path path) {
if (path.isRoot()) {
return path;
}
return getRootPath(path.getParent());
} | java | public static Path getRootPath(Path path) {
if (path.isRoot()) {
return path;
}
return getRootPath(path.getParent());
} | [
"public",
"static",
"Path",
"getRootPath",
"(",
"Path",
"path",
")",
"{",
"if",
"(",
"path",
".",
"isRoot",
"(",
")",
")",
"{",
"return",
"path",
";",
"}",
"return",
"getRootPath",
"(",
"path",
".",
"getParent",
"(",
")",
")",
";",
"}"
] | Returns the root path for the specified path.
@see Path | [
"Returns",
"the",
"root",
"path",
"for",
"the",
"specified",
"path",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/PathUtils.java#L76-L81 |
25,647 | apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/PathUtils.java | PathUtils.withoutLeadingSeparator | public static Path withoutLeadingSeparator(Path path) {
return new Path(StringUtils.removeStart(path.toString(), Path.SEPARATOR));
} | java | public static Path withoutLeadingSeparator(Path path) {
return new Path(StringUtils.removeStart(path.toString(), Path.SEPARATOR));
} | [
"public",
"static",
"Path",
"withoutLeadingSeparator",
"(",
"Path",
"path",
")",
"{",
"return",
"new",
"Path",
"(",
"StringUtils",
".",
"removeStart",
"(",
"path",
".",
"toString",
"(",
")",
",",
"Path",
".",
"SEPARATOR",
")",
")",
";",
"}"
] | Removes the leading slash if present. | [
"Removes",
"the",
"leading",
"slash",
"if",
"present",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/PathUtils.java#L87-L89 |
25,648 | apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/PathUtils.java | PathUtils.deepestNonGlobPath | public static Path deepestNonGlobPath(Path input) {
Path commonRoot = input;
while (commonRoot != null && isGlob(commonRoot)) {
commonRoot = commonRoot.getParent();
}
return commonRoot;
} | java | public static Path deepestNonGlobPath(Path input) {
Path commonRoot = input;
while (commonRoot != null && isGlob(commonRoot)) {
commonRoot = commonRoot.getParent();
}
return commonRoot;
} | [
"public",
"static",
"Path",
"deepestNonGlobPath",
"(",
"Path",
"input",
")",
"{",
"Path",
"commonRoot",
"=",
"input",
";",
"while",
"(",
"commonRoot",
"!=",
"null",
"&&",
"isGlob",
"(",
"commonRoot",
")",
")",
"{",
"commonRoot",
"=",
"commonRoot",
".",
"getParent",
"(",
")",
";",
"}",
"return",
"commonRoot",
";",
"}"
] | Finds the deepest ancestor of input that is not a glob. | [
"Finds",
"the",
"deepest",
"ancestor",
"of",
"input",
"that",
"is",
"not",
"a",
"glob",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/PathUtils.java#L94-L101 |
25,649 | apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/PathUtils.java | PathUtils.deleteEmptyParentDirectories | public static void deleteEmptyParentDirectories(FileSystem fs, Path limitPath, Path startPath)
throws IOException {
if (PathUtils.isAncestor(limitPath, startPath) && !PathUtils.getPathWithoutSchemeAndAuthority(limitPath)
.equals(PathUtils.getPathWithoutSchemeAndAuthority(startPath)) && fs.listStatus(startPath).length == 0) {
if (!fs.delete(startPath, false)) {
log.warn("Failed to delete empty directory " + startPath);
} else {
log.info("Deleted empty directory " + startPath);
}
deleteEmptyParentDirectories(fs, limitPath, startPath.getParent());
}
} | java | public static void deleteEmptyParentDirectories(FileSystem fs, Path limitPath, Path startPath)
throws IOException {
if (PathUtils.isAncestor(limitPath, startPath) && !PathUtils.getPathWithoutSchemeAndAuthority(limitPath)
.equals(PathUtils.getPathWithoutSchemeAndAuthority(startPath)) && fs.listStatus(startPath).length == 0) {
if (!fs.delete(startPath, false)) {
log.warn("Failed to delete empty directory " + startPath);
} else {
log.info("Deleted empty directory " + startPath);
}
deleteEmptyParentDirectories(fs, limitPath, startPath.getParent());
}
} | [
"public",
"static",
"void",
"deleteEmptyParentDirectories",
"(",
"FileSystem",
"fs",
",",
"Path",
"limitPath",
",",
"Path",
"startPath",
")",
"throws",
"IOException",
"{",
"if",
"(",
"PathUtils",
".",
"isAncestor",
"(",
"limitPath",
",",
"startPath",
")",
"&&",
"!",
"PathUtils",
".",
"getPathWithoutSchemeAndAuthority",
"(",
"limitPath",
")",
".",
"equals",
"(",
"PathUtils",
".",
"getPathWithoutSchemeAndAuthority",
"(",
"startPath",
")",
")",
"&&",
"fs",
".",
"listStatus",
"(",
"startPath",
")",
".",
"length",
"==",
"0",
")",
"{",
"if",
"(",
"!",
"fs",
".",
"delete",
"(",
"startPath",
",",
"false",
")",
")",
"{",
"log",
".",
"warn",
"(",
"\"Failed to delete empty directory \"",
"+",
"startPath",
")",
";",
"}",
"else",
"{",
"log",
".",
"info",
"(",
"\"Deleted empty directory \"",
"+",
"startPath",
")",
";",
"}",
"deleteEmptyParentDirectories",
"(",
"fs",
",",
"limitPath",
",",
"startPath",
".",
"getParent",
"(",
")",
")",
";",
"}",
"}"
] | Deletes empty directories starting with startPath and all ancestors up to but not including limitPath.
@param fs {@link FileSystem} where paths are located.
@param limitPath only {@link Path}s that are strict descendants of this path will be deleted.
@param startPath first {@link Path} to delete. Afterwards empty ancestors will be deleted.
@throws IOException | [
"Deletes",
"empty",
"directories",
"starting",
"with",
"startPath",
"and",
"all",
"ancestors",
"up",
"to",
"but",
"not",
"including",
"limitPath",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/PathUtils.java#L189-L200 |
25,650 | apache/incubator-gobblin | gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/recovery/RecoveryHelper.java | RecoveryHelper.getPersistDir | public static Optional<Path> getPersistDir(State state) throws IOException {
if (state.contains(PERSIST_DIR_KEY)) {
return Optional
.of(new Path(state.getProp(PERSIST_DIR_KEY), UserGroupInformation.getCurrentUser().getShortUserName()));
}
return Optional.absent();
} | java | public static Optional<Path> getPersistDir(State state) throws IOException {
if (state.contains(PERSIST_DIR_KEY)) {
return Optional
.of(new Path(state.getProp(PERSIST_DIR_KEY), UserGroupInformation.getCurrentUser().getShortUserName()));
}
return Optional.absent();
} | [
"public",
"static",
"Optional",
"<",
"Path",
">",
"getPersistDir",
"(",
"State",
"state",
")",
"throws",
"IOException",
"{",
"if",
"(",
"state",
".",
"contains",
"(",
"PERSIST_DIR_KEY",
")",
")",
"{",
"return",
"Optional",
".",
"of",
"(",
"new",
"Path",
"(",
"state",
".",
"getProp",
"(",
"PERSIST_DIR_KEY",
")",
",",
"UserGroupInformation",
".",
"getCurrentUser",
"(",
")",
".",
"getShortUserName",
"(",
")",
")",
")",
";",
"}",
"return",
"Optional",
".",
"absent",
"(",
")",
";",
"}"
] | Get the persist directory for this job.
@param state {@link State} containing job information.
@return A {@link Path} used as persist directory for this job. Note this path is user-specific for security reasons.
@throws java.io.IOException | [
"Get",
"the",
"persist",
"directory",
"for",
"this",
"job",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/recovery/RecoveryHelper.java#L69-L75 |
25,651 | apache/incubator-gobblin | gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/recovery/RecoveryHelper.java | RecoveryHelper.persistFile | public boolean persistFile(State state, CopyableFile file, Path path) throws IOException {
if (!this.persistDir.isPresent()) {
return false;
}
String guid = computeGuid(state, file);
Path guidPath = new Path(this.persistDir.get(), guid);
if (!this.fs.exists(guidPath)) {
this.fs.mkdirs(guidPath, new FsPermission(FsAction.ALL, FsAction.READ, FsAction.NONE));
}
Path targetPath = new Path(guidPath, shortenPathName(file.getOrigin().getPath(), 250 - guid.length()));
log.info(String.format("Persisting file %s with guid %s to location %s.", path, guid, targetPath));
if (this.fs.rename(path, targetPath)) {
this.fs.setTimes(targetPath, System.currentTimeMillis(), -1);
return true;
}
return false;
} | java | public boolean persistFile(State state, CopyableFile file, Path path) throws IOException {
if (!this.persistDir.isPresent()) {
return false;
}
String guid = computeGuid(state, file);
Path guidPath = new Path(this.persistDir.get(), guid);
if (!this.fs.exists(guidPath)) {
this.fs.mkdirs(guidPath, new FsPermission(FsAction.ALL, FsAction.READ, FsAction.NONE));
}
Path targetPath = new Path(guidPath, shortenPathName(file.getOrigin().getPath(), 250 - guid.length()));
log.info(String.format("Persisting file %s with guid %s to location %s.", path, guid, targetPath));
if (this.fs.rename(path, targetPath)) {
this.fs.setTimes(targetPath, System.currentTimeMillis(), -1);
return true;
}
return false;
} | [
"public",
"boolean",
"persistFile",
"(",
"State",
"state",
",",
"CopyableFile",
"file",
",",
"Path",
"path",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"this",
".",
"persistDir",
".",
"isPresent",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"String",
"guid",
"=",
"computeGuid",
"(",
"state",
",",
"file",
")",
";",
"Path",
"guidPath",
"=",
"new",
"Path",
"(",
"this",
".",
"persistDir",
".",
"get",
"(",
")",
",",
"guid",
")",
";",
"if",
"(",
"!",
"this",
".",
"fs",
".",
"exists",
"(",
"guidPath",
")",
")",
"{",
"this",
".",
"fs",
".",
"mkdirs",
"(",
"guidPath",
",",
"new",
"FsPermission",
"(",
"FsAction",
".",
"ALL",
",",
"FsAction",
".",
"READ",
",",
"FsAction",
".",
"NONE",
")",
")",
";",
"}",
"Path",
"targetPath",
"=",
"new",
"Path",
"(",
"guidPath",
",",
"shortenPathName",
"(",
"file",
".",
"getOrigin",
"(",
")",
".",
"getPath",
"(",
")",
",",
"250",
"-",
"guid",
".",
"length",
"(",
")",
")",
")",
";",
"log",
".",
"info",
"(",
"String",
".",
"format",
"(",
"\"Persisting file %s with guid %s to location %s.\"",
",",
"path",
",",
"guid",
",",
"targetPath",
")",
")",
";",
"if",
"(",
"this",
".",
"fs",
".",
"rename",
"(",
"path",
",",
"targetPath",
")",
")",
"{",
"this",
".",
"fs",
".",
"setTimes",
"(",
"targetPath",
",",
"System",
".",
"currentTimeMillis",
"(",
")",
",",
"-",
"1",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Moves a copied path into a persistent location managed by gobblin-distcp. This method is used when an already
copied file cannot be successfully published. In future runs, instead of re-copying the file, distcp will use the
persisted file.
@param state {@link State} containing job information.
@param file {@link org.apache.gobblin.data.management.copy.CopyEntity} from which input {@link Path} originated.
@param path {@link Path} to persist.
@return true if persist was successful.
@throws IOException | [
"Moves",
"a",
"copied",
"path",
"into",
"a",
"persistent",
"location",
"managed",
"by",
"gobblin",
"-",
"distcp",
".",
"This",
"method",
"is",
"used",
"when",
"an",
"already",
"copied",
"file",
"cannot",
"be",
"successfully",
"published",
".",
"In",
"future",
"runs",
"instead",
"of",
"re",
"-",
"copying",
"the",
"file",
"distcp",
"will",
"use",
"the",
"persisted",
"file",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/recovery/RecoveryHelper.java#L88-L108 |
25,652 | apache/incubator-gobblin | gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/recovery/RecoveryHelper.java | RecoveryHelper.shortenPathName | static String shortenPathName(Path path, int bytes) {
String pathString = path.toUri().getPath();
String replaced = pathString.replace("/", "_");
if (replaced.length() <= bytes) {
return replaced;
}
int bytesPerHalf = (bytes - 3) / 2;
return replaced.substring(0, bytesPerHalf) + "..." + replaced.substring(replaced.length() - bytesPerHalf);
} | java | static String shortenPathName(Path path, int bytes) {
String pathString = path.toUri().getPath();
String replaced = pathString.replace("/", "_");
if (replaced.length() <= bytes) {
return replaced;
}
int bytesPerHalf = (bytes - 3) / 2;
return replaced.substring(0, bytesPerHalf) + "..." + replaced.substring(replaced.length() - bytesPerHalf);
} | [
"static",
"String",
"shortenPathName",
"(",
"Path",
"path",
",",
"int",
"bytes",
")",
"{",
"String",
"pathString",
"=",
"path",
".",
"toUri",
"(",
")",
".",
"getPath",
"(",
")",
";",
"String",
"replaced",
"=",
"pathString",
".",
"replace",
"(",
"\"/\"",
",",
"\"_\"",
")",
";",
"if",
"(",
"replaced",
".",
"length",
"(",
")",
"<=",
"bytes",
")",
"{",
"return",
"replaced",
";",
"}",
"int",
"bytesPerHalf",
"=",
"(",
"bytes",
"-",
"3",
")",
"/",
"2",
";",
"return",
"replaced",
".",
"substring",
"(",
"0",
",",
"bytesPerHalf",
")",
"+",
"\"...\"",
"+",
"replaced",
".",
"substring",
"(",
"replaced",
".",
"length",
"(",
")",
"-",
"bytesPerHalf",
")",
";",
"}"
] | Shorten an absolute path into a sanitized String of length at most bytes. This is useful for including a summary
of an absolute path in a file name.
<p>
For example: shortenPathName("/user/gobblin/foo/bar/myFile.txt", 25) will be shortened to "_user_gobbl..._myFile.txt".
</p>
@param path absolute {@link Path} to shorten.
@param bytes max number of UTF8 bytes that output string can use (note that,
for now, it is assumed that each character uses exactly one byte).
@return a shortened, sanitized String of length at most bytes. | [
"Shorten",
"an",
"absolute",
"path",
"into",
"a",
"sanitized",
"String",
"of",
"length",
"at",
"most",
"bytes",
".",
"This",
"is",
"useful",
"for",
"including",
"a",
"summary",
"of",
"an",
"absolute",
"path",
"in",
"a",
"file",
"name",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/recovery/RecoveryHelper.java#L175-L185 |
25,653 | apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/ProxiedFileSystemWrapper.java | ProxiedFileSystemWrapper.getProxiedFileSystem | public FileSystem getProxiedFileSystem(State properties, AuthType authType, String authPath, String uri, final Configuration conf)
throws IOException, InterruptedException, URISyntaxException {
Preconditions.checkArgument(StringUtils.isNotBlank(properties.getProp(ConfigurationKeys.FS_PROXY_AS_USER_NAME)),
"State does not contain a proper proxy user name");
String proxyUserName = properties.getProp(ConfigurationKeys.FS_PROXY_AS_USER_NAME);
UserGroupInformation proxyUser;
switch (authType) {
case KEYTAB: // If the authentication type is KEYTAB, log in a super user first before creating a proxy user.
Preconditions.checkArgument(
StringUtils.isNotBlank(properties.getProp(ConfigurationKeys.SUPER_USER_NAME_TO_PROXY_AS_OTHERS)),
"State does not contain a proper proxy token file name");
String superUser = properties.getProp(ConfigurationKeys.SUPER_USER_NAME_TO_PROXY_AS_OTHERS);
UserGroupInformation.loginUserFromKeytab(superUser, authPath);
proxyUser = UserGroupInformation.createProxyUser(proxyUserName, UserGroupInformation.getLoginUser());
break;
case TOKEN: // If the authentication type is TOKEN, create a proxy user and then add the token to the user.
proxyUser = UserGroupInformation.createProxyUser(proxyUserName, UserGroupInformation.getLoginUser());
Optional<Token<?>> proxyToken = getTokenFromSeqFile(authPath, proxyUserName);
if (proxyToken.isPresent()) {
proxyUser.addToken(proxyToken.get());
} else {
LOG.warn("No delegation token found for the current proxy user.");
}
break;
default:
LOG.warn("Creating a proxy user without authentication, which could not perform File system operations.");
proxyUser = UserGroupInformation.createProxyUser(proxyUserName, UserGroupInformation.getLoginUser());
break;
}
final URI fsURI = URI.create(uri);
proxyUser.doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws IOException {
LOG.debug("Now performing file system operations as :" + UserGroupInformation.getCurrentUser());
proxiedFs = FileSystem.get(fsURI, conf);
return null;
}
});
return this.proxiedFs;
} | java | public FileSystem getProxiedFileSystem(State properties, AuthType authType, String authPath, String uri, final Configuration conf)
throws IOException, InterruptedException, URISyntaxException {
Preconditions.checkArgument(StringUtils.isNotBlank(properties.getProp(ConfigurationKeys.FS_PROXY_AS_USER_NAME)),
"State does not contain a proper proxy user name");
String proxyUserName = properties.getProp(ConfigurationKeys.FS_PROXY_AS_USER_NAME);
UserGroupInformation proxyUser;
switch (authType) {
case KEYTAB: // If the authentication type is KEYTAB, log in a super user first before creating a proxy user.
Preconditions.checkArgument(
StringUtils.isNotBlank(properties.getProp(ConfigurationKeys.SUPER_USER_NAME_TO_PROXY_AS_OTHERS)),
"State does not contain a proper proxy token file name");
String superUser = properties.getProp(ConfigurationKeys.SUPER_USER_NAME_TO_PROXY_AS_OTHERS);
UserGroupInformation.loginUserFromKeytab(superUser, authPath);
proxyUser = UserGroupInformation.createProxyUser(proxyUserName, UserGroupInformation.getLoginUser());
break;
case TOKEN: // If the authentication type is TOKEN, create a proxy user and then add the token to the user.
proxyUser = UserGroupInformation.createProxyUser(proxyUserName, UserGroupInformation.getLoginUser());
Optional<Token<?>> proxyToken = getTokenFromSeqFile(authPath, proxyUserName);
if (proxyToken.isPresent()) {
proxyUser.addToken(proxyToken.get());
} else {
LOG.warn("No delegation token found for the current proxy user.");
}
break;
default:
LOG.warn("Creating a proxy user without authentication, which could not perform File system operations.");
proxyUser = UserGroupInformation.createProxyUser(proxyUserName, UserGroupInformation.getLoginUser());
break;
}
final URI fsURI = URI.create(uri);
proxyUser.doAs(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws IOException {
LOG.debug("Now performing file system operations as :" + UserGroupInformation.getCurrentUser());
proxiedFs = FileSystem.get(fsURI, conf);
return null;
}
});
return this.proxiedFs;
} | [
"public",
"FileSystem",
"getProxiedFileSystem",
"(",
"State",
"properties",
",",
"AuthType",
"authType",
",",
"String",
"authPath",
",",
"String",
"uri",
",",
"final",
"Configuration",
"conf",
")",
"throws",
"IOException",
",",
"InterruptedException",
",",
"URISyntaxException",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"properties",
".",
"getProp",
"(",
"ConfigurationKeys",
".",
"FS_PROXY_AS_USER_NAME",
")",
")",
",",
"\"State does not contain a proper proxy user name\"",
")",
";",
"String",
"proxyUserName",
"=",
"properties",
".",
"getProp",
"(",
"ConfigurationKeys",
".",
"FS_PROXY_AS_USER_NAME",
")",
";",
"UserGroupInformation",
"proxyUser",
";",
"switch",
"(",
"authType",
")",
"{",
"case",
"KEYTAB",
":",
"// If the authentication type is KEYTAB, log in a super user first before creating a proxy user.",
"Preconditions",
".",
"checkArgument",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"properties",
".",
"getProp",
"(",
"ConfigurationKeys",
".",
"SUPER_USER_NAME_TO_PROXY_AS_OTHERS",
")",
")",
",",
"\"State does not contain a proper proxy token file name\"",
")",
";",
"String",
"superUser",
"=",
"properties",
".",
"getProp",
"(",
"ConfigurationKeys",
".",
"SUPER_USER_NAME_TO_PROXY_AS_OTHERS",
")",
";",
"UserGroupInformation",
".",
"loginUserFromKeytab",
"(",
"superUser",
",",
"authPath",
")",
";",
"proxyUser",
"=",
"UserGroupInformation",
".",
"createProxyUser",
"(",
"proxyUserName",
",",
"UserGroupInformation",
".",
"getLoginUser",
"(",
")",
")",
";",
"break",
";",
"case",
"TOKEN",
":",
"// If the authentication type is TOKEN, create a proxy user and then add the token to the user.",
"proxyUser",
"=",
"UserGroupInformation",
".",
"createProxyUser",
"(",
"proxyUserName",
",",
"UserGroupInformation",
".",
"getLoginUser",
"(",
")",
")",
";",
"Optional",
"<",
"Token",
"<",
"?",
">",
">",
"proxyToken",
"=",
"getTokenFromSeqFile",
"(",
"authPath",
",",
"proxyUserName",
")",
";",
"if",
"(",
"proxyToken",
".",
"isPresent",
"(",
")",
")",
"{",
"proxyUser",
".",
"addToken",
"(",
"proxyToken",
".",
"get",
"(",
")",
")",
";",
"}",
"else",
"{",
"LOG",
".",
"warn",
"(",
"\"No delegation token found for the current proxy user.\"",
")",
";",
"}",
"break",
";",
"default",
":",
"LOG",
".",
"warn",
"(",
"\"Creating a proxy user without authentication, which could not perform File system operations.\"",
")",
";",
"proxyUser",
"=",
"UserGroupInformation",
".",
"createProxyUser",
"(",
"proxyUserName",
",",
"UserGroupInformation",
".",
"getLoginUser",
"(",
")",
")",
";",
"break",
";",
"}",
"final",
"URI",
"fsURI",
"=",
"URI",
".",
"create",
"(",
"uri",
")",
";",
"proxyUser",
".",
"doAs",
"(",
"new",
"PrivilegedExceptionAction",
"<",
"Void",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"Void",
"run",
"(",
")",
"throws",
"IOException",
"{",
"LOG",
".",
"debug",
"(",
"\"Now performing file system operations as :\"",
"+",
"UserGroupInformation",
".",
"getCurrentUser",
"(",
")",
")",
";",
"proxiedFs",
"=",
"FileSystem",
".",
"get",
"(",
"fsURI",
",",
"conf",
")",
";",
"return",
"null",
";",
"}",
"}",
")",
";",
"return",
"this",
".",
"proxiedFs",
";",
"}"
] | Getter for proxiedFs, using the passed parameters to create an instance of a proxiedFs.
@param properties
@param authType is either TOKEN or KEYTAB.
@param authPath is the KEYTAB location if the authType is KEYTAB; otherwise, it is the token file.
@param uri File system URI.
@throws IOException
@throws InterruptedException
@throws URISyntaxException
@return proxiedFs | [
"Getter",
"for",
"proxiedFs",
"using",
"the",
"passed",
"parameters",
"to",
"create",
"an",
"instance",
"of",
"a",
"proxiedFs",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/ProxiedFileSystemWrapper.java#L101-L141 |
25,654 | apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/ProxiedFileSystemWrapper.java | ProxiedFileSystemWrapper.getTokenFromSeqFile | private static Optional<Token<?>> getTokenFromSeqFile(String authPath, String proxyUserName) throws IOException {
try (Closer closer = Closer.create()) {
FileSystem localFs = FileSystem.getLocal(new Configuration());
SequenceFile.Reader tokenReader =
closer.register(new SequenceFile.Reader(localFs, new Path(authPath), localFs.getConf()));
Text key = new Text();
Token<?> value = new Token<>();
while (tokenReader.next(key, value)) {
LOG.info("Found token for " + key);
if (key.toString().equals(proxyUserName)) {
return Optional.<Token<?>> of(value);
}
}
}
return Optional.absent();
} | java | private static Optional<Token<?>> getTokenFromSeqFile(String authPath, String proxyUserName) throws IOException {
try (Closer closer = Closer.create()) {
FileSystem localFs = FileSystem.getLocal(new Configuration());
SequenceFile.Reader tokenReader =
closer.register(new SequenceFile.Reader(localFs, new Path(authPath), localFs.getConf()));
Text key = new Text();
Token<?> value = new Token<>();
while (tokenReader.next(key, value)) {
LOG.info("Found token for " + key);
if (key.toString().equals(proxyUserName)) {
return Optional.<Token<?>> of(value);
}
}
}
return Optional.absent();
} | [
"private",
"static",
"Optional",
"<",
"Token",
"<",
"?",
">",
">",
"getTokenFromSeqFile",
"(",
"String",
"authPath",
",",
"String",
"proxyUserName",
")",
"throws",
"IOException",
"{",
"try",
"(",
"Closer",
"closer",
"=",
"Closer",
".",
"create",
"(",
")",
")",
"{",
"FileSystem",
"localFs",
"=",
"FileSystem",
".",
"getLocal",
"(",
"new",
"Configuration",
"(",
")",
")",
";",
"SequenceFile",
".",
"Reader",
"tokenReader",
"=",
"closer",
".",
"register",
"(",
"new",
"SequenceFile",
".",
"Reader",
"(",
"localFs",
",",
"new",
"Path",
"(",
"authPath",
")",
",",
"localFs",
".",
"getConf",
"(",
")",
")",
")",
";",
"Text",
"key",
"=",
"new",
"Text",
"(",
")",
";",
"Token",
"<",
"?",
">",
"value",
"=",
"new",
"Token",
"<>",
"(",
")",
";",
"while",
"(",
"tokenReader",
".",
"next",
"(",
"key",
",",
"value",
")",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Found token for \"",
"+",
"key",
")",
";",
"if",
"(",
"key",
".",
"toString",
"(",
")",
".",
"equals",
"(",
"proxyUserName",
")",
")",
"{",
"return",
"Optional",
".",
"<",
"Token",
"<",
"?",
">",
">",
"of",
"(",
"value",
")",
";",
"}",
"}",
"}",
"return",
"Optional",
".",
"absent",
"(",
")",
";",
"}"
] | Get token from the token sequence file.
@param authPath
@param proxyUserName
@return Token for proxyUserName if it exists.
@throws IOException | [
"Get",
"token",
"from",
"the",
"token",
"sequence",
"file",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/ProxiedFileSystemWrapper.java#L150-L165 |
25,655 | apache/incubator-gobblin | gobblin-core/src/main/java/org/apache/gobblin/source/PartitionAwareFileRetrieverUtils.java | PartitionAwareFileRetrieverUtils.getLeadTimeDurationFromConfig | public static Duration getLeadTimeDurationFromConfig(State state) {
String leadTimeProp = state.getProp(DATE_PARTITIONED_SOURCE_PARTITION_LEAD_TIME);
if (leadTimeProp == null || leadTimeProp.length() == 0) {
return DEFAULT_PARTITIONED_SOURCE_PARTITION_LEAD_TIME;
}
int leadTime = Integer.parseInt(leadTimeProp);
DatePartitionType leadTimeGranularity = DEFAULT_DATE_PARTITIONED_SOURCE_PARTITION_LEAD_TIME_GRANULARITY;
String leadTimeGranularityProp = state.getProp(DATE_PARTITIONED_SOURCE_PARTITION_LEAD_TIME_GRANULARITY);
if (leadTimeGranularityProp != null) {
leadTimeGranularity = DatePartitionType.valueOf(leadTimeGranularityProp);
}
return new Duration(leadTime * leadTimeGranularity.getUnitMilliseconds());
} | java | public static Duration getLeadTimeDurationFromConfig(State state) {
String leadTimeProp = state.getProp(DATE_PARTITIONED_SOURCE_PARTITION_LEAD_TIME);
if (leadTimeProp == null || leadTimeProp.length() == 0) {
return DEFAULT_PARTITIONED_SOURCE_PARTITION_LEAD_TIME;
}
int leadTime = Integer.parseInt(leadTimeProp);
DatePartitionType leadTimeGranularity = DEFAULT_DATE_PARTITIONED_SOURCE_PARTITION_LEAD_TIME_GRANULARITY;
String leadTimeGranularityProp = state.getProp(DATE_PARTITIONED_SOURCE_PARTITION_LEAD_TIME_GRANULARITY);
if (leadTimeGranularityProp != null) {
leadTimeGranularity = DatePartitionType.valueOf(leadTimeGranularityProp);
}
return new Duration(leadTime * leadTimeGranularity.getUnitMilliseconds());
} | [
"public",
"static",
"Duration",
"getLeadTimeDurationFromConfig",
"(",
"State",
"state",
")",
"{",
"String",
"leadTimeProp",
"=",
"state",
".",
"getProp",
"(",
"DATE_PARTITIONED_SOURCE_PARTITION_LEAD_TIME",
")",
";",
"if",
"(",
"leadTimeProp",
"==",
"null",
"||",
"leadTimeProp",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
"DEFAULT_PARTITIONED_SOURCE_PARTITION_LEAD_TIME",
";",
"}",
"int",
"leadTime",
"=",
"Integer",
".",
"parseInt",
"(",
"leadTimeProp",
")",
";",
"DatePartitionType",
"leadTimeGranularity",
"=",
"DEFAULT_DATE_PARTITIONED_SOURCE_PARTITION_LEAD_TIME_GRANULARITY",
";",
"String",
"leadTimeGranularityProp",
"=",
"state",
".",
"getProp",
"(",
"DATE_PARTITIONED_SOURCE_PARTITION_LEAD_TIME_GRANULARITY",
")",
";",
"if",
"(",
"leadTimeGranularityProp",
"!=",
"null",
")",
"{",
"leadTimeGranularity",
"=",
"DatePartitionType",
".",
"valueOf",
"(",
"leadTimeGranularityProp",
")",
";",
"}",
"return",
"new",
"Duration",
"(",
"leadTime",
"*",
"leadTimeGranularity",
".",
"getUnitMilliseconds",
"(",
")",
")",
";",
"}"
] | Retrieve the lead time duration from the LEAD_TIME and LEAD_TIME granularity config settings. | [
"Retrieve",
"the",
"lead",
"time",
"duration",
"from",
"the",
"LEAD_TIME",
"and",
"LEAD_TIME",
"granularity",
"config",
"settings",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/source/PartitionAwareFileRetrieverUtils.java#L38-L54 |
25,656 | apache/incubator-gobblin | gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/purger/PurgeableHivePartitionDataset.java | PurgeableHivePartitionDataset.purge | public void purge()
throws IOException {
this.datasetOwner = getOwner();
State state = new State(this.state);
this.datasetOwnerFs = ProxyUtils.getOwnerFs(state, this.datasetOwner);
try (HiveProxyQueryExecutor queryExecutor = ProxyUtils.getQueryExecutor(state, this.datasetOwner)) {
if (this.simulate) {
log.info("Simulate is set to true. Wont't run actual queries");
return;
}
String originalPartitionLocation = getOriginalPartitionLocation();
// Create the staging table and staging partition
queryExecutor.executeQueries(HivePurgerQueryTemplate.getCreateStagingTableQuery(this), this.datasetOwner);
this.startTime = getLastModifiedTime(originalPartitionLocation);
// Execute purge queries, that is insert filtered data into the staging partition
queryExecutor.executeQueries(this.purgeQueries, this.datasetOwner);
this.endTime = getLastModifiedTime(originalPartitionLocation);
// Create a backup table and partition pointing to the original partition location
queryExecutor.executeQueries(HivePurgerQueryTemplate.getBackupQueries(this), this.datasetOwner);
String commitPolicyString = this.state.getProp(ComplianceConfigurationKeys.PURGER_COMMIT_POLICY_CLASS,
ComplianceConfigurationKeys.DEFAULT_PURGER_COMMIT_POLICY_CLASS);
CommitPolicy<PurgeableHivePartitionDataset> commitPolicy =
GobblinConstructorUtils.invokeConstructor(CommitPolicy.class, commitPolicyString);
if (!commitPolicy.shouldCommit(this)) {
log.error("Last modified time before start of execution : " + this.startTime);
log.error("Last modified time after execution of purge queries : " + this.endTime);
throw new RuntimeException("Failed to commit. File modified during job run.");
}
// Alter the original table partition to start pointing to the cleaned-partition-location/staging-partition-location
queryExecutor
.executeQueries(HivePurgerQueryTemplate.getAlterOriginalPartitionLocationQueries(this), this.datasetOwner);
// Drop the staging table
queryExecutor.executeQueries(HivePurgerQueryTemplate.getDropStagingTableQuery(this), this.datasetOwner);
} catch (SQLException e) {
throw new IOException(e);
}
} | java | public void purge()
throws IOException {
this.datasetOwner = getOwner();
State state = new State(this.state);
this.datasetOwnerFs = ProxyUtils.getOwnerFs(state, this.datasetOwner);
try (HiveProxyQueryExecutor queryExecutor = ProxyUtils.getQueryExecutor(state, this.datasetOwner)) {
if (this.simulate) {
log.info("Simulate is set to true. Wont't run actual queries");
return;
}
String originalPartitionLocation = getOriginalPartitionLocation();
// Create the staging table and staging partition
queryExecutor.executeQueries(HivePurgerQueryTemplate.getCreateStagingTableQuery(this), this.datasetOwner);
this.startTime = getLastModifiedTime(originalPartitionLocation);
// Execute purge queries, that is insert filtered data into the staging partition
queryExecutor.executeQueries(this.purgeQueries, this.datasetOwner);
this.endTime = getLastModifiedTime(originalPartitionLocation);
// Create a backup table and partition pointing to the original partition location
queryExecutor.executeQueries(HivePurgerQueryTemplate.getBackupQueries(this), this.datasetOwner);
String commitPolicyString = this.state.getProp(ComplianceConfigurationKeys.PURGER_COMMIT_POLICY_CLASS,
ComplianceConfigurationKeys.DEFAULT_PURGER_COMMIT_POLICY_CLASS);
CommitPolicy<PurgeableHivePartitionDataset> commitPolicy =
GobblinConstructorUtils.invokeConstructor(CommitPolicy.class, commitPolicyString);
if (!commitPolicy.shouldCommit(this)) {
log.error("Last modified time before start of execution : " + this.startTime);
log.error("Last modified time after execution of purge queries : " + this.endTime);
throw new RuntimeException("Failed to commit. File modified during job run.");
}
// Alter the original table partition to start pointing to the cleaned-partition-location/staging-partition-location
queryExecutor
.executeQueries(HivePurgerQueryTemplate.getAlterOriginalPartitionLocationQueries(this), this.datasetOwner);
// Drop the staging table
queryExecutor.executeQueries(HivePurgerQueryTemplate.getDropStagingTableQuery(this), this.datasetOwner);
} catch (SQLException e) {
throw new IOException(e);
}
} | [
"public",
"void",
"purge",
"(",
")",
"throws",
"IOException",
"{",
"this",
".",
"datasetOwner",
"=",
"getOwner",
"(",
")",
";",
"State",
"state",
"=",
"new",
"State",
"(",
"this",
".",
"state",
")",
";",
"this",
".",
"datasetOwnerFs",
"=",
"ProxyUtils",
".",
"getOwnerFs",
"(",
"state",
",",
"this",
".",
"datasetOwner",
")",
";",
"try",
"(",
"HiveProxyQueryExecutor",
"queryExecutor",
"=",
"ProxyUtils",
".",
"getQueryExecutor",
"(",
"state",
",",
"this",
".",
"datasetOwner",
")",
")",
"{",
"if",
"(",
"this",
".",
"simulate",
")",
"{",
"log",
".",
"info",
"(",
"\"Simulate is set to true. Wont't run actual queries\"",
")",
";",
"return",
";",
"}",
"String",
"originalPartitionLocation",
"=",
"getOriginalPartitionLocation",
"(",
")",
";",
"// Create the staging table and staging partition",
"queryExecutor",
".",
"executeQueries",
"(",
"HivePurgerQueryTemplate",
".",
"getCreateStagingTableQuery",
"(",
"this",
")",
",",
"this",
".",
"datasetOwner",
")",
";",
"this",
".",
"startTime",
"=",
"getLastModifiedTime",
"(",
"originalPartitionLocation",
")",
";",
"// Execute purge queries, that is insert filtered data into the staging partition",
"queryExecutor",
".",
"executeQueries",
"(",
"this",
".",
"purgeQueries",
",",
"this",
".",
"datasetOwner",
")",
";",
"this",
".",
"endTime",
"=",
"getLastModifiedTime",
"(",
"originalPartitionLocation",
")",
";",
"// Create a backup table and partition pointing to the original partition location",
"queryExecutor",
".",
"executeQueries",
"(",
"HivePurgerQueryTemplate",
".",
"getBackupQueries",
"(",
"this",
")",
",",
"this",
".",
"datasetOwner",
")",
";",
"String",
"commitPolicyString",
"=",
"this",
".",
"state",
".",
"getProp",
"(",
"ComplianceConfigurationKeys",
".",
"PURGER_COMMIT_POLICY_CLASS",
",",
"ComplianceConfigurationKeys",
".",
"DEFAULT_PURGER_COMMIT_POLICY_CLASS",
")",
";",
"CommitPolicy",
"<",
"PurgeableHivePartitionDataset",
">",
"commitPolicy",
"=",
"GobblinConstructorUtils",
".",
"invokeConstructor",
"(",
"CommitPolicy",
".",
"class",
",",
"commitPolicyString",
")",
";",
"if",
"(",
"!",
"commitPolicy",
".",
"shouldCommit",
"(",
"this",
")",
")",
"{",
"log",
".",
"error",
"(",
"\"Last modified time before start of execution : \"",
"+",
"this",
".",
"startTime",
")",
";",
"log",
".",
"error",
"(",
"\"Last modified time after execution of purge queries : \"",
"+",
"this",
".",
"endTime",
")",
";",
"throw",
"new",
"RuntimeException",
"(",
"\"Failed to commit. File modified during job run.\"",
")",
";",
"}",
"// Alter the original table partition to start pointing to the cleaned-partition-location/staging-partition-location",
"queryExecutor",
".",
"executeQueries",
"(",
"HivePurgerQueryTemplate",
".",
"getAlterOriginalPartitionLocationQueries",
"(",
"this",
")",
",",
"this",
".",
"datasetOwner",
")",
";",
"// Drop the staging table",
"queryExecutor",
".",
"executeQueries",
"(",
"HivePurgerQueryTemplate",
".",
"getDropStagingTableQuery",
"(",
"this",
")",
",",
"this",
".",
"datasetOwner",
")",
";",
"}",
"catch",
"(",
"SQLException",
"e",
")",
"{",
"throw",
"new",
"IOException",
"(",
"e",
")",
";",
"}",
"}"
] | This method is responsible for actual purging.
- It first creates a staging table partition with the same schema as of original table partition.
- Staging table partition is then populated by original table left outer joined with compliance id table.
- Alter query will then change the partition location to the staging partition location.
- In flight queries won't get affected due to alter partition query. | [
"This",
"method",
"is",
"responsible",
"for",
"actual",
"purging",
".",
"-",
"It",
"first",
"creates",
"a",
"staging",
"table",
"partition",
"with",
"the",
"same",
"schema",
"as",
"of",
"original",
"table",
"partition",
".",
"-",
"Staging",
"table",
"partition",
"is",
"then",
"populated",
"by",
"original",
"table",
"left",
"outer",
"joined",
"with",
"compliance",
"id",
"table",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/purger/PurgeableHivePartitionDataset.java#L83-L126 |
25,657 | apache/incubator-gobblin | gobblin-yarn/src/main/java/org/apache/gobblin/yarn/GobblinYarnAppLauncher.java | GobblinYarnAppLauncher.launch | public void launch() throws IOException, YarnException {
this.eventBus.register(this);
String clusterName = this.config.getString(GobblinClusterConfigurationKeys.HELIX_CLUSTER_NAME_KEY);
HelixUtils.createGobblinHelixCluster(
this.config.getString(GobblinClusterConfigurationKeys.ZK_CONNECTION_STRING_KEY), clusterName);
LOGGER.info("Created Helix cluster " + clusterName);
connectHelixManager();
startYarnClient();
this.applicationId = getApplicationId();
this.applicationStatusMonitor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
eventBus.post(new ApplicationReportArrivalEvent(yarnClient.getApplicationReport(applicationId.get())));
} catch (YarnException | IOException e) {
LOGGER.error("Failed to get application report for Gobblin Yarn application " + applicationId.get(), e);
eventBus.post(new GetApplicationReportFailureEvent(e));
}
}
}, 0, this.appReportIntervalMinutes, TimeUnit.MINUTES);
List<Service> services = Lists.newArrayList();
if (this.config.hasPath(GobblinYarnConfigurationKeys.KEYTAB_FILE_PATH)) {
LOGGER.info("Adding YarnAppSecurityManager since login is keytab based");
services.add(buildYarnAppSecurityManager());
}
if (!this.config.hasPath(GobblinYarnConfigurationKeys.LOG_COPIER_DISABLE_DRIVER_COPY) ||
!this.config.getBoolean(GobblinYarnConfigurationKeys.LOG_COPIER_DISABLE_DRIVER_COPY)) {
services.add(buildLogCopier(this.config,
new Path(this.sinkLogRootDir, this.applicationName + Path.SEPARATOR + this.applicationId.get().toString()),
GobblinClusterUtils.getAppWorkDirPath(this.fs, this.applicationName, this.applicationId.get().toString())));
}
if (config.getBoolean(ConfigurationKeys.JOB_EXECINFO_SERVER_ENABLED_KEY)) {
LOGGER.info("Starting the job execution info server since it is enabled");
Properties properties = ConfigUtils.configToProperties(config);
JobExecutionInfoServer executionInfoServer = new JobExecutionInfoServer(properties);
services.add(executionInfoServer);
if (config.getBoolean(ConfigurationKeys.ADMIN_SERVER_ENABLED_KEY)) {
LOGGER.info("Starting the admin UI server since it is enabled");
services.add(ServiceBasedAppLauncher.createAdminServer(properties,
executionInfoServer.getAdvertisedServerUri()));
}
} else if (config.getBoolean(ConfigurationKeys.ADMIN_SERVER_ENABLED_KEY)) {
LOGGER.warn("NOT starting the admin UI because the job execution info server is NOT enabled");
}
this.serviceManager = Optional.of(new ServiceManager(services));
// Start all the services running in the ApplicationMaster
this.serviceManager.get().startAsync();
} | java | public void launch() throws IOException, YarnException {
this.eventBus.register(this);
String clusterName = this.config.getString(GobblinClusterConfigurationKeys.HELIX_CLUSTER_NAME_KEY);
HelixUtils.createGobblinHelixCluster(
this.config.getString(GobblinClusterConfigurationKeys.ZK_CONNECTION_STRING_KEY), clusterName);
LOGGER.info("Created Helix cluster " + clusterName);
connectHelixManager();
startYarnClient();
this.applicationId = getApplicationId();
this.applicationStatusMonitor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
eventBus.post(new ApplicationReportArrivalEvent(yarnClient.getApplicationReport(applicationId.get())));
} catch (YarnException | IOException e) {
LOGGER.error("Failed to get application report for Gobblin Yarn application " + applicationId.get(), e);
eventBus.post(new GetApplicationReportFailureEvent(e));
}
}
}, 0, this.appReportIntervalMinutes, TimeUnit.MINUTES);
List<Service> services = Lists.newArrayList();
if (this.config.hasPath(GobblinYarnConfigurationKeys.KEYTAB_FILE_PATH)) {
LOGGER.info("Adding YarnAppSecurityManager since login is keytab based");
services.add(buildYarnAppSecurityManager());
}
if (!this.config.hasPath(GobblinYarnConfigurationKeys.LOG_COPIER_DISABLE_DRIVER_COPY) ||
!this.config.getBoolean(GobblinYarnConfigurationKeys.LOG_COPIER_DISABLE_DRIVER_COPY)) {
services.add(buildLogCopier(this.config,
new Path(this.sinkLogRootDir, this.applicationName + Path.SEPARATOR + this.applicationId.get().toString()),
GobblinClusterUtils.getAppWorkDirPath(this.fs, this.applicationName, this.applicationId.get().toString())));
}
if (config.getBoolean(ConfigurationKeys.JOB_EXECINFO_SERVER_ENABLED_KEY)) {
LOGGER.info("Starting the job execution info server since it is enabled");
Properties properties = ConfigUtils.configToProperties(config);
JobExecutionInfoServer executionInfoServer = new JobExecutionInfoServer(properties);
services.add(executionInfoServer);
if (config.getBoolean(ConfigurationKeys.ADMIN_SERVER_ENABLED_KEY)) {
LOGGER.info("Starting the admin UI server since it is enabled");
services.add(ServiceBasedAppLauncher.createAdminServer(properties,
executionInfoServer.getAdvertisedServerUri()));
}
} else if (config.getBoolean(ConfigurationKeys.ADMIN_SERVER_ENABLED_KEY)) {
LOGGER.warn("NOT starting the admin UI because the job execution info server is NOT enabled");
}
this.serviceManager = Optional.of(new ServiceManager(services));
// Start all the services running in the ApplicationMaster
this.serviceManager.get().startAsync();
} | [
"public",
"void",
"launch",
"(",
")",
"throws",
"IOException",
",",
"YarnException",
"{",
"this",
".",
"eventBus",
".",
"register",
"(",
"this",
")",
";",
"String",
"clusterName",
"=",
"this",
".",
"config",
".",
"getString",
"(",
"GobblinClusterConfigurationKeys",
".",
"HELIX_CLUSTER_NAME_KEY",
")",
";",
"HelixUtils",
".",
"createGobblinHelixCluster",
"(",
"this",
".",
"config",
".",
"getString",
"(",
"GobblinClusterConfigurationKeys",
".",
"ZK_CONNECTION_STRING_KEY",
")",
",",
"clusterName",
")",
";",
"LOGGER",
".",
"info",
"(",
"\"Created Helix cluster \"",
"+",
"clusterName",
")",
";",
"connectHelixManager",
"(",
")",
";",
"startYarnClient",
"(",
")",
";",
"this",
".",
"applicationId",
"=",
"getApplicationId",
"(",
")",
";",
"this",
".",
"applicationStatusMonitor",
".",
"scheduleAtFixedRate",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"try",
"{",
"eventBus",
".",
"post",
"(",
"new",
"ApplicationReportArrivalEvent",
"(",
"yarnClient",
".",
"getApplicationReport",
"(",
"applicationId",
".",
"get",
"(",
")",
")",
")",
")",
";",
"}",
"catch",
"(",
"YarnException",
"|",
"IOException",
"e",
")",
"{",
"LOGGER",
".",
"error",
"(",
"\"Failed to get application report for Gobblin Yarn application \"",
"+",
"applicationId",
".",
"get",
"(",
")",
",",
"e",
")",
";",
"eventBus",
".",
"post",
"(",
"new",
"GetApplicationReportFailureEvent",
"(",
"e",
")",
")",
";",
"}",
"}",
"}",
",",
"0",
",",
"this",
".",
"appReportIntervalMinutes",
",",
"TimeUnit",
".",
"MINUTES",
")",
";",
"List",
"<",
"Service",
">",
"services",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
"if",
"(",
"this",
".",
"config",
".",
"hasPath",
"(",
"GobblinYarnConfigurationKeys",
".",
"KEYTAB_FILE_PATH",
")",
")",
"{",
"LOGGER",
".",
"info",
"(",
"\"Adding YarnAppSecurityManager since login is keytab based\"",
")",
";",
"services",
".",
"add",
"(",
"buildYarnAppSecurityManager",
"(",
")",
")",
";",
"}",
"if",
"(",
"!",
"this",
".",
"config",
".",
"hasPath",
"(",
"GobblinYarnConfigurationKeys",
".",
"LOG_COPIER_DISABLE_DRIVER_COPY",
")",
"||",
"!",
"this",
".",
"config",
".",
"getBoolean",
"(",
"GobblinYarnConfigurationKeys",
".",
"LOG_COPIER_DISABLE_DRIVER_COPY",
")",
")",
"{",
"services",
".",
"add",
"(",
"buildLogCopier",
"(",
"this",
".",
"config",
",",
"new",
"Path",
"(",
"this",
".",
"sinkLogRootDir",
",",
"this",
".",
"applicationName",
"+",
"Path",
".",
"SEPARATOR",
"+",
"this",
".",
"applicationId",
".",
"get",
"(",
")",
".",
"toString",
"(",
")",
")",
",",
"GobblinClusterUtils",
".",
"getAppWorkDirPath",
"(",
"this",
".",
"fs",
",",
"this",
".",
"applicationName",
",",
"this",
".",
"applicationId",
".",
"get",
"(",
")",
".",
"toString",
"(",
")",
")",
")",
")",
";",
"}",
"if",
"(",
"config",
".",
"getBoolean",
"(",
"ConfigurationKeys",
".",
"JOB_EXECINFO_SERVER_ENABLED_KEY",
")",
")",
"{",
"LOGGER",
".",
"info",
"(",
"\"Starting the job execution info server since it is enabled\"",
")",
";",
"Properties",
"properties",
"=",
"ConfigUtils",
".",
"configToProperties",
"(",
"config",
")",
";",
"JobExecutionInfoServer",
"executionInfoServer",
"=",
"new",
"JobExecutionInfoServer",
"(",
"properties",
")",
";",
"services",
".",
"add",
"(",
"executionInfoServer",
")",
";",
"if",
"(",
"config",
".",
"getBoolean",
"(",
"ConfigurationKeys",
".",
"ADMIN_SERVER_ENABLED_KEY",
")",
")",
"{",
"LOGGER",
".",
"info",
"(",
"\"Starting the admin UI server since it is enabled\"",
")",
";",
"services",
".",
"add",
"(",
"ServiceBasedAppLauncher",
".",
"createAdminServer",
"(",
"properties",
",",
"executionInfoServer",
".",
"getAdvertisedServerUri",
"(",
")",
")",
")",
";",
"}",
"}",
"else",
"if",
"(",
"config",
".",
"getBoolean",
"(",
"ConfigurationKeys",
".",
"ADMIN_SERVER_ENABLED_KEY",
")",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"NOT starting the admin UI because the job execution info server is NOT enabled\"",
")",
";",
"}",
"this",
".",
"serviceManager",
"=",
"Optional",
".",
"of",
"(",
"new",
"ServiceManager",
"(",
"services",
")",
")",
";",
"// Start all the services running in the ApplicationMaster",
"this",
".",
"serviceManager",
".",
"get",
"(",
")",
".",
"startAsync",
"(",
")",
";",
"}"
] | Launch a new Gobblin instance on Yarn.
@throws IOException if there's something wrong launching the application
@throws YarnException if there's something wrong launching the application | [
"Launch",
"a",
"new",
"Gobblin",
"instance",
"on",
"Yarn",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-yarn/src/main/java/org/apache/gobblin/yarn/GobblinYarnAppLauncher.java#L249-L303 |
25,658 | apache/incubator-gobblin | gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/restore/RestorableHivePartitionDatasetFinder.java | RestorableHivePartitionDatasetFinder.findDatasets | public List<HivePartitionDataset> findDatasets()
throws IOException {
Preconditions.checkArgument(this.state.contains(ComplianceConfigurationKeys.RESTORE_DATASET),
"Missing required property " + ComplianceConfigurationKeys.RESTORE_DATASET);
HivePartitionDataset hivePartitionDataset =
HivePartitionFinder.findDataset(this.state.getProp(ComplianceConfigurationKeys.RESTORE_DATASET), this.state);
Preconditions.checkNotNull(hivePartitionDataset, "No dataset to restore");
return Collections.singletonList(hivePartitionDataset);
} | java | public List<HivePartitionDataset> findDatasets()
throws IOException {
Preconditions.checkArgument(this.state.contains(ComplianceConfigurationKeys.RESTORE_DATASET),
"Missing required property " + ComplianceConfigurationKeys.RESTORE_DATASET);
HivePartitionDataset hivePartitionDataset =
HivePartitionFinder.findDataset(this.state.getProp(ComplianceConfigurationKeys.RESTORE_DATASET), this.state);
Preconditions.checkNotNull(hivePartitionDataset, "No dataset to restore");
return Collections.singletonList(hivePartitionDataset);
} | [
"public",
"List",
"<",
"HivePartitionDataset",
">",
"findDatasets",
"(",
")",
"throws",
"IOException",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"this",
".",
"state",
".",
"contains",
"(",
"ComplianceConfigurationKeys",
".",
"RESTORE_DATASET",
")",
",",
"\"Missing required property \"",
"+",
"ComplianceConfigurationKeys",
".",
"RESTORE_DATASET",
")",
";",
"HivePartitionDataset",
"hivePartitionDataset",
"=",
"HivePartitionFinder",
".",
"findDataset",
"(",
"this",
".",
"state",
".",
"getProp",
"(",
"ComplianceConfigurationKeys",
".",
"RESTORE_DATASET",
")",
",",
"this",
".",
"state",
")",
";",
"Preconditions",
".",
"checkNotNull",
"(",
"hivePartitionDataset",
",",
"\"No dataset to restore\"",
")",
";",
"return",
"Collections",
".",
"singletonList",
"(",
"hivePartitionDataset",
")",
";",
"}"
] | Will return a Singleton list of HivePartitionDataset to be restored. | [
"Will",
"return",
"a",
"Singleton",
"list",
"of",
"HivePartitionDataset",
"to",
"be",
"restored",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-compliance/src/main/java/org/apache/gobblin/compliance/restore/RestorableHivePartitionDatasetFinder.java#L59-L68 |
25,659 | apache/incubator-gobblin | gobblin-modules/gobblin-kafka-08/src/main/java/org/apache/gobblin/metrics/kafka/KafkaPusher.java | KafkaPusher.pushMessages | public void pushMessages(List<byte[]> messages) {
List<KeyedMessage<String, byte[]>> keyedMessages = Lists.transform(messages,
new Function<byte[], KeyedMessage<String, byte[]>>() {
@Nullable
@Override
public KeyedMessage<String, byte[]> apply(byte[] bytes) {
return new KeyedMessage<String, byte[]>(topic, bytes);
}
});
this.producer.send(keyedMessages);
} | java | public void pushMessages(List<byte[]> messages) {
List<KeyedMessage<String, byte[]>> keyedMessages = Lists.transform(messages,
new Function<byte[], KeyedMessage<String, byte[]>>() {
@Nullable
@Override
public KeyedMessage<String, byte[]> apply(byte[] bytes) {
return new KeyedMessage<String, byte[]>(topic, bytes);
}
});
this.producer.send(keyedMessages);
} | [
"public",
"void",
"pushMessages",
"(",
"List",
"<",
"byte",
"[",
"]",
">",
"messages",
")",
"{",
"List",
"<",
"KeyedMessage",
"<",
"String",
",",
"byte",
"[",
"]",
">",
">",
"keyedMessages",
"=",
"Lists",
".",
"transform",
"(",
"messages",
",",
"new",
"Function",
"<",
"byte",
"[",
"]",
",",
"KeyedMessage",
"<",
"String",
",",
"byte",
"[",
"]",
">",
">",
"(",
")",
"{",
"@",
"Nullable",
"@",
"Override",
"public",
"KeyedMessage",
"<",
"String",
",",
"byte",
"[",
"]",
">",
"apply",
"(",
"byte",
"[",
"]",
"bytes",
")",
"{",
"return",
"new",
"KeyedMessage",
"<",
"String",
",",
"byte",
"[",
"]",
">",
"(",
"topic",
",",
"bytes",
")",
";",
"}",
"}",
")",
";",
"this",
".",
"producer",
".",
"send",
"(",
"keyedMessages",
")",
";",
"}"
] | Push all mbyte array messages to the Kafka topic.
@param messages List of byte array messages to push to Kakfa. | [
"Push",
"all",
"mbyte",
"array",
"messages",
"to",
"the",
"Kafka",
"topic",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-08/src/main/java/org/apache/gobblin/metrics/kafka/KafkaPusher.java#L60-L70 |
25,660 | apache/incubator-gobblin | gobblin-modules/gobblin-kafka-08/src/main/java/org/apache/gobblin/metrics/kafka/KafkaPusher.java | KafkaPusher.createProducer | protected ProducerCloseable<String, byte[]> createProducer(ProducerConfig config) {
return this.closer.register(new ProducerCloseable<String, byte[]>(config));
} | java | protected ProducerCloseable<String, byte[]> createProducer(ProducerConfig config) {
return this.closer.register(new ProducerCloseable<String, byte[]>(config));
} | [
"protected",
"ProducerCloseable",
"<",
"String",
",",
"byte",
"[",
"]",
">",
"createProducer",
"(",
"ProducerConfig",
"config",
")",
"{",
"return",
"this",
".",
"closer",
".",
"register",
"(",
"new",
"ProducerCloseable",
"<",
"String",
",",
"byte",
"[",
"]",
">",
"(",
"config",
")",
")",
";",
"}"
] | Actually creates the Kafka producer. | [
"Actually",
"creates",
"the",
"Kafka",
"producer",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-kafka-08/src/main/java/org/apache/gobblin/metrics/kafka/KafkaPusher.java#L81-L83 |
25,661 | apache/incubator-gobblin | gobblin-core/src/main/java/org/apache/gobblin/writer/ThrottleWriter.java | ThrottleWriter.acquirePermits | private void acquirePermits(long permits) throws InterruptedException {
long startMs = System.currentTimeMillis(); //Measure in milliseconds. (Nanoseconds are more precise but expensive and not worth for this case)
limiter.acquirePermits(permits);
long permitAcquisitionTime = System.currentTimeMillis() - startMs;
if (throttledTimer.isPresent()) { // Metrics enabled
Instrumented.updateTimer(throttledTimer, permitAcquisitionTime, TimeUnit.MILLISECONDS);
}
this.throttledTime += permitAcquisitionTime;
} | java | private void acquirePermits(long permits) throws InterruptedException {
long startMs = System.currentTimeMillis(); //Measure in milliseconds. (Nanoseconds are more precise but expensive and not worth for this case)
limiter.acquirePermits(permits);
long permitAcquisitionTime = System.currentTimeMillis() - startMs;
if (throttledTimer.isPresent()) { // Metrics enabled
Instrumented.updateTimer(throttledTimer, permitAcquisitionTime, TimeUnit.MILLISECONDS);
}
this.throttledTime += permitAcquisitionTime;
} | [
"private",
"void",
"acquirePermits",
"(",
"long",
"permits",
")",
"throws",
"InterruptedException",
"{",
"long",
"startMs",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"//Measure in milliseconds. (Nanoseconds are more precise but expensive and not worth for this case)",
"limiter",
".",
"acquirePermits",
"(",
"permits",
")",
";",
"long",
"permitAcquisitionTime",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
"-",
"startMs",
";",
"if",
"(",
"throttledTimer",
".",
"isPresent",
"(",
")",
")",
"{",
"// Metrics enabled",
"Instrumented",
".",
"updateTimer",
"(",
"throttledTimer",
",",
"permitAcquisitionTime",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
";",
"}",
"this",
".",
"throttledTime",
"+=",
"permitAcquisitionTime",
";",
"}"
] | Acquire permit along with emitting metrics if enabled.
@param permits
@throws InterruptedException | [
"Acquire",
"permit",
"along",
"with",
"emitting",
"metrics",
"if",
"enabled",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/writer/ThrottleWriter.java#L154-L162 |
25,662 | apache/incubator-gobblin | gobblin-modules/gobblin-kafka-common/src/main/java/org/apache/gobblin/metrics/kafka/KafkaSchemaRegistry.java | KafkaSchemaRegistry.getSchemaByKey | public S getSchemaByKey(K 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 | public S getSchemaByKey(K 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);
}
} | [
"public",
"S",
"getSchemaByKey",
"(",
"K",
"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.
@throws SchemaRegistryException if failed to get schema by key. | [
"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/KafkaSchemaRegistry.java#L97-L103 |
25,663 | apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/HeapDumpForTaskUtils.java | HeapDumpForTaskUtils.generateDumpScript | public static void generateDumpScript(Path dumpScript, FileSystem fs, String heapFileName, String chmod)
throws IOException {
if (fs.exists(dumpScript)) {
LOG.info("Heap dump script already exists: " + dumpScript);
return;
}
try (BufferedWriter scriptWriter =
new BufferedWriter(new OutputStreamWriter(fs.create(dumpScript), ConfigurationKeys.DEFAULT_CHARSET_ENCODING))) {
Path dumpDir = new Path(dumpScript.getParent(), DUMP_FOLDER);
if (!fs.exists(dumpDir)) {
fs.mkdirs(dumpDir);
}
scriptWriter.write("#!/bin/sh\n");
scriptWriter.write("if [ -n \"$HADOOP_PREFIX\" ]; then\n");
scriptWriter
.write(" ${HADOOP_PREFIX}/bin/hadoop dfs -put " + heapFileName + " " + dumpDir + "/${PWD//\\//_}.hprof\n");
scriptWriter.write("else\n");
scriptWriter
.write(" ${HADOOP_HOME}/bin/hadoop dfs -put " + heapFileName + " " + dumpDir + "/${PWD//\\//_}.hprof\n");
scriptWriter.write("fi\n");
} catch (IOException ioe) {
LOG.error("Heap dump script is not generated successfully.");
if (fs.exists(dumpScript)) {
fs.delete(dumpScript, true);
}
throw ioe;
}
Runtime.getRuntime().exec(chmod + " " + dumpScript);
} | java | public static void generateDumpScript(Path dumpScript, FileSystem fs, String heapFileName, String chmod)
throws IOException {
if (fs.exists(dumpScript)) {
LOG.info("Heap dump script already exists: " + dumpScript);
return;
}
try (BufferedWriter scriptWriter =
new BufferedWriter(new OutputStreamWriter(fs.create(dumpScript), ConfigurationKeys.DEFAULT_CHARSET_ENCODING))) {
Path dumpDir = new Path(dumpScript.getParent(), DUMP_FOLDER);
if (!fs.exists(dumpDir)) {
fs.mkdirs(dumpDir);
}
scriptWriter.write("#!/bin/sh\n");
scriptWriter.write("if [ -n \"$HADOOP_PREFIX\" ]; then\n");
scriptWriter
.write(" ${HADOOP_PREFIX}/bin/hadoop dfs -put " + heapFileName + " " + dumpDir + "/${PWD//\\//_}.hprof\n");
scriptWriter.write("else\n");
scriptWriter
.write(" ${HADOOP_HOME}/bin/hadoop dfs -put " + heapFileName + " " + dumpDir + "/${PWD//\\//_}.hprof\n");
scriptWriter.write("fi\n");
} catch (IOException ioe) {
LOG.error("Heap dump script is not generated successfully.");
if (fs.exists(dumpScript)) {
fs.delete(dumpScript, true);
}
throw ioe;
}
Runtime.getRuntime().exec(chmod + " " + dumpScript);
} | [
"public",
"static",
"void",
"generateDumpScript",
"(",
"Path",
"dumpScript",
",",
"FileSystem",
"fs",
",",
"String",
"heapFileName",
",",
"String",
"chmod",
")",
"throws",
"IOException",
"{",
"if",
"(",
"fs",
".",
"exists",
"(",
"dumpScript",
")",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Heap dump script already exists: \"",
"+",
"dumpScript",
")",
";",
"return",
";",
"}",
"try",
"(",
"BufferedWriter",
"scriptWriter",
"=",
"new",
"BufferedWriter",
"(",
"new",
"OutputStreamWriter",
"(",
"fs",
".",
"create",
"(",
"dumpScript",
")",
",",
"ConfigurationKeys",
".",
"DEFAULT_CHARSET_ENCODING",
")",
")",
")",
"{",
"Path",
"dumpDir",
"=",
"new",
"Path",
"(",
"dumpScript",
".",
"getParent",
"(",
")",
",",
"DUMP_FOLDER",
")",
";",
"if",
"(",
"!",
"fs",
".",
"exists",
"(",
"dumpDir",
")",
")",
"{",
"fs",
".",
"mkdirs",
"(",
"dumpDir",
")",
";",
"}",
"scriptWriter",
".",
"write",
"(",
"\"#!/bin/sh\\n\"",
")",
";",
"scriptWriter",
".",
"write",
"(",
"\"if [ -n \\\"$HADOOP_PREFIX\\\" ]; then\\n\"",
")",
";",
"scriptWriter",
".",
"write",
"(",
"\" ${HADOOP_PREFIX}/bin/hadoop dfs -put \"",
"+",
"heapFileName",
"+",
"\" \"",
"+",
"dumpDir",
"+",
"\"/${PWD//\\\\//_}.hprof\\n\"",
")",
";",
"scriptWriter",
".",
"write",
"(",
"\"else\\n\"",
")",
";",
"scriptWriter",
".",
"write",
"(",
"\" ${HADOOP_HOME}/bin/hadoop dfs -put \"",
"+",
"heapFileName",
"+",
"\" \"",
"+",
"dumpDir",
"+",
"\"/${PWD//\\\\//_}.hprof\\n\"",
")",
";",
"scriptWriter",
".",
"write",
"(",
"\"fi\\n\"",
")",
";",
"}",
"catch",
"(",
"IOException",
"ioe",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Heap dump script is not generated successfully.\"",
")",
";",
"if",
"(",
"fs",
".",
"exists",
"(",
"dumpScript",
")",
")",
"{",
"fs",
".",
"delete",
"(",
"dumpScript",
",",
"true",
")",
";",
"}",
"throw",
"ioe",
";",
"}",
"Runtime",
".",
"getRuntime",
"(",
")",
".",
"exec",
"(",
"chmod",
"+",
"\" \"",
"+",
"dumpScript",
")",
";",
"}"
] | Generate the dumpScript, which is used when OOM error is thrown during task execution.
The current content dumpScript puts the .prof files to the DUMP_FOLDER within the same directory of the dumpScript.
User needs to add the following options to the task java.opts:
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./heapFileName.hprof -XX:OnOutOfMemoryError=./dumpScriptFileName
@param dumpScript The path to the dumpScript, which needs to be added to the Distributed cache.
To use it, simply put the path of dumpScript to the gobblin config: job.hdfs.files.
@param fs File system
@param heapFileName the name of the .prof file.
@param chmod chmod for the dump script. For hdfs file, e.g, "hadoop fs -chmod 755"
@throws IOException | [
"Generate",
"the",
"dumpScript",
"which",
"is",
"used",
"when",
"OOM",
"error",
"is",
"thrown",
"during",
"task",
"execution",
".",
"The",
"current",
"content",
"dumpScript",
"puts",
"the",
".",
"prof",
"files",
"to",
"the",
"DUMP_FOLDER",
"within",
"the",
"same",
"directory",
"of",
"the",
"dumpScript",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/HeapDumpForTaskUtils.java#L55-L86 |
25,664 | apache/incubator-gobblin | gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/EventSubmitter.java | EventSubmitter.submit | public static void submit(Optional<EventSubmitter> submitter, String name) {
if (submitter.isPresent()) {
submitter.get().submit(name);
}
} | java | public static void submit(Optional<EventSubmitter> submitter, String name) {
if (submitter.isPresent()) {
submitter.get().submit(name);
}
} | [
"public",
"static",
"void",
"submit",
"(",
"Optional",
"<",
"EventSubmitter",
">",
"submitter",
",",
"String",
"name",
")",
"{",
"if",
"(",
"submitter",
".",
"isPresent",
"(",
")",
")",
"{",
"submitter",
".",
"get",
"(",
")",
".",
"submit",
"(",
"name",
")",
";",
"}",
"}"
] | Calls submit on submitter if present. | [
"Calls",
"submit",
"on",
"submitter",
"if",
"present",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/event/EventSubmitter.java#L99-L103 |
25,665 | apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/JvmUtils.java | JvmUtils.getJvmInputArguments | public static String getJvmInputArguments() {
RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
List<String> arguments = runtimeMxBean.getInputArguments();
return String.format("JVM Input Arguments: %s", JOINER.join(arguments));
} | java | public static String getJvmInputArguments() {
RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
List<String> arguments = runtimeMxBean.getInputArguments();
return String.format("JVM Input Arguments: %s", JOINER.join(arguments));
} | [
"public",
"static",
"String",
"getJvmInputArguments",
"(",
")",
"{",
"RuntimeMXBean",
"runtimeMxBean",
"=",
"ManagementFactory",
".",
"getRuntimeMXBean",
"(",
")",
";",
"List",
"<",
"String",
">",
"arguments",
"=",
"runtimeMxBean",
".",
"getInputArguments",
"(",
")",
";",
"return",
"String",
".",
"format",
"(",
"\"JVM Input Arguments: %s\"",
",",
"JOINER",
".",
"join",
"(",
"arguments",
")",
")",
";",
"}"
] | Gets the input arguments passed to the JVM.
@return The input arguments. | [
"Gets",
"the",
"input",
"arguments",
"passed",
"to",
"the",
"JVM",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/JvmUtils.java#L39-L43 |
25,666 | apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/JvmUtils.java | JvmUtils.formatJvmArguments | public static String formatJvmArguments(Optional<String> jvmArguments) {
if (jvmArguments.isPresent()) {
return PORT_UTILS.replacePortTokens(jvmArguments.get());
}
return StringUtils.EMPTY;
} | java | public static String formatJvmArguments(Optional<String> jvmArguments) {
if (jvmArguments.isPresent()) {
return PORT_UTILS.replacePortTokens(jvmArguments.get());
}
return StringUtils.EMPTY;
} | [
"public",
"static",
"String",
"formatJvmArguments",
"(",
"Optional",
"<",
"String",
">",
"jvmArguments",
")",
"{",
"if",
"(",
"jvmArguments",
".",
"isPresent",
"(",
")",
")",
"{",
"return",
"PORT_UTILS",
".",
"replacePortTokens",
"(",
"jvmArguments",
".",
"get",
"(",
")",
")",
";",
"}",
"return",
"StringUtils",
".",
"EMPTY",
";",
"}"
] | Formats the specified jvm arguments such that any tokens are replaced with concrete values;
@param jvmArguments
@return The formatted jvm arguments. | [
"Formats",
"the",
"specified",
"jvm",
"arguments",
"such",
"that",
"any",
"tokens",
"are",
"replaced",
"with",
"concrete",
"values",
";"
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/JvmUtils.java#L50-L55 |
25,667 | apache/incubator-gobblin | gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/converter/initializer/AvroToJdbcEntryConverterInitializer.java | AvroToJdbcEntryConverterInitializer.initialize | @Override
public void initialize() {
String table = Preconditions.checkNotNull(this.state.getProp(ForkOperatorUtils
.getPropertyNameForBranch(JdbcPublisher.JDBC_PUBLISHER_FINAL_TABLE_NAME, this.branches, this.branchId)));
String db = Preconditions.checkNotNull(this.state.getProp(ForkOperatorUtils
.getPropertyNameForBranch(JdbcPublisher.JDBC_PUBLISHER_DATABASE_NAME, this.branches, this.branchId)));
try (Connection conn = createConnection()) {
JdbcWriterCommands commands = this.jdbcWriterCommandsFactory.newInstance(this.state, conn);
Map<String, JdbcType> dateColumnMapping = commands.retrieveDateColumns(db, table);
LOG.info("Date column mapping: " + dateColumnMapping);
final String dateFieldsKey = ForkOperatorUtils.getPropertyNameForBranch(
AvroToJdbcEntryConverter.CONVERTER_AVRO_JDBC_DATE_FIELDS, this.branches, this.branchId);
for (WorkUnit wu : this.workUnits) {
wu.setProp(dateFieldsKey, new Gson().toJson(dateColumnMapping));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
} | java | @Override
public void initialize() {
String table = Preconditions.checkNotNull(this.state.getProp(ForkOperatorUtils
.getPropertyNameForBranch(JdbcPublisher.JDBC_PUBLISHER_FINAL_TABLE_NAME, this.branches, this.branchId)));
String db = Preconditions.checkNotNull(this.state.getProp(ForkOperatorUtils
.getPropertyNameForBranch(JdbcPublisher.JDBC_PUBLISHER_DATABASE_NAME, this.branches, this.branchId)));
try (Connection conn = createConnection()) {
JdbcWriterCommands commands = this.jdbcWriterCommandsFactory.newInstance(this.state, conn);
Map<String, JdbcType> dateColumnMapping = commands.retrieveDateColumns(db, table);
LOG.info("Date column mapping: " + dateColumnMapping);
final String dateFieldsKey = ForkOperatorUtils.getPropertyNameForBranch(
AvroToJdbcEntryConverter.CONVERTER_AVRO_JDBC_DATE_FIELDS, this.branches, this.branchId);
for (WorkUnit wu : this.workUnits) {
wu.setProp(dateFieldsKey, new Gson().toJson(dateColumnMapping));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
} | [
"@",
"Override",
"public",
"void",
"initialize",
"(",
")",
"{",
"String",
"table",
"=",
"Preconditions",
".",
"checkNotNull",
"(",
"this",
".",
"state",
".",
"getProp",
"(",
"ForkOperatorUtils",
".",
"getPropertyNameForBranch",
"(",
"JdbcPublisher",
".",
"JDBC_PUBLISHER_FINAL_TABLE_NAME",
",",
"this",
".",
"branches",
",",
"this",
".",
"branchId",
")",
")",
")",
";",
"String",
"db",
"=",
"Preconditions",
".",
"checkNotNull",
"(",
"this",
".",
"state",
".",
"getProp",
"(",
"ForkOperatorUtils",
".",
"getPropertyNameForBranch",
"(",
"JdbcPublisher",
".",
"JDBC_PUBLISHER_DATABASE_NAME",
",",
"this",
".",
"branches",
",",
"this",
".",
"branchId",
")",
")",
")",
";",
"try",
"(",
"Connection",
"conn",
"=",
"createConnection",
"(",
")",
")",
"{",
"JdbcWriterCommands",
"commands",
"=",
"this",
".",
"jdbcWriterCommandsFactory",
".",
"newInstance",
"(",
"this",
".",
"state",
",",
"conn",
")",
";",
"Map",
"<",
"String",
",",
"JdbcType",
">",
"dateColumnMapping",
"=",
"commands",
".",
"retrieveDateColumns",
"(",
"db",
",",
"table",
")",
";",
"LOG",
".",
"info",
"(",
"\"Date column mapping: \"",
"+",
"dateColumnMapping",
")",
";",
"final",
"String",
"dateFieldsKey",
"=",
"ForkOperatorUtils",
".",
"getPropertyNameForBranch",
"(",
"AvroToJdbcEntryConverter",
".",
"CONVERTER_AVRO_JDBC_DATE_FIELDS",
",",
"this",
".",
"branches",
",",
"this",
".",
"branchId",
")",
";",
"for",
"(",
"WorkUnit",
"wu",
":",
"this",
".",
"workUnits",
")",
"{",
"wu",
".",
"setProp",
"(",
"dateFieldsKey",
",",
"new",
"Gson",
"(",
")",
".",
"toJson",
"(",
"dateColumnMapping",
")",
")",
";",
"}",
"}",
"catch",
"(",
"SQLException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] | AvroToJdbcEntryConverter list of date columns existing in the table. As we don't want each converter
making a connection against database to get the same information. Here, ConverterInitializer will
retrieve it and store it into WorkUnit so that AvroToJdbcEntryConverter will use it later.
{@inheritDoc}
@see org.apache.gobblin.initializer.Initializer#initialize() | [
"AvroToJdbcEntryConverter",
"list",
"of",
"date",
"columns",
"existing",
"in",
"the",
"table",
".",
"As",
"we",
"don",
"t",
"want",
"each",
"converter",
"making",
"a",
"connection",
"against",
"database",
"to",
"get",
"the",
"same",
"information",
".",
"Here",
"ConverterInitializer",
"will",
"retrieve",
"it",
"and",
"store",
"it",
"into",
"WorkUnit",
"so",
"that",
"AvroToJdbcEntryConverter",
"will",
"use",
"it",
"later",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/converter/initializer/AvroToJdbcEntryConverterInitializer.java#L80-L99 |
25,668 | apache/incubator-gobblin | gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GitMonitoringService.java | GitMonitoringService.startUp | @Override
protected void startUp() {
log.info("Starting the " + getClass().getSimpleName());
log.info("Polling git with interval {} ", this.pollingInterval);
// Schedule the job config fetch task
this.scheduledExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
if (shouldPollGit()) {
processGitConfigChanges();
}
} catch (GitAPIException | IOException e) {
log.error("Failed to process git config changes", e);
// next run will try again since errors could be intermittent
}
}
}, 0, this.pollingInterval, TimeUnit.SECONDS);
} | java | @Override
protected void startUp() {
log.info("Starting the " + getClass().getSimpleName());
log.info("Polling git with interval {} ", this.pollingInterval);
// Schedule the job config fetch task
this.scheduledExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
if (shouldPollGit()) {
processGitConfigChanges();
}
} catch (GitAPIException | IOException e) {
log.error("Failed to process git config changes", e);
// next run will try again since errors could be intermittent
}
}
}, 0, this.pollingInterval, TimeUnit.SECONDS);
} | [
"@",
"Override",
"protected",
"void",
"startUp",
"(",
")",
"{",
"log",
".",
"info",
"(",
"\"Starting the \"",
"+",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
")",
";",
"log",
".",
"info",
"(",
"\"Polling git with interval {} \"",
",",
"this",
".",
"pollingInterval",
")",
";",
"// Schedule the job config fetch task",
"this",
".",
"scheduledExecutor",
".",
"scheduleAtFixedRate",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"try",
"{",
"if",
"(",
"shouldPollGit",
"(",
")",
")",
"{",
"processGitConfigChanges",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"GitAPIException",
"|",
"IOException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"Failed to process git config changes\"",
",",
"e",
")",
";",
"// next run will try again since errors could be intermittent",
"}",
"}",
"}",
",",
"0",
",",
"this",
".",
"pollingInterval",
",",
"TimeUnit",
".",
"SECONDS",
")",
";",
"}"
] | Start the service. | [
"Start",
"the",
"service",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GitMonitoringService.java#L195-L214 |
25,669 | apache/incubator-gobblin | gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GitMonitoringService.java | GitMonitoringService.processGitConfigChangesHelper | void processGitConfigChangesHelper(List<DiffEntry> changes) throws IOException {
for (DiffEntry change : changes) {
switch (change.getChangeType()) {
case ADD:
case MODIFY:
addChange(change);
break;
case DELETE:
removeChange(change);
break;
case RENAME:
removeChange(change);
addChange(change);
break;
default:
throw new RuntimeException("Unsupported change type " + change.getChangeType());
}
}
// Done processing changes, so checkpoint
this.gitRepo.moveCheckpointAndHashesForward();
} | java | void processGitConfigChangesHelper(List<DiffEntry> changes) throws IOException {
for (DiffEntry change : changes) {
switch (change.getChangeType()) {
case ADD:
case MODIFY:
addChange(change);
break;
case DELETE:
removeChange(change);
break;
case RENAME:
removeChange(change);
addChange(change);
break;
default:
throw new RuntimeException("Unsupported change type " + change.getChangeType());
}
}
// Done processing changes, so checkpoint
this.gitRepo.moveCheckpointAndHashesForward();
} | [
"void",
"processGitConfigChangesHelper",
"(",
"List",
"<",
"DiffEntry",
">",
"changes",
")",
"throws",
"IOException",
"{",
"for",
"(",
"DiffEntry",
"change",
":",
"changes",
")",
"{",
"switch",
"(",
"change",
".",
"getChangeType",
"(",
")",
")",
"{",
"case",
"ADD",
":",
"case",
"MODIFY",
":",
"addChange",
"(",
"change",
")",
";",
"break",
";",
"case",
"DELETE",
":",
"removeChange",
"(",
"change",
")",
";",
"break",
";",
"case",
"RENAME",
":",
"removeChange",
"(",
"change",
")",
";",
"addChange",
"(",
"change",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"RuntimeException",
"(",
"\"Unsupported change type \"",
"+",
"change",
".",
"getChangeType",
"(",
")",
")",
";",
"}",
"}",
"// Done processing changes, so checkpoint",
"this",
".",
"gitRepo",
".",
"moveCheckpointAndHashesForward",
"(",
")",
";",
"}"
] | A helper method where actual processing of the list of changes since the last refresh of the repository takes place
and the changes applied.
@throws IOException | [
"A",
"helper",
"method",
"where",
"actual",
"processing",
"of",
"the",
"list",
"of",
"changes",
"since",
"the",
"last",
"refresh",
"of",
"the",
"repository",
"takes",
"place",
"and",
"the",
"changes",
"applied",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-service/src/main/java/org/apache/gobblin/service/modules/core/GitMonitoringService.java#L234-L255 |
25,670 | apache/incubator-gobblin | gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java | State.addAll | public void addAll(State otherState) {
Properties diffCommonProps = new Properties();
diffCommonProps.putAll(Maps.difference(this.commonProperties, otherState.commonProperties).entriesOnlyOnRight());
addAll(diffCommonProps);
addAll(otherState.specProperties);
} | java | public void addAll(State otherState) {
Properties diffCommonProps = new Properties();
diffCommonProps.putAll(Maps.difference(this.commonProperties, otherState.commonProperties).entriesOnlyOnRight());
addAll(diffCommonProps);
addAll(otherState.specProperties);
} | [
"public",
"void",
"addAll",
"(",
"State",
"otherState",
")",
"{",
"Properties",
"diffCommonProps",
"=",
"new",
"Properties",
"(",
")",
";",
"diffCommonProps",
".",
"putAll",
"(",
"Maps",
".",
"difference",
"(",
"this",
".",
"commonProperties",
",",
"otherState",
".",
"commonProperties",
")",
".",
"entriesOnlyOnRight",
"(",
")",
")",
";",
"addAll",
"(",
"diffCommonProps",
")",
";",
"addAll",
"(",
"otherState",
".",
"specProperties",
")",
";",
"}"
] | Populates this instance with properties of the other instance.
@param otherState the other {@link State} instance | [
"Populates",
"this",
"instance",
"with",
"properties",
"of",
"the",
"other",
"instance",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java#L112-L117 |
25,671 | apache/incubator-gobblin | gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java | State.getProp | public String getProp(String key) {
if (this.specProperties.containsKey(key)) {
return this.specProperties.getProperty(key);
}
return this.commonProperties.getProperty(key);
} | java | public String getProp(String key) {
if (this.specProperties.containsKey(key)) {
return this.specProperties.getProperty(key);
}
return this.commonProperties.getProperty(key);
} | [
"public",
"String",
"getProp",
"(",
"String",
"key",
")",
"{",
"if",
"(",
"this",
".",
"specProperties",
".",
"containsKey",
"(",
"key",
")",
")",
"{",
"return",
"this",
".",
"specProperties",
".",
"getProperty",
"(",
"key",
")",
";",
"}",
"return",
"this",
".",
"commonProperties",
".",
"getProperty",
"(",
"key",
")",
";",
"}"
] | Get the value of a property.
@param key property key
@return value associated with the key as a string or <code>null</code> if the property is not set | [
"Get",
"the",
"value",
"of",
"a",
"property",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java#L262-L267 |
25,672 | apache/incubator-gobblin | gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java | State.getPropAsList | public List<String> getPropAsList(String key, String def) {
return LIST_SPLITTER.splitToList(getProp(key, def));
} | java | public List<String> getPropAsList(String key, String def) {
return LIST_SPLITTER.splitToList(getProp(key, def));
} | [
"public",
"List",
"<",
"String",
">",
"getPropAsList",
"(",
"String",
"key",
",",
"String",
"def",
")",
"{",
"return",
"LIST_SPLITTER",
".",
"splitToList",
"(",
"getProp",
"(",
"key",
",",
"def",
")",
")",
";",
"}"
] | Get the value of a property as a list of strings, using the given default value if the property is not set.
@param key property key
@param def default value
@return value (the default value if the property is not set) associated with the key as a list of strings | [
"Get",
"the",
"value",
"of",
"a",
"property",
"as",
"a",
"list",
"of",
"strings",
"using",
"the",
"given",
"default",
"value",
"if",
"the",
"property",
"is",
"not",
"set",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java#L300-L302 |
25,673 | apache/incubator-gobblin | gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java | State.getPropAsLong | public long getPropAsLong(String key, long def) {
return Long.parseLong(getProp(key, String.valueOf(def)));
} | java | public long getPropAsLong(String key, long def) {
return Long.parseLong(getProp(key, String.valueOf(def)));
} | [
"public",
"long",
"getPropAsLong",
"(",
"String",
"key",
",",
"long",
"def",
")",
"{",
"return",
"Long",
".",
"parseLong",
"(",
"getProp",
"(",
"key",
",",
"String",
".",
"valueOf",
"(",
"def",
")",
")",
")",
";",
"}"
] | Get the value of a property as a long integer, using the given default value if the property is not set.
@param key property key
@param def default value
@return long integer value associated with the key or the default value if the property is not set | [
"Get",
"the",
"value",
"of",
"a",
"property",
"as",
"a",
"long",
"integer",
"using",
"the",
"given",
"default",
"value",
"if",
"the",
"property",
"is",
"not",
"set",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java#L363-L365 |
25,674 | apache/incubator-gobblin | gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java | State.getPropAsInt | public int getPropAsInt(String key, int def) {
return Integer.parseInt(getProp(key, String.valueOf(def)));
} | java | public int getPropAsInt(String key, int def) {
return Integer.parseInt(getProp(key, String.valueOf(def)));
} | [
"public",
"int",
"getPropAsInt",
"(",
"String",
"key",
",",
"int",
"def",
")",
"{",
"return",
"Integer",
".",
"parseInt",
"(",
"getProp",
"(",
"key",
",",
"String",
".",
"valueOf",
"(",
"def",
")",
")",
")",
";",
"}"
] | Get the value of a property as an integer, using the given default value if the property is not set.
@param key property key
@param def default value
@return integer value associated with the key or the default value if the property is not set | [
"Get",
"the",
"value",
"of",
"a",
"property",
"as",
"an",
"integer",
"using",
"the",
"given",
"default",
"value",
"if",
"the",
"property",
"is",
"not",
"set",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java#L384-L386 |
25,675 | apache/incubator-gobblin | gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java | State.getPropAsDouble | public double getPropAsDouble(String key, double def) {
return Double.parseDouble(getProp(key, String.valueOf(def)));
} | java | public double getPropAsDouble(String key, double def) {
return Double.parseDouble(getProp(key, String.valueOf(def)));
} | [
"public",
"double",
"getPropAsDouble",
"(",
"String",
"key",
",",
"double",
"def",
")",
"{",
"return",
"Double",
".",
"parseDouble",
"(",
"getProp",
"(",
"key",
",",
"String",
".",
"valueOf",
"(",
"def",
")",
")",
")",
";",
"}"
] | Get the value of a property as a double, using the given default value if the property is not set.
@param key property key
@param def default value
@return double value associated with the key or the default value if the property is not set | [
"Get",
"the",
"value",
"of",
"a",
"property",
"as",
"a",
"double",
"using",
"the",
"given",
"default",
"value",
"if",
"the",
"property",
"is",
"not",
"set",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java#L449-L451 |
25,676 | apache/incubator-gobblin | gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java | State.getPropAsBoolean | public boolean getPropAsBoolean(String key, boolean def) {
return Boolean.parseBoolean(getProp(key, String.valueOf(def)));
} | java | public boolean getPropAsBoolean(String key, boolean def) {
return Boolean.parseBoolean(getProp(key, String.valueOf(def)));
} | [
"public",
"boolean",
"getPropAsBoolean",
"(",
"String",
"key",
",",
"boolean",
"def",
")",
"{",
"return",
"Boolean",
".",
"parseBoolean",
"(",
"getProp",
"(",
"key",
",",
"String",
".",
"valueOf",
"(",
"def",
")",
")",
")",
";",
"}"
] | Get the value of a property as a boolean, using the given default value if the property is not set.
@param key property key
@param def default value
@return boolean value associated with the key or the default value if the property is not set | [
"Get",
"the",
"value",
"of",
"a",
"property",
"as",
"a",
"boolean",
"using",
"the",
"given",
"default",
"value",
"if",
"the",
"property",
"is",
"not",
"set",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java#L470-L472 |
25,677 | apache/incubator-gobblin | gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java | State.removeProp | public void removeProp(String key) {
this.specProperties.remove(key);
if (this.commonProperties.containsKey(key)) {
// This case should not happen.
Properties commonPropsCopy = new Properties();
commonPropsCopy.putAll(this.commonProperties);
commonPropsCopy.remove(key);
this.commonProperties = commonPropsCopy;
}
} | java | public void removeProp(String key) {
this.specProperties.remove(key);
if (this.commonProperties.containsKey(key)) {
// This case should not happen.
Properties commonPropsCopy = new Properties();
commonPropsCopy.putAll(this.commonProperties);
commonPropsCopy.remove(key);
this.commonProperties = commonPropsCopy;
}
} | [
"public",
"void",
"removeProp",
"(",
"String",
"key",
")",
"{",
"this",
".",
"specProperties",
".",
"remove",
"(",
"key",
")",
";",
"if",
"(",
"this",
".",
"commonProperties",
".",
"containsKey",
"(",
"key",
")",
")",
"{",
"// This case should not happen.",
"Properties",
"commonPropsCopy",
"=",
"new",
"Properties",
"(",
")",
";",
"commonPropsCopy",
".",
"putAll",
"(",
"this",
".",
"commonProperties",
")",
";",
"commonPropsCopy",
".",
"remove",
"(",
"key",
")",
";",
"this",
".",
"commonProperties",
"=",
"commonPropsCopy",
";",
"}",
"}"
] | Remove a property if it exists.
@param key property key | [
"Remove",
"a",
"property",
"if",
"it",
"exists",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java#L492-L501 |
25,678 | apache/incubator-gobblin | gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java | State.removePropsWithPrefix | public void removePropsWithPrefix(String prefix) {
this.specProperties.entrySet().removeIf(entry -> ((String) entry.getKey()).startsWith(prefix));
Properties newCommonProperties = null;
for (Object key: this.commonProperties.keySet()) {
if (((String)key).startsWith(prefix)) {
if (newCommonProperties == null) {
newCommonProperties = new Properties();
newCommonProperties.putAll(this.commonProperties);
}
newCommonProperties.remove(key);
}
}
if (newCommonProperties != null) {
this.commonProperties = newCommonProperties;
}
} | java | public void removePropsWithPrefix(String prefix) {
this.specProperties.entrySet().removeIf(entry -> ((String) entry.getKey()).startsWith(prefix));
Properties newCommonProperties = null;
for (Object key: this.commonProperties.keySet()) {
if (((String)key).startsWith(prefix)) {
if (newCommonProperties == null) {
newCommonProperties = new Properties();
newCommonProperties.putAll(this.commonProperties);
}
newCommonProperties.remove(key);
}
}
if (newCommonProperties != null) {
this.commonProperties = newCommonProperties;
}
} | [
"public",
"void",
"removePropsWithPrefix",
"(",
"String",
"prefix",
")",
"{",
"this",
".",
"specProperties",
".",
"entrySet",
"(",
")",
".",
"removeIf",
"(",
"entry",
"->",
"(",
"(",
"String",
")",
"entry",
".",
"getKey",
"(",
")",
")",
".",
"startsWith",
"(",
"prefix",
")",
")",
";",
"Properties",
"newCommonProperties",
"=",
"null",
";",
"for",
"(",
"Object",
"key",
":",
"this",
".",
"commonProperties",
".",
"keySet",
"(",
")",
")",
"{",
"if",
"(",
"(",
"(",
"String",
")",
"key",
")",
".",
"startsWith",
"(",
"prefix",
")",
")",
"{",
"if",
"(",
"newCommonProperties",
"==",
"null",
")",
"{",
"newCommonProperties",
"=",
"new",
"Properties",
"(",
")",
";",
"newCommonProperties",
".",
"putAll",
"(",
"this",
".",
"commonProperties",
")",
";",
"}",
"newCommonProperties",
".",
"remove",
"(",
"key",
")",
";",
"}",
"}",
"if",
"(",
"newCommonProperties",
"!=",
"null",
")",
"{",
"this",
".",
"commonProperties",
"=",
"newCommonProperties",
";",
"}",
"}"
] | Remove all properties with a certain keyPrefix
@param prefix key prefix | [
"Remove",
"all",
"properties",
"with",
"a",
"certain",
"keyPrefix"
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/configuration/State.java#L508-L525 |
25,679 | apache/incubator-gobblin | gobblin-core/src/main/java/org/apache/gobblin/publisher/TimestampDataPublisher.java | TimestampDataPublisher.getDbTableName | private String getDbTableName(String schemaName) {
Preconditions.checkArgument(schemaName.matches(".+_.+_.+"));
return schemaName.replaceFirst("_", ".").substring(0, schemaName.lastIndexOf('_'));
} | java | private String getDbTableName(String schemaName) {
Preconditions.checkArgument(schemaName.matches(".+_.+_.+"));
return schemaName.replaceFirst("_", ".").substring(0, schemaName.lastIndexOf('_'));
} | [
"private",
"String",
"getDbTableName",
"(",
"String",
"schemaName",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"schemaName",
".",
"matches",
"(",
"\".+_.+_.+\"",
")",
")",
";",
"return",
"schemaName",
".",
"replaceFirst",
"(",
"\"_\"",
",",
"\".\"",
")",
".",
"substring",
"(",
"0",
",",
"schemaName",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
")",
";",
"}"
] | Translate schema name to "dbname.tablename" to use in path
@param schemaName In format "dbname_tablename_xxxxx"
@return db and table name in format "dbname.tablename" | [
"Translate",
"schema",
"name",
"to",
"dbname",
".",
"tablename",
"to",
"use",
"in",
"path"
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/publisher/TimestampDataPublisher.java#L90-L93 |
25,680 | apache/incubator-gobblin | gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/splitter/DistcpFileSplitter.java | DistcpFileSplitter.mergeAllSplitWorkUnits | public static Collection<WorkUnitState> mergeAllSplitWorkUnits(FileSystem fs, Collection<WorkUnitState> workUnits)
throws IOException {
ListMultimap<CopyableFile, WorkUnitState> splitWorkUnitsMap = ArrayListMultimap.create();
for (WorkUnitState workUnit : workUnits) {
if (isSplitWorkUnit(workUnit)) {
CopyableFile copyableFile = (CopyableFile) CopySource.deserializeCopyEntity(workUnit);
splitWorkUnitsMap.put(copyableFile, workUnit);
}
}
for (CopyableFile file : splitWorkUnitsMap.keySet()) {
log.info(String.format("Merging split file %s.", file.getDestination()));
WorkUnitState oldWorkUnit = splitWorkUnitsMap.get(file).get(0);
Path outputDir = FileAwareInputStreamDataWriter.getOutputDir(oldWorkUnit);
CopyEntity.DatasetAndPartition datasetAndPartition =
file.getDatasetAndPartition(CopySource.deserializeCopyableDataset(oldWorkUnit));
Path parentPath = FileAwareInputStreamDataWriter.getOutputFilePath(file, outputDir, datasetAndPartition)
.getParent();
WorkUnitState newWorkUnit = mergeSplits(fs, file, splitWorkUnitsMap.get(file), parentPath);
for (WorkUnitState wu : splitWorkUnitsMap.get(file)) {
// Set to committed so that task states will not fail
wu.setWorkingState(WorkUnitState.WorkingState.COMMITTED);
workUnits.remove(wu);
}
workUnits.add(newWorkUnit);
}
return workUnits;
} | java | public static Collection<WorkUnitState> mergeAllSplitWorkUnits(FileSystem fs, Collection<WorkUnitState> workUnits)
throws IOException {
ListMultimap<CopyableFile, WorkUnitState> splitWorkUnitsMap = ArrayListMultimap.create();
for (WorkUnitState workUnit : workUnits) {
if (isSplitWorkUnit(workUnit)) {
CopyableFile copyableFile = (CopyableFile) CopySource.deserializeCopyEntity(workUnit);
splitWorkUnitsMap.put(copyableFile, workUnit);
}
}
for (CopyableFile file : splitWorkUnitsMap.keySet()) {
log.info(String.format("Merging split file %s.", file.getDestination()));
WorkUnitState oldWorkUnit = splitWorkUnitsMap.get(file).get(0);
Path outputDir = FileAwareInputStreamDataWriter.getOutputDir(oldWorkUnit);
CopyEntity.DatasetAndPartition datasetAndPartition =
file.getDatasetAndPartition(CopySource.deserializeCopyableDataset(oldWorkUnit));
Path parentPath = FileAwareInputStreamDataWriter.getOutputFilePath(file, outputDir, datasetAndPartition)
.getParent();
WorkUnitState newWorkUnit = mergeSplits(fs, file, splitWorkUnitsMap.get(file), parentPath);
for (WorkUnitState wu : splitWorkUnitsMap.get(file)) {
// Set to committed so that task states will not fail
wu.setWorkingState(WorkUnitState.WorkingState.COMMITTED);
workUnits.remove(wu);
}
workUnits.add(newWorkUnit);
}
return workUnits;
} | [
"public",
"static",
"Collection",
"<",
"WorkUnitState",
">",
"mergeAllSplitWorkUnits",
"(",
"FileSystem",
"fs",
",",
"Collection",
"<",
"WorkUnitState",
">",
"workUnits",
")",
"throws",
"IOException",
"{",
"ListMultimap",
"<",
"CopyableFile",
",",
"WorkUnitState",
">",
"splitWorkUnitsMap",
"=",
"ArrayListMultimap",
".",
"create",
"(",
")",
";",
"for",
"(",
"WorkUnitState",
"workUnit",
":",
"workUnits",
")",
"{",
"if",
"(",
"isSplitWorkUnit",
"(",
"workUnit",
")",
")",
"{",
"CopyableFile",
"copyableFile",
"=",
"(",
"CopyableFile",
")",
"CopySource",
".",
"deserializeCopyEntity",
"(",
"workUnit",
")",
";",
"splitWorkUnitsMap",
".",
"put",
"(",
"copyableFile",
",",
"workUnit",
")",
";",
"}",
"}",
"for",
"(",
"CopyableFile",
"file",
":",
"splitWorkUnitsMap",
".",
"keySet",
"(",
")",
")",
"{",
"log",
".",
"info",
"(",
"String",
".",
"format",
"(",
"\"Merging split file %s.\"",
",",
"file",
".",
"getDestination",
"(",
")",
")",
")",
";",
"WorkUnitState",
"oldWorkUnit",
"=",
"splitWorkUnitsMap",
".",
"get",
"(",
"file",
")",
".",
"get",
"(",
"0",
")",
";",
"Path",
"outputDir",
"=",
"FileAwareInputStreamDataWriter",
".",
"getOutputDir",
"(",
"oldWorkUnit",
")",
";",
"CopyEntity",
".",
"DatasetAndPartition",
"datasetAndPartition",
"=",
"file",
".",
"getDatasetAndPartition",
"(",
"CopySource",
".",
"deserializeCopyableDataset",
"(",
"oldWorkUnit",
")",
")",
";",
"Path",
"parentPath",
"=",
"FileAwareInputStreamDataWriter",
".",
"getOutputFilePath",
"(",
"file",
",",
"outputDir",
",",
"datasetAndPartition",
")",
".",
"getParent",
"(",
")",
";",
"WorkUnitState",
"newWorkUnit",
"=",
"mergeSplits",
"(",
"fs",
",",
"file",
",",
"splitWorkUnitsMap",
".",
"get",
"(",
"file",
")",
",",
"parentPath",
")",
";",
"for",
"(",
"WorkUnitState",
"wu",
":",
"splitWorkUnitsMap",
".",
"get",
"(",
"file",
")",
")",
"{",
"// Set to committed so that task states will not fail",
"wu",
".",
"setWorkingState",
"(",
"WorkUnitState",
".",
"WorkingState",
".",
"COMMITTED",
")",
";",
"workUnits",
".",
"remove",
"(",
"wu",
")",
";",
"}",
"workUnits",
".",
"add",
"(",
"newWorkUnit",
")",
";",
"}",
"return",
"workUnits",
";",
"}"
] | Finds all split work units in the input collection and merges the file parts into the expected output files.
@param fs {@link FileSystem} where file parts exist.
@param workUnits Collection of {@link WorkUnitState}s possibly containing split work units.
@return The collection of {@link WorkUnitState}s where split work units for each file have been merged.
@throws IOException | [
"Finds",
"all",
"split",
"work",
"units",
"in",
"the",
"input",
"collection",
"and",
"merges",
"the",
"file",
"parts",
"into",
"the",
"expected",
"output",
"files",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/splitter/DistcpFileSplitter.java#L144-L174 |
25,681 | apache/incubator-gobblin | gobblin-yarn/src/main/java/org/apache/gobblin/yarn/YarnService.java | YarnService.shouldStickToTheSameNode | private boolean shouldStickToTheSameNode(int containerExitStatus) {
switch (containerExitStatus) {
case ContainerExitStatus.DISKS_FAILED:
return false;
case ContainerExitStatus.ABORTED:
// Mostly likely this exit status is due to node failures because the
// application itself will not release containers.
return false;
default:
// Stick to the same node for other cases if host affinity is enabled.
return this.containerHostAffinityEnabled;
}
} | java | private boolean shouldStickToTheSameNode(int containerExitStatus) {
switch (containerExitStatus) {
case ContainerExitStatus.DISKS_FAILED:
return false;
case ContainerExitStatus.ABORTED:
// Mostly likely this exit status is due to node failures because the
// application itself will not release containers.
return false;
default:
// Stick to the same node for other cases if host affinity is enabled.
return this.containerHostAffinityEnabled;
}
} | [
"private",
"boolean",
"shouldStickToTheSameNode",
"(",
"int",
"containerExitStatus",
")",
"{",
"switch",
"(",
"containerExitStatus",
")",
"{",
"case",
"ContainerExitStatus",
".",
"DISKS_FAILED",
":",
"return",
"false",
";",
"case",
"ContainerExitStatus",
".",
"ABORTED",
":",
"// Mostly likely this exit status is due to node failures because the",
"// application itself will not release containers.",
"return",
"false",
";",
"default",
":",
"// Stick to the same node for other cases if host affinity is enabled.",
"return",
"this",
".",
"containerHostAffinityEnabled",
";",
"}",
"}"
] | Check the exit status of a completed container and see if the replacement container
should try to be started on the same node. Some exit status indicates a disk or
node failure and in such cases the replacement container should try to be started on
a different node. | [
"Check",
"the",
"exit",
"status",
"of",
"a",
"completed",
"container",
"and",
"see",
"if",
"the",
"replacement",
"container",
"should",
"try",
"to",
"be",
"started",
"on",
"the",
"same",
"node",
".",
"Some",
"exit",
"status",
"indicates",
"a",
"disk",
"or",
"node",
"failure",
"and",
"in",
"such",
"cases",
"the",
"replacement",
"container",
"should",
"try",
"to",
"be",
"started",
"on",
"a",
"different",
"node",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-yarn/src/main/java/org/apache/gobblin/yarn/YarnService.java#L434-L446 |
25,682 | apache/incubator-gobblin | gobblin-yarn/src/main/java/org/apache/gobblin/yarn/YarnService.java | YarnService.handleContainerCompletion | private void handleContainerCompletion(ContainerStatus containerStatus) {
Map.Entry<Container, String> completedContainerEntry = this.containerMap.remove(containerStatus.getContainerId());
String completedInstanceName = completedContainerEntry.getValue();
LOGGER.info(String.format("Container %s running Helix instance %s has completed with exit status %d",
containerStatus.getContainerId(), completedInstanceName, containerStatus.getExitStatus()));
if (!Strings.isNullOrEmpty(containerStatus.getDiagnostics())) {
LOGGER.info(String.format("Received the following diagnostics information for container %s: %s",
containerStatus.getContainerId(), containerStatus.getDiagnostics()));
}
if (this.shutdownInProgress) {
return;
}
this.helixInstanceRetryCount.putIfAbsent(completedInstanceName, new AtomicInteger(0));
int retryCount =
this.helixInstanceRetryCount.get(completedInstanceName).incrementAndGet();
// Populate event metadata
Optional<ImmutableMap.Builder<String, String>> eventMetadataBuilder = Optional.absent();
if (this.eventSubmitter.isPresent()) {
eventMetadataBuilder = Optional.of(buildContainerStatusEventMetadata(containerStatus));
eventMetadataBuilder.get().put(GobblinYarnEventConstants.EventMetadata.HELIX_INSTANCE_ID, completedInstanceName);
eventMetadataBuilder.get().put(GobblinYarnEventConstants.EventMetadata.CONTAINER_STATUS_RETRY_ATTEMPT, retryCount + "");
}
if (this.helixInstanceMaxRetries > 0 && retryCount > this.helixInstanceMaxRetries) {
if (this.eventSubmitter.isPresent()) {
this.eventSubmitter.get().submit(GobblinYarnEventConstants.EventNames.HELIX_INSTANCE_COMPLETION,
eventMetadataBuilder.get().build());
}
LOGGER.warn("Maximum number of retries has been achieved for Helix instance " + completedInstanceName);
return;
}
// Add the Helix instance name of the completed container to the queue of unused
// instance names so they can be reused by a replacement container.
this.unusedHelixInstanceNames.offer(completedInstanceName);
if (this.eventSubmitter.isPresent()) {
this.eventSubmitter.get().submit(GobblinYarnEventConstants.EventNames.HELIX_INSTANCE_COMPLETION,
eventMetadataBuilder.get().build());
}
LOGGER.info(String.format("Requesting a new container to replace %s to run Helix instance %s",
containerStatus.getContainerId(), completedInstanceName));
this.eventBus.post(new NewContainerRequest(
shouldStickToTheSameNode(containerStatus.getExitStatus()) ?
Optional.of(completedContainerEntry.getKey()) : Optional.<Container>absent()));
} | java | private void handleContainerCompletion(ContainerStatus containerStatus) {
Map.Entry<Container, String> completedContainerEntry = this.containerMap.remove(containerStatus.getContainerId());
String completedInstanceName = completedContainerEntry.getValue();
LOGGER.info(String.format("Container %s running Helix instance %s has completed with exit status %d",
containerStatus.getContainerId(), completedInstanceName, containerStatus.getExitStatus()));
if (!Strings.isNullOrEmpty(containerStatus.getDiagnostics())) {
LOGGER.info(String.format("Received the following diagnostics information for container %s: %s",
containerStatus.getContainerId(), containerStatus.getDiagnostics()));
}
if (this.shutdownInProgress) {
return;
}
this.helixInstanceRetryCount.putIfAbsent(completedInstanceName, new AtomicInteger(0));
int retryCount =
this.helixInstanceRetryCount.get(completedInstanceName).incrementAndGet();
// Populate event metadata
Optional<ImmutableMap.Builder<String, String>> eventMetadataBuilder = Optional.absent();
if (this.eventSubmitter.isPresent()) {
eventMetadataBuilder = Optional.of(buildContainerStatusEventMetadata(containerStatus));
eventMetadataBuilder.get().put(GobblinYarnEventConstants.EventMetadata.HELIX_INSTANCE_ID, completedInstanceName);
eventMetadataBuilder.get().put(GobblinYarnEventConstants.EventMetadata.CONTAINER_STATUS_RETRY_ATTEMPT, retryCount + "");
}
if (this.helixInstanceMaxRetries > 0 && retryCount > this.helixInstanceMaxRetries) {
if (this.eventSubmitter.isPresent()) {
this.eventSubmitter.get().submit(GobblinYarnEventConstants.EventNames.HELIX_INSTANCE_COMPLETION,
eventMetadataBuilder.get().build());
}
LOGGER.warn("Maximum number of retries has been achieved for Helix instance " + completedInstanceName);
return;
}
// Add the Helix instance name of the completed container to the queue of unused
// instance names so they can be reused by a replacement container.
this.unusedHelixInstanceNames.offer(completedInstanceName);
if (this.eventSubmitter.isPresent()) {
this.eventSubmitter.get().submit(GobblinYarnEventConstants.EventNames.HELIX_INSTANCE_COMPLETION,
eventMetadataBuilder.get().build());
}
LOGGER.info(String.format("Requesting a new container to replace %s to run Helix instance %s",
containerStatus.getContainerId(), completedInstanceName));
this.eventBus.post(new NewContainerRequest(
shouldStickToTheSameNode(containerStatus.getExitStatus()) ?
Optional.of(completedContainerEntry.getKey()) : Optional.<Container>absent()));
} | [
"private",
"void",
"handleContainerCompletion",
"(",
"ContainerStatus",
"containerStatus",
")",
"{",
"Map",
".",
"Entry",
"<",
"Container",
",",
"String",
">",
"completedContainerEntry",
"=",
"this",
".",
"containerMap",
".",
"remove",
"(",
"containerStatus",
".",
"getContainerId",
"(",
")",
")",
";",
"String",
"completedInstanceName",
"=",
"completedContainerEntry",
".",
"getValue",
"(",
")",
";",
"LOGGER",
".",
"info",
"(",
"String",
".",
"format",
"(",
"\"Container %s running Helix instance %s has completed with exit status %d\"",
",",
"containerStatus",
".",
"getContainerId",
"(",
")",
",",
"completedInstanceName",
",",
"containerStatus",
".",
"getExitStatus",
"(",
")",
")",
")",
";",
"if",
"(",
"!",
"Strings",
".",
"isNullOrEmpty",
"(",
"containerStatus",
".",
"getDiagnostics",
"(",
")",
")",
")",
"{",
"LOGGER",
".",
"info",
"(",
"String",
".",
"format",
"(",
"\"Received the following diagnostics information for container %s: %s\"",
",",
"containerStatus",
".",
"getContainerId",
"(",
")",
",",
"containerStatus",
".",
"getDiagnostics",
"(",
")",
")",
")",
";",
"}",
"if",
"(",
"this",
".",
"shutdownInProgress",
")",
"{",
"return",
";",
"}",
"this",
".",
"helixInstanceRetryCount",
".",
"putIfAbsent",
"(",
"completedInstanceName",
",",
"new",
"AtomicInteger",
"(",
"0",
")",
")",
";",
"int",
"retryCount",
"=",
"this",
".",
"helixInstanceRetryCount",
".",
"get",
"(",
"completedInstanceName",
")",
".",
"incrementAndGet",
"(",
")",
";",
"// Populate event metadata",
"Optional",
"<",
"ImmutableMap",
".",
"Builder",
"<",
"String",
",",
"String",
">",
">",
"eventMetadataBuilder",
"=",
"Optional",
".",
"absent",
"(",
")",
";",
"if",
"(",
"this",
".",
"eventSubmitter",
".",
"isPresent",
"(",
")",
")",
"{",
"eventMetadataBuilder",
"=",
"Optional",
".",
"of",
"(",
"buildContainerStatusEventMetadata",
"(",
"containerStatus",
")",
")",
";",
"eventMetadataBuilder",
".",
"get",
"(",
")",
".",
"put",
"(",
"GobblinYarnEventConstants",
".",
"EventMetadata",
".",
"HELIX_INSTANCE_ID",
",",
"completedInstanceName",
")",
";",
"eventMetadataBuilder",
".",
"get",
"(",
")",
".",
"put",
"(",
"GobblinYarnEventConstants",
".",
"EventMetadata",
".",
"CONTAINER_STATUS_RETRY_ATTEMPT",
",",
"retryCount",
"+",
"\"\"",
")",
";",
"}",
"if",
"(",
"this",
".",
"helixInstanceMaxRetries",
">",
"0",
"&&",
"retryCount",
">",
"this",
".",
"helixInstanceMaxRetries",
")",
"{",
"if",
"(",
"this",
".",
"eventSubmitter",
".",
"isPresent",
"(",
")",
")",
"{",
"this",
".",
"eventSubmitter",
".",
"get",
"(",
")",
".",
"submit",
"(",
"GobblinYarnEventConstants",
".",
"EventNames",
".",
"HELIX_INSTANCE_COMPLETION",
",",
"eventMetadataBuilder",
".",
"get",
"(",
")",
".",
"build",
"(",
")",
")",
";",
"}",
"LOGGER",
".",
"warn",
"(",
"\"Maximum number of retries has been achieved for Helix instance \"",
"+",
"completedInstanceName",
")",
";",
"return",
";",
"}",
"// Add the Helix instance name of the completed container to the queue of unused",
"// instance names so they can be reused by a replacement container.",
"this",
".",
"unusedHelixInstanceNames",
".",
"offer",
"(",
"completedInstanceName",
")",
";",
"if",
"(",
"this",
".",
"eventSubmitter",
".",
"isPresent",
"(",
")",
")",
"{",
"this",
".",
"eventSubmitter",
".",
"get",
"(",
")",
".",
"submit",
"(",
"GobblinYarnEventConstants",
".",
"EventNames",
".",
"HELIX_INSTANCE_COMPLETION",
",",
"eventMetadataBuilder",
".",
"get",
"(",
")",
".",
"build",
"(",
")",
")",
";",
"}",
"LOGGER",
".",
"info",
"(",
"String",
".",
"format",
"(",
"\"Requesting a new container to replace %s to run Helix instance %s\"",
",",
"containerStatus",
".",
"getContainerId",
"(",
")",
",",
"completedInstanceName",
")",
")",
";",
"this",
".",
"eventBus",
".",
"post",
"(",
"new",
"NewContainerRequest",
"(",
"shouldStickToTheSameNode",
"(",
"containerStatus",
".",
"getExitStatus",
"(",
")",
")",
"?",
"Optional",
".",
"of",
"(",
"completedContainerEntry",
".",
"getKey",
"(",
")",
")",
":",
"Optional",
".",
"<",
"Container",
">",
"absent",
"(",
")",
")",
")",
";",
"}"
] | Handle the completion of a container. A new container will be requested to replace the one
that just exited. Depending on the exit status and if container host affinity is enabled,
the new container may or may not try to be started on the same node.
A container completes in either of the following conditions: 1) some error happens in the
container and caused the container to exit, 2) the container gets killed due to some reason,
for example, if it runs over the allowed amount of virtual or physical memory, 3) the gets
preempted by the ResourceManager, or 4) the container gets stopped by the ApplicationMaster.
A replacement container is needed in all but the last case. | [
"Handle",
"the",
"completion",
"of",
"a",
"container",
".",
"A",
"new",
"container",
"will",
"be",
"requested",
"to",
"replace",
"the",
"one",
"that",
"just",
"exited",
".",
"Depending",
"on",
"the",
"exit",
"status",
"and",
"if",
"container",
"host",
"affinity",
"is",
"enabled",
"the",
"new",
"container",
"may",
"or",
"may",
"not",
"try",
"to",
"be",
"started",
"on",
"the",
"same",
"node",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-yarn/src/main/java/org/apache/gobblin/yarn/YarnService.java#L459-L511 |
25,683 | apache/incubator-gobblin | gobblin-runtime/src/main/java/org/apache/gobblin/runtime/api/JobSpec.java | JobSpec.builder | public static Builder builder(URI catalogURI, Properties jobProps) {
String name = JobState.getJobNameFromProps(jobProps);
String group = JobState.getJobGroupFromProps(jobProps);
if (null == group) {
group = "default";
}
try {
URI jobURI = new URI(catalogURI.getScheme(), catalogURI.getAuthority(),
"/" + group + "/" + name, null);
Builder builder = new Builder(jobURI).withConfigAsProperties(jobProps);
String descr = JobState.getJobDescriptionFromProps(jobProps);
if (null != descr) {
builder.withDescription(descr);
}
return builder;
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to create a JobSpec URI: " + e, e);
}
} | java | public static Builder builder(URI catalogURI, Properties jobProps) {
String name = JobState.getJobNameFromProps(jobProps);
String group = JobState.getJobGroupFromProps(jobProps);
if (null == group) {
group = "default";
}
try {
URI jobURI = new URI(catalogURI.getScheme(), catalogURI.getAuthority(),
"/" + group + "/" + name, null);
Builder builder = new Builder(jobURI).withConfigAsProperties(jobProps);
String descr = JobState.getJobDescriptionFromProps(jobProps);
if (null != descr) {
builder.withDescription(descr);
}
return builder;
} catch (URISyntaxException e) {
throw new RuntimeException("Unable to create a JobSpec URI: " + e, e);
}
} | [
"public",
"static",
"Builder",
"builder",
"(",
"URI",
"catalogURI",
",",
"Properties",
"jobProps",
")",
"{",
"String",
"name",
"=",
"JobState",
".",
"getJobNameFromProps",
"(",
"jobProps",
")",
";",
"String",
"group",
"=",
"JobState",
".",
"getJobGroupFromProps",
"(",
"jobProps",
")",
";",
"if",
"(",
"null",
"==",
"group",
")",
"{",
"group",
"=",
"\"default\"",
";",
"}",
"try",
"{",
"URI",
"jobURI",
"=",
"new",
"URI",
"(",
"catalogURI",
".",
"getScheme",
"(",
")",
",",
"catalogURI",
".",
"getAuthority",
"(",
")",
",",
"\"/\"",
"+",
"group",
"+",
"\"/\"",
"+",
"name",
",",
"null",
")",
";",
"Builder",
"builder",
"=",
"new",
"Builder",
"(",
"jobURI",
")",
".",
"withConfigAsProperties",
"(",
"jobProps",
")",
";",
"String",
"descr",
"=",
"JobState",
".",
"getJobDescriptionFromProps",
"(",
"jobProps",
")",
";",
"if",
"(",
"null",
"!=",
"descr",
")",
"{",
"builder",
".",
"withDescription",
"(",
"descr",
")",
";",
"}",
"return",
"builder",
";",
"}",
"catch",
"(",
"URISyntaxException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Unable to create a JobSpec URI: \"",
"+",
"e",
",",
"e",
")",
";",
"}",
"}"
] | Creates a builder for the JobSpec based on values in a job properties config. | [
"Creates",
"a",
"builder",
"for",
"the",
"JobSpec",
"based",
"on",
"values",
"in",
"a",
"job",
"properties",
"config",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/api/JobSpec.java#L90-L109 |
25,684 | apache/incubator-gobblin | gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/MetricContext.java | MetricContext.sendNotification | public void sendNotification(final Notification notification) {
ContextAwareTimer.Context timer = this.notificationTimer.time();
if(!this.notificationTargets.isEmpty()) {
for (final Map.Entry<UUID, Function<Notification, Void>> entry : this.notificationTargets.entrySet()) {
try {
entry.getValue().apply(notification);
} catch (RuntimeException exception) {
LOG.warn("RuntimeException when running notification target. Skipping.", exception);
}
}
}
if(getParent().isPresent()) {
getParent().get().sendNotification(notification);
}
timer.stop();
} | java | public void sendNotification(final Notification notification) {
ContextAwareTimer.Context timer = this.notificationTimer.time();
if(!this.notificationTargets.isEmpty()) {
for (final Map.Entry<UUID, Function<Notification, Void>> entry : this.notificationTargets.entrySet()) {
try {
entry.getValue().apply(notification);
} catch (RuntimeException exception) {
LOG.warn("RuntimeException when running notification target. Skipping.", exception);
}
}
}
if(getParent().isPresent()) {
getParent().get().sendNotification(notification);
}
timer.stop();
} | [
"public",
"void",
"sendNotification",
"(",
"final",
"Notification",
"notification",
")",
"{",
"ContextAwareTimer",
".",
"Context",
"timer",
"=",
"this",
".",
"notificationTimer",
".",
"time",
"(",
")",
";",
"if",
"(",
"!",
"this",
".",
"notificationTargets",
".",
"isEmpty",
"(",
")",
")",
"{",
"for",
"(",
"final",
"Map",
".",
"Entry",
"<",
"UUID",
",",
"Function",
"<",
"Notification",
",",
"Void",
">",
">",
"entry",
":",
"this",
".",
"notificationTargets",
".",
"entrySet",
"(",
")",
")",
"{",
"try",
"{",
"entry",
".",
"getValue",
"(",
")",
".",
"apply",
"(",
"notification",
")",
";",
"}",
"catch",
"(",
"RuntimeException",
"exception",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"RuntimeException when running notification target. Skipping.\"",
",",
"exception",
")",
";",
"}",
"}",
"}",
"if",
"(",
"getParent",
"(",
")",
".",
"isPresent",
"(",
")",
")",
"{",
"getParent",
"(",
")",
".",
"get",
"(",
")",
".",
"sendNotification",
"(",
"notification",
")",
";",
"}",
"timer",
".",
"stop",
"(",
")",
";",
"}"
] | Send a notification to all targets of this context and to the parent of this context.
@param notification {@link org.apache.gobblin.metrics.notification.Notification} to send. | [
"Send",
"a",
"notification",
"to",
"all",
"targets",
"of",
"this",
"context",
"and",
"to",
"the",
"parent",
"of",
"this",
"context",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-metrics-libs/gobblin-metrics-base/src/main/java/org/apache/gobblin/metrics/MetricContext.java#L605-L622 |
25,685 | apache/incubator-gobblin | gobblin-compaction/src/main/java/org/apache/gobblin/compaction/mapreduce/orc/OrcKeyCompactorOutputFormat.java | OrcKeyCompactorOutputFormat.getRecordWriter | @Override
public RecordWriter getRecordWriter(TaskAttemptContext taskAttemptContext) throws IOException {
Configuration conf = taskAttemptContext.getConfiguration();
String extension = "." + conf.get(COMPACTION_OUTPUT_EXTENSION, "orc" );
Path filename = getDefaultWorkFile(taskAttemptContext, extension);
Writer writer = OrcFile.createWriter(filename,
org.apache.orc.mapred.OrcOutputFormat.buildOptions(conf));
return new OrcMapreduceRecordWriter(writer);
} | java | @Override
public RecordWriter getRecordWriter(TaskAttemptContext taskAttemptContext) throws IOException {
Configuration conf = taskAttemptContext.getConfiguration();
String extension = "." + conf.get(COMPACTION_OUTPUT_EXTENSION, "orc" );
Path filename = getDefaultWorkFile(taskAttemptContext, extension);
Writer writer = OrcFile.createWriter(filename,
org.apache.orc.mapred.OrcOutputFormat.buildOptions(conf));
return new OrcMapreduceRecordWriter(writer);
} | [
"@",
"Override",
"public",
"RecordWriter",
"getRecordWriter",
"(",
"TaskAttemptContext",
"taskAttemptContext",
")",
"throws",
"IOException",
"{",
"Configuration",
"conf",
"=",
"taskAttemptContext",
".",
"getConfiguration",
"(",
")",
";",
"String",
"extension",
"=",
"\".\"",
"+",
"conf",
".",
"get",
"(",
"COMPACTION_OUTPUT_EXTENSION",
",",
"\"orc\"",
")",
";",
"Path",
"filename",
"=",
"getDefaultWorkFile",
"(",
"taskAttemptContext",
",",
"extension",
")",
";",
"Writer",
"writer",
"=",
"OrcFile",
".",
"createWriter",
"(",
"filename",
",",
"org",
".",
"apache",
".",
"orc",
".",
"mapred",
".",
"OrcOutputFormat",
".",
"buildOptions",
"(",
"conf",
")",
")",
";",
"return",
"new",
"OrcMapreduceRecordWriter",
"(",
"writer",
")",
";",
"}"
] | Required for extension since super method hard-coded file extension as ".orc". To keep flexibility
of extension name, we made it configuration driven.
@param taskAttemptContext The source of configuration that determines the file extension
@return The {@link RecordWriter} that write out Orc object.
@throws IOException | [
"Required",
"for",
"extension",
"since",
"super",
"method",
"hard",
"-",
"coded",
"file",
"extension",
"as",
".",
"orc",
".",
"To",
"keep",
"flexibility",
"of",
"extension",
"name",
"we",
"made",
"it",
"configuration",
"driven",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-compaction/src/main/java/org/apache/gobblin/compaction/mapreduce/orc/OrcKeyCompactorOutputFormat.java#L60-L69 |
25,686 | apache/incubator-gobblin | gobblin-runtime/src/main/java/org/apache/gobblin/runtime/locks/FileBasedJobLockFactory.java | FileBasedJobLockFactory.create | public static FileBasedJobLockFactory create(Config factoryConfig,
Configuration hadoopConf,
Optional<Logger> log)
throws IOException {
FileSystem fs = factoryConfig.hasPath(FS_URI_CONFIG) ?
FileSystem.get(URI.create(factoryConfig.getString(FS_URI_CONFIG)), hadoopConf) :
getDefaultFileSystem(hadoopConf);
String lockFilesDir = factoryConfig.hasPath(LOCK_DIR_CONFIG) ?
factoryConfig.getString(LOCK_DIR_CONFIG) :
getDefaultLockDir(fs, log);
return new FileBasedJobLockFactory(fs, lockFilesDir, log);
} | java | public static FileBasedJobLockFactory create(Config factoryConfig,
Configuration hadoopConf,
Optional<Logger> log)
throws IOException {
FileSystem fs = factoryConfig.hasPath(FS_URI_CONFIG) ?
FileSystem.get(URI.create(factoryConfig.getString(FS_URI_CONFIG)), hadoopConf) :
getDefaultFileSystem(hadoopConf);
String lockFilesDir = factoryConfig.hasPath(LOCK_DIR_CONFIG) ?
factoryConfig.getString(LOCK_DIR_CONFIG) :
getDefaultLockDir(fs, log);
return new FileBasedJobLockFactory(fs, lockFilesDir, log);
} | [
"public",
"static",
"FileBasedJobLockFactory",
"create",
"(",
"Config",
"factoryConfig",
",",
"Configuration",
"hadoopConf",
",",
"Optional",
"<",
"Logger",
">",
"log",
")",
"throws",
"IOException",
"{",
"FileSystem",
"fs",
"=",
"factoryConfig",
".",
"hasPath",
"(",
"FS_URI_CONFIG",
")",
"?",
"FileSystem",
".",
"get",
"(",
"URI",
".",
"create",
"(",
"factoryConfig",
".",
"getString",
"(",
"FS_URI_CONFIG",
")",
")",
",",
"hadoopConf",
")",
":",
"getDefaultFileSystem",
"(",
"hadoopConf",
")",
";",
"String",
"lockFilesDir",
"=",
"factoryConfig",
".",
"hasPath",
"(",
"LOCK_DIR_CONFIG",
")",
"?",
"factoryConfig",
".",
"getString",
"(",
"LOCK_DIR_CONFIG",
")",
":",
"getDefaultLockDir",
"(",
"fs",
",",
"log",
")",
";",
"return",
"new",
"FileBasedJobLockFactory",
"(",
"fs",
",",
"lockFilesDir",
",",
"log",
")",
";",
"}"
] | Create a new instance using the specified factory and hadoop configurations. | [
"Create",
"a",
"new",
"instance",
"using",
"the",
"specified",
"factory",
"and",
"hadoop",
"configurations",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/locks/FileBasedJobLockFactory.java#L85-L96 |
25,687 | apache/incubator-gobblin | gobblin-runtime/src/main/java/org/apache/gobblin/runtime/locks/FileBasedJobLockFactory.java | FileBasedJobLockFactory.isLocked | boolean isLocked(Path lockFile) throws JobLockException {
try {
return this.fs.exists(lockFile);
} catch (IOException e) {
throw new JobLockException(e);
}
} | java | boolean isLocked(Path lockFile) throws JobLockException {
try {
return this.fs.exists(lockFile);
} catch (IOException e) {
throw new JobLockException(e);
}
} | [
"boolean",
"isLocked",
"(",
"Path",
"lockFile",
")",
"throws",
"JobLockException",
"{",
"try",
"{",
"return",
"this",
".",
"fs",
".",
"exists",
"(",
"lockFile",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"JobLockException",
"(",
"e",
")",
";",
"}",
"}"
] | Check if the lock is locked.
@return if the lock is locked
@throws JobLockException thrown if checking the status of the {@link JobLock} fails | [
"Check",
"if",
"the",
"lock",
"is",
"locked",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/locks/FileBasedJobLockFactory.java#L189-L195 |
25,688 | apache/incubator-gobblin | gobblin-api/src/main/java/org/apache/gobblin/util/RecordCountProvider.java | RecordCountProvider.getRecordCount | public long getRecordCount(Collection<Path> paths) {
long count = 0;
for (Path path : paths) {
count += getRecordCount(path);
}
return count;
} | java | public long getRecordCount(Collection<Path> paths) {
long count = 0;
for (Path path : paths) {
count += getRecordCount(path);
}
return count;
} | [
"public",
"long",
"getRecordCount",
"(",
"Collection",
"<",
"Path",
">",
"paths",
")",
"{",
"long",
"count",
"=",
"0",
";",
"for",
"(",
"Path",
"path",
":",
"paths",
")",
"{",
"count",
"+=",
"getRecordCount",
"(",
"path",
")",
";",
"}",
"return",
"count",
";",
"}"
] | Get record count for a list of paths. | [
"Get",
"record",
"count",
"for",
"a",
"list",
"of",
"paths",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-api/src/main/java/org/apache/gobblin/util/RecordCountProvider.java#L55-L61 |
25,689 | apache/incubator-gobblin | gobblin-aws/src/main/java/org/apache/gobblin/aws/GobblinAWSClusterLauncher.java | GobblinAWSClusterLauncher.launch | public void launch() throws IOException, InterruptedException {
this.eventBus.register(this);
// Create Helix cluster and connect to it
HelixUtils.createGobblinHelixCluster(this.zkConnectionString, this.helixClusterName, false);
LOGGER.info("Created Helix cluster " + this.helixClusterName);
connectHelixManager();
// Core logic to launch cluster
this.clusterId = getClusterId();
// TODO: Add cluster monitoring
countDownLatch.await();
} | java | public void launch() throws IOException, InterruptedException {
this.eventBus.register(this);
// Create Helix cluster and connect to it
HelixUtils.createGobblinHelixCluster(this.zkConnectionString, this.helixClusterName, false);
LOGGER.info("Created Helix cluster " + this.helixClusterName);
connectHelixManager();
// Core logic to launch cluster
this.clusterId = getClusterId();
// TODO: Add cluster monitoring
countDownLatch.await();
} | [
"public",
"void",
"launch",
"(",
")",
"throws",
"IOException",
",",
"InterruptedException",
"{",
"this",
".",
"eventBus",
".",
"register",
"(",
"this",
")",
";",
"// Create Helix cluster and connect to it",
"HelixUtils",
".",
"createGobblinHelixCluster",
"(",
"this",
".",
"zkConnectionString",
",",
"this",
".",
"helixClusterName",
",",
"false",
")",
";",
"LOGGER",
".",
"info",
"(",
"\"Created Helix cluster \"",
"+",
"this",
".",
"helixClusterName",
")",
";",
"connectHelixManager",
"(",
")",
";",
"// Core logic to launch cluster",
"this",
".",
"clusterId",
"=",
"getClusterId",
"(",
")",
";",
"// TODO: Add cluster monitoring",
"countDownLatch",
".",
"await",
"(",
")",
";",
"}"
] | Launch a new Gobblin cluster on AWS.
@throws IOException If there's something wrong launching the cluster | [
"Launch",
"a",
"new",
"Gobblin",
"cluster",
"on",
"AWS",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-aws/src/main/java/org/apache/gobblin/aws/GobblinAWSClusterLauncher.java#L256-L270 |
25,690 | apache/incubator-gobblin | gobblin-modules/gobblin-http/src/main/java/org/apache/gobblin/converter/AvroHttpJoinConverter.java | AvroHttpJoinConverter.generateHttpOperation | @Override
protected HttpOperation generateHttpOperation (GenericRecord inputRecord, State state) {
Map<String, String> keyAndValue = new HashMap<>();
Optional<Iterable<String>> keys = getKeys(state);
HttpOperation operation;
if (keys.isPresent()) {
for (String key : keys.get()) {
String value = inputRecord.get(key).toString();
log.debug("Http join converter: key is {}, value is {}", key, value);
keyAndValue.put(key, value);
}
operation = new HttpOperation();
operation.setKeys(keyAndValue);
} else {
operation = HttpUtils.toHttpOperation(inputRecord);
}
return operation;
} | java | @Override
protected HttpOperation generateHttpOperation (GenericRecord inputRecord, State state) {
Map<String, String> keyAndValue = new HashMap<>();
Optional<Iterable<String>> keys = getKeys(state);
HttpOperation operation;
if (keys.isPresent()) {
for (String key : keys.get()) {
String value = inputRecord.get(key).toString();
log.debug("Http join converter: key is {}, value is {}", key, value);
keyAndValue.put(key, value);
}
operation = new HttpOperation();
operation.setKeys(keyAndValue);
} else {
operation = HttpUtils.toHttpOperation(inputRecord);
}
return operation;
} | [
"@",
"Override",
"protected",
"HttpOperation",
"generateHttpOperation",
"(",
"GenericRecord",
"inputRecord",
",",
"State",
"state",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"keyAndValue",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"Optional",
"<",
"Iterable",
"<",
"String",
">",
">",
"keys",
"=",
"getKeys",
"(",
"state",
")",
";",
"HttpOperation",
"operation",
";",
"if",
"(",
"keys",
".",
"isPresent",
"(",
")",
")",
"{",
"for",
"(",
"String",
"key",
":",
"keys",
".",
"get",
"(",
")",
")",
"{",
"String",
"value",
"=",
"inputRecord",
".",
"get",
"(",
"key",
")",
".",
"toString",
"(",
")",
";",
"log",
".",
"debug",
"(",
"\"Http join converter: key is {}, value is {}\"",
",",
"key",
",",
"value",
")",
";",
"keyAndValue",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"}",
"operation",
"=",
"new",
"HttpOperation",
"(",
")",
";",
"operation",
".",
"setKeys",
"(",
"keyAndValue",
")",
";",
"}",
"else",
"{",
"operation",
"=",
"HttpUtils",
".",
"toHttpOperation",
"(",
"inputRecord",
")",
";",
"}",
"return",
"operation",
";",
"}"
] | Extract user defined keys by looking at "gobblin.converter.http.keys"
If keys are defined, extract key-value pair from inputRecord and set it to HttpOperation
If keys are not defined, generate HttpOperation by HttpUtils.toHttpOperation | [
"Extract",
"user",
"defined",
"keys",
"by",
"looking",
"at",
"gobblin",
".",
"converter",
".",
"http",
".",
"keys",
"If",
"keys",
"are",
"defined",
"extract",
"key",
"-",
"value",
"pair",
"from",
"inputRecord",
"and",
"set",
"it",
"to",
"HttpOperation",
"If",
"keys",
"are",
"not",
"defined",
"generate",
"HttpOperation",
"by",
"HttpUtils",
".",
"toHttpOperation"
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-http/src/main/java/org/apache/gobblin/converter/AvroHttpJoinConverter.java#L77-L95 |
25,691 | apache/incubator-gobblin | gobblin-cluster/src/main/java/org/apache/gobblin/cluster/GobblinClusterUtils.java | GobblinClusterUtils.getJobStateFilePath | public static Path getJobStateFilePath(boolean usingStateStore, Path appWorkPath, String jobId) {
final Path jobStateFilePath;
// the state store uses a path of the form workdir/_jobstate/job_id/job_id.job.state while old method stores the file
// in the app work dir.
if (usingStateStore) {
jobStateFilePath = new Path(appWorkPath, GobblinClusterConfigurationKeys.JOB_STATE_DIR_NAME
+ Path.SEPARATOR + jobId + Path.SEPARATOR + jobId + "."
+ AbstractJobLauncher.JOB_STATE_FILE_NAME);
} else {
jobStateFilePath = new Path(appWorkPath, jobId + "." + AbstractJobLauncher.JOB_STATE_FILE_NAME);
}
log.info("job state file path: " + jobStateFilePath);
return jobStateFilePath;
} | java | public static Path getJobStateFilePath(boolean usingStateStore, Path appWorkPath, String jobId) {
final Path jobStateFilePath;
// the state store uses a path of the form workdir/_jobstate/job_id/job_id.job.state while old method stores the file
// in the app work dir.
if (usingStateStore) {
jobStateFilePath = new Path(appWorkPath, GobblinClusterConfigurationKeys.JOB_STATE_DIR_NAME
+ Path.SEPARATOR + jobId + Path.SEPARATOR + jobId + "."
+ AbstractJobLauncher.JOB_STATE_FILE_NAME);
} else {
jobStateFilePath = new Path(appWorkPath, jobId + "." + AbstractJobLauncher.JOB_STATE_FILE_NAME);
}
log.info("job state file path: " + jobStateFilePath);
return jobStateFilePath;
} | [
"public",
"static",
"Path",
"getJobStateFilePath",
"(",
"boolean",
"usingStateStore",
",",
"Path",
"appWorkPath",
",",
"String",
"jobId",
")",
"{",
"final",
"Path",
"jobStateFilePath",
";",
"// the state store uses a path of the form workdir/_jobstate/job_id/job_id.job.state while old method stores the file",
"// in the app work dir.",
"if",
"(",
"usingStateStore",
")",
"{",
"jobStateFilePath",
"=",
"new",
"Path",
"(",
"appWorkPath",
",",
"GobblinClusterConfigurationKeys",
".",
"JOB_STATE_DIR_NAME",
"+",
"Path",
".",
"SEPARATOR",
"+",
"jobId",
"+",
"Path",
".",
"SEPARATOR",
"+",
"jobId",
"+",
"\".\"",
"+",
"AbstractJobLauncher",
".",
"JOB_STATE_FILE_NAME",
")",
";",
"}",
"else",
"{",
"jobStateFilePath",
"=",
"new",
"Path",
"(",
"appWorkPath",
",",
"jobId",
"+",
"\".\"",
"+",
"AbstractJobLauncher",
".",
"JOB_STATE_FILE_NAME",
")",
";",
"}",
"log",
".",
"info",
"(",
"\"job state file path: \"",
"+",
"jobStateFilePath",
")",
";",
"return",
"jobStateFilePath",
";",
"}"
] | Generate the path to the job.state file
@param usingStateStore is a state store being used to store the job.state content
@param appWorkPath work directory
@param jobId job id
@return a {@link Path} referring to the job.state | [
"Generate",
"the",
"path",
"to",
"the",
"job",
".",
"state",
"file"
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-cluster/src/main/java/org/apache/gobblin/cluster/GobblinClusterUtils.java#L90-L107 |
25,692 | apache/incubator-gobblin | gobblin-core/src/main/java/org/apache/gobblin/publisher/BaseDataPublisher.java | BaseDataPublisher.loadExistingMetadata | private String loadExistingMetadata(Path metadataFilename, int branchId) {
try {
FileSystem fsForBranch = writerFileSystemByBranches.get(branchId);
if (!fsForBranch.exists(metadataFilename)) {
return null;
}
FSDataInputStream existingMetadata = writerFileSystemByBranches.get(branchId).open(metadataFilename);
return IOUtils.toString(existingMetadata, StandardCharsets.UTF_8);
} catch (IOException e) {
LOG.warn("IOException {} while trying to read existing metadata {} - treating as null", e.getMessage(),
metadataFilename.toString());
return null;
}
} | java | private String loadExistingMetadata(Path metadataFilename, int branchId) {
try {
FileSystem fsForBranch = writerFileSystemByBranches.get(branchId);
if (!fsForBranch.exists(metadataFilename)) {
return null;
}
FSDataInputStream existingMetadata = writerFileSystemByBranches.get(branchId).open(metadataFilename);
return IOUtils.toString(existingMetadata, StandardCharsets.UTF_8);
} catch (IOException e) {
LOG.warn("IOException {} while trying to read existing metadata {} - treating as null", e.getMessage(),
metadataFilename.toString());
return null;
}
} | [
"private",
"String",
"loadExistingMetadata",
"(",
"Path",
"metadataFilename",
",",
"int",
"branchId",
")",
"{",
"try",
"{",
"FileSystem",
"fsForBranch",
"=",
"writerFileSystemByBranches",
".",
"get",
"(",
"branchId",
")",
";",
"if",
"(",
"!",
"fsForBranch",
".",
"exists",
"(",
"metadataFilename",
")",
")",
"{",
"return",
"null",
";",
"}",
"FSDataInputStream",
"existingMetadata",
"=",
"writerFileSystemByBranches",
".",
"get",
"(",
"branchId",
")",
".",
"open",
"(",
"metadataFilename",
")",
";",
"return",
"IOUtils",
".",
"toString",
"(",
"existingMetadata",
",",
"StandardCharsets",
".",
"UTF_8",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"IOException {} while trying to read existing metadata {} - treating as null\"",
",",
"e",
".",
"getMessage",
"(",
")",
",",
"metadataFilename",
".",
"toString",
"(",
")",
")",
";",
"return",
"null",
";",
"}",
"}"
] | Read in existing metadata as a UTF8 string. | [
"Read",
"in",
"existing",
"metadata",
"as",
"a",
"UTF8",
"string",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/publisher/BaseDataPublisher.java#L265-L278 |
25,693 | apache/incubator-gobblin | gobblin-core/src/main/java/org/apache/gobblin/publisher/BaseDataPublisher.java | BaseDataPublisher.createDestinationDescriptor | protected DatasetDescriptor createDestinationDescriptor(WorkUnitState state, int branchId) {
Path publisherOutputDir = getPublisherOutputDir(state, branchId);
FileSystem fs = this.publisherFileSystemByBranches.get(branchId);
DatasetDescriptor destination = new DatasetDescriptor(fs.getScheme(), publisherOutputDir.toString());
destination.addMetadata(DatasetConstants.FS_URI, fs.getUri().toString());
destination.addMetadata(DatasetConstants.BRANCH, String.valueOf(branchId));
return destination;
} | java | protected DatasetDescriptor createDestinationDescriptor(WorkUnitState state, int branchId) {
Path publisherOutputDir = getPublisherOutputDir(state, branchId);
FileSystem fs = this.publisherFileSystemByBranches.get(branchId);
DatasetDescriptor destination = new DatasetDescriptor(fs.getScheme(), publisherOutputDir.toString());
destination.addMetadata(DatasetConstants.FS_URI, fs.getUri().toString());
destination.addMetadata(DatasetConstants.BRANCH, String.valueOf(branchId));
return destination;
} | [
"protected",
"DatasetDescriptor",
"createDestinationDescriptor",
"(",
"WorkUnitState",
"state",
",",
"int",
"branchId",
")",
"{",
"Path",
"publisherOutputDir",
"=",
"getPublisherOutputDir",
"(",
"state",
",",
"branchId",
")",
";",
"FileSystem",
"fs",
"=",
"this",
".",
"publisherFileSystemByBranches",
".",
"get",
"(",
"branchId",
")",
";",
"DatasetDescriptor",
"destination",
"=",
"new",
"DatasetDescriptor",
"(",
"fs",
".",
"getScheme",
"(",
")",
",",
"publisherOutputDir",
".",
"toString",
"(",
")",
")",
";",
"destination",
".",
"addMetadata",
"(",
"DatasetConstants",
".",
"FS_URI",
",",
"fs",
".",
"getUri",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"destination",
".",
"addMetadata",
"(",
"DatasetConstants",
".",
"BRANCH",
",",
"String",
".",
"valueOf",
"(",
"branchId",
")",
")",
";",
"return",
"destination",
";",
"}"
] | Create destination dataset descriptor | [
"Create",
"destination",
"dataset",
"descriptor"
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/publisher/BaseDataPublisher.java#L324-L331 |
25,694 | apache/incubator-gobblin | gobblin-core/src/main/java/org/apache/gobblin/publisher/BaseDataPublisher.java | BaseDataPublisher.publishMetadata | @Override
public void publishMetadata(Collection<? extends WorkUnitState> states)
throws IOException {
Set<String> partitions = new HashSet<>();
// There should be one merged metadata file per branch; first merge all of the pieces together
mergeMetadataAndCollectPartitionNames(states, partitions);
partitions.removeIf(Objects::isNull);
// Now, pick an arbitrary WorkUnitState to get config information around metadata such as
// the desired output filename. We assume that publisher config settings
// are the same across all workunits so it doesn't really matter which workUnit we retrieve this information
// from.
WorkUnitState anyState = states.iterator().next();
for (int branchId = 0; branchId < numBranches; branchId++) {
String mdOutputPath = getMetadataOutputPathFromState(anyState, branchId);
String userSpecifiedPath = getUserSpecifiedOutputPathFromState(anyState, branchId);
if (partitions.isEmpty() || userSpecifiedPath != null) {
publishMetadata(getMergedMetadataForPartitionAndBranch(null, branchId),
branchId,
getMetadataOutputFileForBranch(anyState, branchId));
} else {
String metadataFilename = getMetadataFileNameForBranch(anyState, branchId);
if (mdOutputPath == null || metadataFilename == null) {
LOG.info("Metadata filename not set for branch " + String.valueOf(branchId) + ": not publishing metadata.");
continue;
}
for (String partition : partitions) {
publishMetadata(getMergedMetadataForPartitionAndBranch(partition, branchId),
branchId,
new Path(new Path(mdOutputPath, partition), metadataFilename));
}
}
}
} | java | @Override
public void publishMetadata(Collection<? extends WorkUnitState> states)
throws IOException {
Set<String> partitions = new HashSet<>();
// There should be one merged metadata file per branch; first merge all of the pieces together
mergeMetadataAndCollectPartitionNames(states, partitions);
partitions.removeIf(Objects::isNull);
// Now, pick an arbitrary WorkUnitState to get config information around metadata such as
// the desired output filename. We assume that publisher config settings
// are the same across all workunits so it doesn't really matter which workUnit we retrieve this information
// from.
WorkUnitState anyState = states.iterator().next();
for (int branchId = 0; branchId < numBranches; branchId++) {
String mdOutputPath = getMetadataOutputPathFromState(anyState, branchId);
String userSpecifiedPath = getUserSpecifiedOutputPathFromState(anyState, branchId);
if (partitions.isEmpty() || userSpecifiedPath != null) {
publishMetadata(getMergedMetadataForPartitionAndBranch(null, branchId),
branchId,
getMetadataOutputFileForBranch(anyState, branchId));
} else {
String metadataFilename = getMetadataFileNameForBranch(anyState, branchId);
if (mdOutputPath == null || metadataFilename == null) {
LOG.info("Metadata filename not set for branch " + String.valueOf(branchId) + ": not publishing metadata.");
continue;
}
for (String partition : partitions) {
publishMetadata(getMergedMetadataForPartitionAndBranch(partition, branchId),
branchId,
new Path(new Path(mdOutputPath, partition), metadataFilename));
}
}
}
} | [
"@",
"Override",
"public",
"void",
"publishMetadata",
"(",
"Collection",
"<",
"?",
"extends",
"WorkUnitState",
">",
"states",
")",
"throws",
"IOException",
"{",
"Set",
"<",
"String",
">",
"partitions",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"// There should be one merged metadata file per branch; first merge all of the pieces together",
"mergeMetadataAndCollectPartitionNames",
"(",
"states",
",",
"partitions",
")",
";",
"partitions",
".",
"removeIf",
"(",
"Objects",
"::",
"isNull",
")",
";",
"// Now, pick an arbitrary WorkUnitState to get config information around metadata such as",
"// the desired output filename. We assume that publisher config settings",
"// are the same across all workunits so it doesn't really matter which workUnit we retrieve this information",
"// from.",
"WorkUnitState",
"anyState",
"=",
"states",
".",
"iterator",
"(",
")",
".",
"next",
"(",
")",
";",
"for",
"(",
"int",
"branchId",
"=",
"0",
";",
"branchId",
"<",
"numBranches",
";",
"branchId",
"++",
")",
"{",
"String",
"mdOutputPath",
"=",
"getMetadataOutputPathFromState",
"(",
"anyState",
",",
"branchId",
")",
";",
"String",
"userSpecifiedPath",
"=",
"getUserSpecifiedOutputPathFromState",
"(",
"anyState",
",",
"branchId",
")",
";",
"if",
"(",
"partitions",
".",
"isEmpty",
"(",
")",
"||",
"userSpecifiedPath",
"!=",
"null",
")",
"{",
"publishMetadata",
"(",
"getMergedMetadataForPartitionAndBranch",
"(",
"null",
",",
"branchId",
")",
",",
"branchId",
",",
"getMetadataOutputFileForBranch",
"(",
"anyState",
",",
"branchId",
")",
")",
";",
"}",
"else",
"{",
"String",
"metadataFilename",
"=",
"getMetadataFileNameForBranch",
"(",
"anyState",
",",
"branchId",
")",
";",
"if",
"(",
"mdOutputPath",
"==",
"null",
"||",
"metadataFilename",
"==",
"null",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Metadata filename not set for branch \"",
"+",
"String",
".",
"valueOf",
"(",
"branchId",
")",
"+",
"\": not publishing metadata.\"",
")",
";",
"continue",
";",
"}",
"for",
"(",
"String",
"partition",
":",
"partitions",
")",
"{",
"publishMetadata",
"(",
"getMergedMetadataForPartitionAndBranch",
"(",
"partition",
",",
"branchId",
")",
",",
"branchId",
",",
"new",
"Path",
"(",
"new",
"Path",
"(",
"mdOutputPath",
",",
"partition",
")",
",",
"metadataFilename",
")",
")",
";",
"}",
"}",
"}",
"}"
] | Merge all of the metadata output from each work-unit and publish the merged record.
@param states States from all tasks
@throws IOException If there is an error publishing the file | [
"Merge",
"all",
"of",
"the",
"metadata",
"output",
"from",
"each",
"work",
"-",
"unit",
"and",
"publish",
"the",
"merged",
"record",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/publisher/BaseDataPublisher.java#L539-L576 |
25,695 | apache/incubator-gobblin | gobblin-core/src/main/java/org/apache/gobblin/publisher/BaseDataPublisher.java | BaseDataPublisher.publishMetadata | private void publishMetadata(String metadataValue, int branchId, Path metadataOutputPath)
throws IOException {
try {
if (metadataOutputPath == null) {
LOG.info("Metadata output path not set for branch " + String.valueOf(branchId) + ", not publishing.");
return;
}
if (metadataValue == null) {
LOG.info("No metadata collected for branch " + String.valueOf(branchId) + ", not publishing.");
return;
}
FileSystem fs = this.metaDataWriterFileSystemByBranches.get(branchId);
if (!fs.exists(metadataOutputPath.getParent())) {
WriterUtils.mkdirsWithRecursivePermissionWithRetry(fs, metadataOutputPath, this.permissions.get(branchId), retrierConfig);
}
//Delete the file if metadata already exists
if (fs.exists(metadataOutputPath)) {
HadoopUtils.deletePath(fs, metadataOutputPath, false);
}
LOG.info("Writing metadata for branch " + String.valueOf(branchId) + " to " + metadataOutputPath.toString());
try (FSDataOutputStream outputStream = fs.create(metadataOutputPath)) {
outputStream.write(metadataValue.getBytes(StandardCharsets.UTF_8));
}
} catch (IOException e) {
LOG.error("Metadata file is not generated: " + e, e);
}
} | java | private void publishMetadata(String metadataValue, int branchId, Path metadataOutputPath)
throws IOException {
try {
if (metadataOutputPath == null) {
LOG.info("Metadata output path not set for branch " + String.valueOf(branchId) + ", not publishing.");
return;
}
if (metadataValue == null) {
LOG.info("No metadata collected for branch " + String.valueOf(branchId) + ", not publishing.");
return;
}
FileSystem fs = this.metaDataWriterFileSystemByBranches.get(branchId);
if (!fs.exists(metadataOutputPath.getParent())) {
WriterUtils.mkdirsWithRecursivePermissionWithRetry(fs, metadataOutputPath, this.permissions.get(branchId), retrierConfig);
}
//Delete the file if metadata already exists
if (fs.exists(metadataOutputPath)) {
HadoopUtils.deletePath(fs, metadataOutputPath, false);
}
LOG.info("Writing metadata for branch " + String.valueOf(branchId) + " to " + metadataOutputPath.toString());
try (FSDataOutputStream outputStream = fs.create(metadataOutputPath)) {
outputStream.write(metadataValue.getBytes(StandardCharsets.UTF_8));
}
} catch (IOException e) {
LOG.error("Metadata file is not generated: " + e, e);
}
} | [
"private",
"void",
"publishMetadata",
"(",
"String",
"metadataValue",
",",
"int",
"branchId",
",",
"Path",
"metadataOutputPath",
")",
"throws",
"IOException",
"{",
"try",
"{",
"if",
"(",
"metadataOutputPath",
"==",
"null",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Metadata output path not set for branch \"",
"+",
"String",
".",
"valueOf",
"(",
"branchId",
")",
"+",
"\", not publishing.\"",
")",
";",
"return",
";",
"}",
"if",
"(",
"metadataValue",
"==",
"null",
")",
"{",
"LOG",
".",
"info",
"(",
"\"No metadata collected for branch \"",
"+",
"String",
".",
"valueOf",
"(",
"branchId",
")",
"+",
"\", not publishing.\"",
")",
";",
"return",
";",
"}",
"FileSystem",
"fs",
"=",
"this",
".",
"metaDataWriterFileSystemByBranches",
".",
"get",
"(",
"branchId",
")",
";",
"if",
"(",
"!",
"fs",
".",
"exists",
"(",
"metadataOutputPath",
".",
"getParent",
"(",
")",
")",
")",
"{",
"WriterUtils",
".",
"mkdirsWithRecursivePermissionWithRetry",
"(",
"fs",
",",
"metadataOutputPath",
",",
"this",
".",
"permissions",
".",
"get",
"(",
"branchId",
")",
",",
"retrierConfig",
")",
";",
"}",
"//Delete the file if metadata already exists",
"if",
"(",
"fs",
".",
"exists",
"(",
"metadataOutputPath",
")",
")",
"{",
"HadoopUtils",
".",
"deletePath",
"(",
"fs",
",",
"metadataOutputPath",
",",
"false",
")",
";",
"}",
"LOG",
".",
"info",
"(",
"\"Writing metadata for branch \"",
"+",
"String",
".",
"valueOf",
"(",
"branchId",
")",
"+",
"\" to \"",
"+",
"metadataOutputPath",
".",
"toString",
"(",
")",
")",
";",
"try",
"(",
"FSDataOutputStream",
"outputStream",
"=",
"fs",
".",
"create",
"(",
"metadataOutputPath",
")",
")",
"{",
"outputStream",
".",
"write",
"(",
"metadataValue",
".",
"getBytes",
"(",
"StandardCharsets",
".",
"UTF_8",
")",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Metadata file is not generated: \"",
"+",
"e",
",",
"e",
")",
";",
"}",
"}"
] | Publish metadata to a set of paths | [
"Publish",
"metadata",
"to",
"a",
"set",
"of",
"paths"
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/publisher/BaseDataPublisher.java#L661-L691 |
25,696 | apache/incubator-gobblin | gobblin-config-management/gobblin-config-client/src/main/java/org/apache/gobblin/config/client/ConfigClient.java | ConfigClient.getImports | public Collection<URI> getImports(URI configKeyUri, boolean recursive)
throws ConfigStoreFactoryDoesNotExistsException, ConfigStoreCreationException, VersionDoesNotExistException {
return getImports(configKeyUri, recursive, Optional.<Config>absent());
} | java | public Collection<URI> getImports(URI configKeyUri, boolean recursive)
throws ConfigStoreFactoryDoesNotExistsException, ConfigStoreCreationException, VersionDoesNotExistException {
return getImports(configKeyUri, recursive, Optional.<Config>absent());
} | [
"public",
"Collection",
"<",
"URI",
">",
"getImports",
"(",
"URI",
"configKeyUri",
",",
"boolean",
"recursive",
")",
"throws",
"ConfigStoreFactoryDoesNotExistsException",
",",
"ConfigStoreCreationException",
",",
"VersionDoesNotExistException",
"{",
"return",
"getImports",
"(",
"configKeyUri",
",",
"recursive",
",",
"Optional",
".",
"<",
"Config",
">",
"absent",
"(",
")",
")",
";",
"}"
] | Get the import links of the input URI.
@param configKeyUri - The URI for the configuration key.
@param recursive - Specify whether to get direct import links or recursively import links
@return the import links of the input URI.
@throws ConfigStoreFactoryDoesNotExistsException: if missing scheme name or the scheme name is invalid
@throws ConfigStoreCreationException: Specified {@link ConfigStoreFactory} can not create required {@link ConfigStore}
@throws VersionDoesNotExistException: Required version does not exist anymore ( may get deleted by retention job ) | [
"Get",
"the",
"import",
"links",
"of",
"the",
"input",
"URI",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-config-management/gobblin-config-client/src/main/java/org/apache/gobblin/config/client/ConfigClient.java#L222-L225 |
25,697 | apache/incubator-gobblin | gobblin-config-management/gobblin-config-client/src/main/java/org/apache/gobblin/config/client/ConfigClient.java | ConfigClient.getConfigStoreFactory | @SuppressWarnings("unchecked")
private ConfigStoreFactory<ConfigStore> getConfigStoreFactory(URI configKeyUri)
throws ConfigStoreFactoryDoesNotExistsException {
@SuppressWarnings("rawtypes")
ConfigStoreFactory csf = this.configStoreFactoryRegister.getConfigStoreFactory(configKeyUri.getScheme());
if (csf == null) {
throw new ConfigStoreFactoryDoesNotExistsException(configKeyUri.getScheme(), "scheme name does not exists");
}
return csf;
} | java | @SuppressWarnings("unchecked")
private ConfigStoreFactory<ConfigStore> getConfigStoreFactory(URI configKeyUri)
throws ConfigStoreFactoryDoesNotExistsException {
@SuppressWarnings("rawtypes")
ConfigStoreFactory csf = this.configStoreFactoryRegister.getConfigStoreFactory(configKeyUri.getScheme());
if (csf == null) {
throw new ConfigStoreFactoryDoesNotExistsException(configKeyUri.getScheme(), "scheme name does not exists");
}
return csf;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"ConfigStoreFactory",
"<",
"ConfigStore",
">",
"getConfigStoreFactory",
"(",
"URI",
"configKeyUri",
")",
"throws",
"ConfigStoreFactoryDoesNotExistsException",
"{",
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"ConfigStoreFactory",
"csf",
"=",
"this",
".",
"configStoreFactoryRegister",
".",
"getConfigStoreFactory",
"(",
"configKeyUri",
".",
"getScheme",
"(",
")",
")",
";",
"if",
"(",
"csf",
"==",
"null",
")",
"{",
"throw",
"new",
"ConfigStoreFactoryDoesNotExistsException",
"(",
"configKeyUri",
".",
"getScheme",
"(",
")",
",",
"\"scheme name does not exists\"",
")",
";",
"}",
"return",
"csf",
";",
"}"
] | use serviceLoader to load configStoreFactories | [
"use",
"serviceLoader",
"to",
"load",
"configStoreFactories"
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-config-management/gobblin-config-client/src/main/java/org/apache/gobblin/config/client/ConfigClient.java#L379-L389 |
25,698 | apache/incubator-gobblin | gobblin-runtime/src/main/java/org/apache/gobblin/runtime/util/MultiWorkUnitUnpackingIterator.java | MultiWorkUnitUnpackingIterator.seekNext | private void seekNext() {
if (!needSeek) {
return;
}
// First, iterate all
if (this.currentIterator != null && this.currentIterator.hasNext()) {
needSeek = false;
return;
}
// Then, find the next available work unit
nextWu = null;
this.currentIterator = null;
while (nextWu == null && workUnits.hasNext()) {
nextWu = workUnits.next();
if (nextWu instanceof MultiWorkUnit) {
this.currentIterator = ((MultiWorkUnit) nextWu).getWorkUnits().iterator();
if (!this.currentIterator.hasNext()) {
nextWu = null;
}
}
}
needSeek = false;
} | java | private void seekNext() {
if (!needSeek) {
return;
}
// First, iterate all
if (this.currentIterator != null && this.currentIterator.hasNext()) {
needSeek = false;
return;
}
// Then, find the next available work unit
nextWu = null;
this.currentIterator = null;
while (nextWu == null && workUnits.hasNext()) {
nextWu = workUnits.next();
if (nextWu instanceof MultiWorkUnit) {
this.currentIterator = ((MultiWorkUnit) nextWu).getWorkUnits().iterator();
if (!this.currentIterator.hasNext()) {
nextWu = null;
}
}
}
needSeek = false;
} | [
"private",
"void",
"seekNext",
"(",
")",
"{",
"if",
"(",
"!",
"needSeek",
")",
"{",
"return",
";",
"}",
"// First, iterate all",
"if",
"(",
"this",
".",
"currentIterator",
"!=",
"null",
"&&",
"this",
".",
"currentIterator",
".",
"hasNext",
"(",
")",
")",
"{",
"needSeek",
"=",
"false",
";",
"return",
";",
"}",
"// Then, find the next available work unit",
"nextWu",
"=",
"null",
";",
"this",
".",
"currentIterator",
"=",
"null",
";",
"while",
"(",
"nextWu",
"==",
"null",
"&&",
"workUnits",
".",
"hasNext",
"(",
")",
")",
"{",
"nextWu",
"=",
"workUnits",
".",
"next",
"(",
")",
";",
"if",
"(",
"nextWu",
"instanceof",
"MultiWorkUnit",
")",
"{",
"this",
".",
"currentIterator",
"=",
"(",
"(",
"MultiWorkUnit",
")",
"nextWu",
")",
".",
"getWorkUnits",
"(",
")",
".",
"iterator",
"(",
")",
";",
"if",
"(",
"!",
"this",
".",
"currentIterator",
".",
"hasNext",
"(",
")",
")",
"{",
"nextWu",
"=",
"null",
";",
"}",
"}",
"}",
"needSeek",
"=",
"false",
";",
"}"
] | Seek to the next available work unit, skipping all empty work units | [
"Seek",
"to",
"the",
"next",
"available",
"work",
"unit",
"skipping",
"all",
"empty",
"work",
"units"
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/util/MultiWorkUnitUnpackingIterator.java#L62-L87 |
25,699 | apache/incubator-gobblin | gobblin-data-management/src/main/java/org/apache/gobblin/data/management/retention/dataset/MultiVersionCleanableDatasetBase.java | MultiVersionCleanableDatasetBase.clean | @Override
public void clean() throws IOException {
if (this.isDatasetBlacklisted) {
this.log.info("Dataset blacklisted. Cleanup skipped for " + datasetRoot());
return;
}
boolean atLeastOneFailureSeen = false;
for (VersionFinderAndPolicy<T> versionFinderAndPolicy : getVersionFindersAndPolicies()) {
VersionSelectionPolicy<T> selectionPolicy = versionFinderAndPolicy.getVersionSelectionPolicy();
VersionFinder<? extends T> versionFinder = versionFinderAndPolicy.getVersionFinder();
if (!selectionPolicy.versionClass().isAssignableFrom(versionFinder.versionClass())) {
throw new IOException("Incompatible dataset version classes.");
}
this.log.info(String.format("Cleaning dataset %s. Using version finder %s and policy %s", this,
versionFinder.getClass().getName(), selectionPolicy));
List<T> versions = Lists.newArrayList(versionFinder.findDatasetVersions(this));
if (versions.isEmpty()) {
this.log.warn("No dataset version can be found. Ignoring.");
continue;
}
Collections.sort(versions, Collections.reverseOrder());
Collection<T> deletableVersions = selectionPolicy.listSelectedVersions(versions);
cleanImpl(deletableVersions);
List<DatasetVersion> allVersions = Lists.newArrayList();
for (T ver : versions) {
allVersions.add(ver);
}
for (RetentionAction retentionAction : versionFinderAndPolicy.getRetentionActions()) {
try {
retentionAction.execute(allVersions);
} catch (Throwable t) {
atLeastOneFailureSeen = true;
log.error(String.format("RetentionAction %s failed for dataset %s", retentionAction.getClass().getName(),
this.datasetRoot()), t);
}
}
}
if (atLeastOneFailureSeen) {
throw new RuntimeException(String.format(
"At least one failure happened while processing %s. Look for previous logs for failures", datasetRoot()));
}
} | java | @Override
public void clean() throws IOException {
if (this.isDatasetBlacklisted) {
this.log.info("Dataset blacklisted. Cleanup skipped for " + datasetRoot());
return;
}
boolean atLeastOneFailureSeen = false;
for (VersionFinderAndPolicy<T> versionFinderAndPolicy : getVersionFindersAndPolicies()) {
VersionSelectionPolicy<T> selectionPolicy = versionFinderAndPolicy.getVersionSelectionPolicy();
VersionFinder<? extends T> versionFinder = versionFinderAndPolicy.getVersionFinder();
if (!selectionPolicy.versionClass().isAssignableFrom(versionFinder.versionClass())) {
throw new IOException("Incompatible dataset version classes.");
}
this.log.info(String.format("Cleaning dataset %s. Using version finder %s and policy %s", this,
versionFinder.getClass().getName(), selectionPolicy));
List<T> versions = Lists.newArrayList(versionFinder.findDatasetVersions(this));
if (versions.isEmpty()) {
this.log.warn("No dataset version can be found. Ignoring.");
continue;
}
Collections.sort(versions, Collections.reverseOrder());
Collection<T> deletableVersions = selectionPolicy.listSelectedVersions(versions);
cleanImpl(deletableVersions);
List<DatasetVersion> allVersions = Lists.newArrayList();
for (T ver : versions) {
allVersions.add(ver);
}
for (RetentionAction retentionAction : versionFinderAndPolicy.getRetentionActions()) {
try {
retentionAction.execute(allVersions);
} catch (Throwable t) {
atLeastOneFailureSeen = true;
log.error(String.format("RetentionAction %s failed for dataset %s", retentionAction.getClass().getName(),
this.datasetRoot()), t);
}
}
}
if (atLeastOneFailureSeen) {
throw new RuntimeException(String.format(
"At least one failure happened while processing %s. Look for previous logs for failures", datasetRoot()));
}
} | [
"@",
"Override",
"public",
"void",
"clean",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"this",
".",
"isDatasetBlacklisted",
")",
"{",
"this",
".",
"log",
".",
"info",
"(",
"\"Dataset blacklisted. Cleanup skipped for \"",
"+",
"datasetRoot",
"(",
")",
")",
";",
"return",
";",
"}",
"boolean",
"atLeastOneFailureSeen",
"=",
"false",
";",
"for",
"(",
"VersionFinderAndPolicy",
"<",
"T",
">",
"versionFinderAndPolicy",
":",
"getVersionFindersAndPolicies",
"(",
")",
")",
"{",
"VersionSelectionPolicy",
"<",
"T",
">",
"selectionPolicy",
"=",
"versionFinderAndPolicy",
".",
"getVersionSelectionPolicy",
"(",
")",
";",
"VersionFinder",
"<",
"?",
"extends",
"T",
">",
"versionFinder",
"=",
"versionFinderAndPolicy",
".",
"getVersionFinder",
"(",
")",
";",
"if",
"(",
"!",
"selectionPolicy",
".",
"versionClass",
"(",
")",
".",
"isAssignableFrom",
"(",
"versionFinder",
".",
"versionClass",
"(",
")",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Incompatible dataset version classes.\"",
")",
";",
"}",
"this",
".",
"log",
".",
"info",
"(",
"String",
".",
"format",
"(",
"\"Cleaning dataset %s. Using version finder %s and policy %s\"",
",",
"this",
",",
"versionFinder",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
",",
"selectionPolicy",
")",
")",
";",
"List",
"<",
"T",
">",
"versions",
"=",
"Lists",
".",
"newArrayList",
"(",
"versionFinder",
".",
"findDatasetVersions",
"(",
"this",
")",
")",
";",
"if",
"(",
"versions",
".",
"isEmpty",
"(",
")",
")",
"{",
"this",
".",
"log",
".",
"warn",
"(",
"\"No dataset version can be found. Ignoring.\"",
")",
";",
"continue",
";",
"}",
"Collections",
".",
"sort",
"(",
"versions",
",",
"Collections",
".",
"reverseOrder",
"(",
")",
")",
";",
"Collection",
"<",
"T",
">",
"deletableVersions",
"=",
"selectionPolicy",
".",
"listSelectedVersions",
"(",
"versions",
")",
";",
"cleanImpl",
"(",
"deletableVersions",
")",
";",
"List",
"<",
"DatasetVersion",
">",
"allVersions",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
"for",
"(",
"T",
"ver",
":",
"versions",
")",
"{",
"allVersions",
".",
"add",
"(",
"ver",
")",
";",
"}",
"for",
"(",
"RetentionAction",
"retentionAction",
":",
"versionFinderAndPolicy",
".",
"getRetentionActions",
"(",
")",
")",
"{",
"try",
"{",
"retentionAction",
".",
"execute",
"(",
"allVersions",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"atLeastOneFailureSeen",
"=",
"true",
";",
"log",
".",
"error",
"(",
"String",
".",
"format",
"(",
"\"RetentionAction %s failed for dataset %s\"",
",",
"retentionAction",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
",",
"this",
".",
"datasetRoot",
"(",
")",
")",
",",
"t",
")",
";",
"}",
"}",
"}",
"if",
"(",
"atLeastOneFailureSeen",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"String",
".",
"format",
"(",
"\"At least one failure happened while processing %s. Look for previous logs for failures\"",
",",
"datasetRoot",
"(",
")",
")",
")",
";",
"}",
"}"
] | Method to perform the Retention operations for this dataset.
<ul>
<li>{@link MultiVersionCleanableDatasetBase#getVersionFindersAndPolicies()} gets a list {@link VersionFinderAndPolicy}s
<li>Each {@link VersionFinderAndPolicy} contains a {@link VersionFinder} and a {@link VersionSelectionPolicy}. It can
optionally have a {@link RetentionAction}
<li>The {@link MultiVersionCleanableDatasetBase#clean()} method finds all the {@link FileSystemDatasetVersion}s using
{@link VersionFinderAndPolicy#versionFinder}
<li> It gets the deletable {@link FileSystemDatasetVersion}s by applying {@link VersionFinderAndPolicy#versionSelectionPolicy}.
These deletable version are deleted and then deletes empty parent directories.
<li>If additional retention actions are available at {@link VersionFinderAndPolicy#getRetentionActions()}, all versions
found by the {@link VersionFinderAndPolicy#versionFinder} are passed to {@link RetentionAction#execute(List)} for
each {@link RetentionAction}
</ul> | [
"Method",
"to",
"perform",
"the",
"Retention",
"operations",
"for",
"this",
"dataset",
"."
] | f029b4c0fea0fe4aa62f36dda2512344ff708bae | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/retention/dataset/MultiVersionCleanableDatasetBase.java#L257-L311 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.